'use strict';

var chunk7Z3M6OQQ_cjs = require('./chunk-7Z3M6OQQ.cjs');
var chunkIYTJBWRE_cjs = require('./chunk-IYTJBWRE.cjs');
var chunkQ2RX2PCI_cjs = require('./chunk-Q2RX2PCI.cjs');
var chunkBNXCMVRQ_cjs = require('./chunk-BNXCMVRQ.cjs');
var chunk3ZX4WMIX_cjs = require('./chunk-3ZX4WMIX.cjs');
var chunkD5HE46WD_cjs = require('./chunk-D5HE46WD.cjs');
var chunk4UERBOUH_cjs = require('./chunk-4UERBOUH.cjs');
var chunkAF3E2D32_cjs = require('./chunk-AF3E2D32.cjs');
var types = require('@storm-software/config-tools/types');
var readFile = require('@stryke/fs/read-file');
var removeFile = require('@stryke/fs/remove-file');
var hashFiles = require('@stryke/hash/hash-files');
var exists = require('@stryke/path/exists');
var joinPaths = require('@stryke/path/join-paths');
var nanoidClient = require('@stryke/unique-id/nanoid-client');
var isString = require('@stryke/type-checks/is-string');
var isUndefined = require('@stryke/type-checks/is-undefined');
var defu = require('defu');
var loadEnv$1 = require('@stryke/env/load-env');
var c12 = require('c12');
var parseTypeDefinition = require('@stryke/convert/parse-type-definition');
var isObject = require('@stryke/type-checks/is-object');
var isSetString = require('@stryke/type-checks/is-set-string');
var hash = require('@stryke/hash/hash');
var superdiff = require('@donedeal0/superdiff');
var packageFns = require('@stryke/fs/package-fns');
var stormJson = require('@stryke/json/storm-json');
var titleCase = require('@stryke/string-format/title-case');
var ts = require('typescript');
var helpers = require('@stryke/fs/helpers');
var throttle = require('@stryke/helpers/throttle');
var index = require('@stryke/path/index');
var unimport = require('unimport');

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

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

async function initContext(log, context, hooks) {
  log(types.LogLevelLabel.TRACE, `Initializing the context for the Storm Stack project.`);
  const packageJsonPath = joinPaths.joinPaths(context.options.projectRoot, "package.json");
  if (!exists.existsSync(packageJsonPath)) {
    throw new Error(`Cannot find a \`package.json\` configuration file in ${context.options.projectRoot}.`);
  }
  context.packageJson = await readFile.readJsonFile(packageJsonPath);
  context.options.name ??= context.packageJson?.name;
  const projectJsonPath = joinPaths.joinPaths(context.options.projectRoot, "project.json");
  if (exists.existsSync(projectJsonPath)) {
    context.projectJson = await readFile.readJsonFile(projectJsonPath);
    context.options.projectType ??= context.projectJson?.projectType;
    context.options.name ??= context.projectJson?.name;
    if (context.options.name?.startsWith("@") && context.options.name.split("/").filter(Boolean).length > 1) {
      context.options.name = context.options.name.split("/").filter(Boolean)[1];
    }
  }
  const checksum = await hashFiles.hashDirectory(context.options.projectRoot, {
    ignore: [
      "node_modules",
      ".git",
      ".nx",
      ".cache",
      ".storm",
      "tmp"
    ]
  });
  context.meta ??= {
    buildId: nanoidClient.nanoid(24),
    releaseId: nanoidClient.nanoid(24),
    checksum,
    timestamp: Date.now()
  };
  context.artifactsDir ??= ".storm";
  const metaFilePath = joinPaths.joinPaths(context.options.projectRoot, context.artifactsDir, "meta.json");
  try {
    if (exists.existsSync(metaFilePath)) {
      context.persistedMeta = await readFile.readJsonFile(metaFilePath);
    }
  } catch {
    context.persistedMeta = void 0;
    await removeFile.removeFile(metaFilePath);
  }
  await hooks.callHook("init:context", context).catch((error) => {
    log(types.LogLevelLabel.ERROR, `An error occurred while initializing the context for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occurred while initializing the context for the Storm Stack project", {
      cause: error
    });
  });
}
chunkAF3E2D32_cjs.__name(initContext, "initContext");
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 chunk7Z3M6OQQ_cjs.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 chunkIYTJBWRE_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 chunkIYTJBWRE_cjs.reflectType(context, {
      file,
      name
    });
    vars = (void 0)(varsType);
  }
  const defaultVarsType = await chunkIYTJBWRE_cjs.reflectType(context, chunkD5HE46WD_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: `${chunkD5HE46WD_cjs.getDotenvDefaultTypeDefinition(context).file}#${chunkD5HE46WD_cjs.getDotenvDefaultTypeDefinition(context).name}`
  };
  if (!context.options.dotenv?.types) {
    log(types.LogLevelLabel.WARN, "No environment variable type definitions were provided in the `dotenv.types` configuration.");
  } else {
    params = isObject.isObject(context.options.dotenv.types) ? context.options.dotenv.types : {
      variables: `${context.options.dotenv.types}#Variables`,
      secrets: `${context.options.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.options.projectRoot, result.variables.typeDefinition.file))) {
      result.variables.reflection = await reflectDotenvVariables(log, context, joinPaths.joinPaths(context.options.projectRoot, 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.options.projectRoot, result.secrets.typeDefinition.file))) {
      result.secrets.reflection = await reflectDotenvSecrets(log, context, joinPaths.joinPaths(context.options.projectRoot, 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");

// src/init/dotenv/index.ts
async function initDotenv(log, context, hooks) {
  log(types.LogLevelLabel.TRACE, `Initializing the context for the Storm Stack project.`);
  context.dotenv ??= {};
  context.dotenv.types = await reflectDotenvTypes(log, context);
  context.dotenv.additionalFiles = context.dotenv?.additionalFiles ?? [];
  context.dotenv.replace = Boolean(context.dotenv?.replace ?? context.options.projectType === "application");
  const env = defu__default.default(await loadEnv(context.options, context.dotenv, context.envPaths.cache, context.envPaths.config, context.packageJson, context.workspaceConfig), {
    APP_NAME: context.options.name || context.packageJson.name?.replace(`/${context.workspaceConfig.namespace}`, ""),
    APP_VERSION: context.packageJson.version,
    BUILD_ID: context.meta.buildId,
    BUILD_TIMESTAMP: context.meta.timestamp,
    BUILD_CHECKSUM: context.meta.checksum,
    RELEASE_ID: context.meta.releaseId,
    RELEASE_TAG: `${context.options.name}@${context.packageJson.version}`,
    MODE: context.options.mode,
    ORG: context.workspaceConfig.organization,
    ORGANIZATION: context.workspaceConfig.organization,
    PLATFORM: context.options.platform,
    STACKTRACE: context.options.mode === "development",
    ENVIRONMENT: context.options.mode,
    DEVELOPMENT: context.options.mode === "development",
    STAGING: context.options.mode === "staging",
    PRODUCTION: context.options.mode === "production",
    DEBUG: context.options.mode === "development"
  });
  context.dotenv.values = Object.keys(env).reduce((ret, key) => {
    let value = env[key];
    if (isString.isString(value)) {
      value = `"${value.replaceAll('"', "")}"`;
    } else if (!isUndefined.isUndefined(value)) {
      value = String(value);
    }
    ret[key.replaceAll("(", "").replaceAll(")", "")] = value;
    return ret;
  }, env);
  await hooks.callHook("init:dotenv", context).catch((error) => {
    log(types.LogLevelLabel.ERROR, `An error occurred while initializing the dotenv configuration for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occurred while initializing the dotenv configuration for the Storm Stack project", {
      cause: error
    });
  });
}
chunkAF3E2D32_cjs.__name(initDotenv, "initDotenv");
function resolveEntry(options, entry) {
  const parsed = parseTypeDefinition.parseTypeDefinition(entry);
  const entryFile = parsed.file.replace(options.options.projectRoot, "").replaceAll("\\", "/").replaceAll(/^(?:\.\/)*/g, "");
  return {
    file: joinPaths.joinPaths(options.options.projectRoot, options.artifactsDir, `entry-${hash.hash({
      file: entryFile,
      name: parsed.name
    }, {
      maxLength: 24
    }).replaceAll("-", "0").replaceAll("_", "1")}.ts`),
    name: parsed.name
  };
}
chunkAF3E2D32_cjs.__name(resolveEntry, "resolveEntry");

// src/init/entry/index.ts
async function initEntry(log, context, hooks) {
  log(types.LogLevelLabel.TRACE, `Initializing the entry points for the Storm Stack project.`);
  if (context.options.projectType === "application" && context.options.entry) {
    if (isSetString.isSetString(context.options.entry)) {
      context.entry = [
        {
          ...resolveEntry(context, context.options.entry),
          input: parseTypeDefinition.parseTypeDefinition(context.options.entry)
        }
      ];
    } else if (Array.isArray(context.options.entry) && context.options.entry.filter(Boolean).length > 0) {
      context.entry = context.options.entry.map((entry) => ({
        ...resolveEntry(context, entry),
        input: parseTypeDefinition.parseTypeDefinition(entry)
      })).filter(Boolean);
    }
  }
  await hooks.callHook("init:entry", context).catch((error) => {
    log(types.LogLevelLabel.ERROR, `An error occurred while initializing the entry points for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occurred while initializing the entry points for the Storm Stack project", {
      cause: error
    });
  });
}
chunkAF3E2D32_cjs.__name(initEntry, "initEntry");

// src/init/installs/node.ts
function getNodeDeps(context) {
  const result = {
    "@types/node": "devDependency"
  };
  if (context.options.projectType === "application") {
    result["@stryke/env"] = "dependency";
    result.unctx = "dependency";
  }
  return result;
}
chunkAF3E2D32_cjs.__name(getNodeDeps, "getNodeDeps");

// src/init/installs/shared.ts
function getSharedDeps(context) {
  const result = {
    "@stryke/types": "devDependency",
    "@storm-stack/types": "devDependency"
  };
  if (context.options.projectType === "application") {
    result["@stryke/type-checks"] = "dependency";
    result["@stryke/json"] = "dependency";
    result["@stryke/url"] = "dependency";
    result["@stryke/http"] = "dependency";
    result.unstorage = "dependency";
  }
  return result;
}
chunkAF3E2D32_cjs.__name(getSharedDeps, "getSharedDeps");

// src/init/installs/index.ts
async function initInstalls(log, context, hooks) {
  log(types.LogLevelLabel.TRACE, `Checking and installing missing project dependencies.`);
  context.installs = getSharedDeps(context);
  if (context.options.platform === "node") {
    const installs = getNodeDeps(context);
    context.installs = Object.keys(installs).reduce((ret, key) => {
      if (installs[key] && ret[key] !== "dependency") {
        ret[key] = installs[key];
      }
      return ret;
    }, context.installs);
  }
  await hooks.callHook("init:installs", context).catch((error) => {
    log(types.LogLevelLabel.ERROR, `An error occured while installing project dependencies: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while installing project dependencies", {
      cause: error
    });
  });
  log(types.LogLevelLabel.TRACE, `The following packages must be installed as dependencies: ${Object.keys(context.installs).map((key) => `${key} (${context.installs[key]})`).join(", ")}`);
  for (const [key, value] of Object.entries(context.installs)) {
    await chunk3ZX4WMIX_cjs.installPackage(log, context, key, value === "devDependency");
  }
}
chunkAF3E2D32_cjs.__name(initInstalls, "initInstalls");
async function getTsconfigChanges(context) {
  const tsconfig = await chunkQ2RX2PCI_cjs.getParsedTypeScriptConfig(context);
  const tsconfigJson = await readFile.readJsonFile(chunkQ2RX2PCI_cjs.getTsconfigFilePath(context));
  tsconfigJson.compilerOptions ??= {};
  if (tsconfigJson.reflection !== true) {
    tsconfigJson.reflection = true;
  }
  if (tsconfig.options.experimentalDecorators !== true) {
    tsconfigJson.compilerOptions.experimentalDecorators = true;
  }
  if (tsconfig.options.emitDecoratorMetadata !== true) {
    tsconfigJson.compilerOptions.emitDecoratorMetadata = true;
  }
  if (!tsconfig.options.lib?.some((lib) => lib.toLowerCase() !== "esnext" && lib.toLowerCase() !== "es2021" && lib.toLowerCase() !== "es2022" && lib.toLowerCase() !== "es2023")) {
    tsconfigJson.compilerOptions.lib ??= [];
    tsconfigJson.compilerOptions.lib.push("esnext");
  }
  if (tsconfig.options.module !== ts__default.default.ModuleKind.ESNext) {
    tsconfigJson.compilerOptions.module = "ESNext";
  }
  if (!tsconfig.options.target || ![
    ts__default.default.ScriptTarget.ESNext,
    ts__default.default.ScriptTarget.ES2024,
    ts__default.default.ScriptTarget.ES2023,
    ts__default.default.ScriptTarget.ES2022,
    ts__default.default.ScriptTarget.ES2021
  ].includes(tsconfig.options.target)) {
    tsconfigJson.compilerOptions.target = "ESNext";
  }
  if (tsconfig.options.moduleResolution !== ts__default.default.ModuleResolutionKind.Bundler) {
    tsconfigJson.compilerOptions.moduleResolution = "Bundler";
  }
  if (tsconfig.options.moduleDetection !== ts__default.default.ModuleDetectionKind.Force) {
    tsconfigJson.compilerOptions.moduleDetection = "force";
  }
  if (tsconfig.options.allowSyntheticDefaultImports !== true) {
    tsconfigJson.compilerOptions.allowSyntheticDefaultImports = true;
  }
  if (tsconfig.options.noImplicitOverride !== true) {
    tsconfigJson.compilerOptions.noImplicitOverride = true;
  }
  if (tsconfig.options.noUncheckedIndexedAccess !== true) {
    tsconfigJson.compilerOptions.noUncheckedIndexedAccess = true;
  }
  if (tsconfig.options.skipLibCheck !== true) {
    tsconfigJson.compilerOptions.skipLibCheck = true;
  }
  if (tsconfig.options.resolveJsonModule !== true) {
    tsconfigJson.compilerOptions.resolveJsonModule = true;
  }
  if (tsconfig.options.isolatedModules !== true) {
    tsconfigJson.compilerOptions.isolatedModules = true;
  }
  if (tsconfig.options.verbatimModuleSyntax !== false) {
    tsconfigJson.compilerOptions.verbatimModuleSyntax = false;
  }
  if (tsconfig.options.allowJs !== true) {
    tsconfigJson.compilerOptions.allowJs = true;
  }
  if (tsconfig.options.esModuleInterop !== true) {
    tsconfigJson.compilerOptions.esModuleInterop = true;
  }
  if (tsconfig.options.declaration !== true) {
    tsconfigJson.compilerOptions.declaration = true;
  }
  if (context.options.platform === "browser") {
    if (tsconfig.options.jsx !== ts__default.default.JsxEmit.ReactJSX) {
      tsconfigJson.compilerOptions.jsx = "react-jsx";
    }
    if (!tsconfig.options.lib?.some((lib) => lib.toLowerCase() !== "dom")) {
      tsconfigJson.compilerOptions.lib ??= [];
      tsconfigJson.compilerOptions.lib.push("dom");
    }
    if (!tsconfig.options.lib?.some((lib) => lib.toLowerCase() !== "dom.iterable")) {
      tsconfigJson.compilerOptions.lib ??= [];
      tsconfigJson.compilerOptions.lib.push("dom.iterable");
    }
  } else if (context.options.platform === "node") {
    if (!tsconfig.options.types?.some((type) => type.toLowerCase() === "node" || type.toLowerCase() === "@types/node")) {
      tsconfigJson.compilerOptions.types ??= [];
      tsconfigJson.compilerOptions.types.push("node");
    }
  }
  return tsconfigJson;
}
chunkAF3E2D32_cjs.__name(getTsconfigChanges, "getTsconfigChanges");

// src/init/tsconfig/index.ts
async function initTsconfig(log, context, hooks) {
  log(types.LogLevelLabel.TRACE, "Initializing TypeScript configuration for the Storm Stack project.");
  if (!packageFns.isPackageExists("typescript")) {
    throw new Error('The TypeScript package is not installed. Please install the package using the command: "npm install typescript --save-dev"');
  }
  const originalTsconfigJson = await readFile.readJsonFile(context.options.tsconfig);
  const json = await getTsconfigChanges(context);
  if (!json.include?.some((filterPattern) => filterPattern.includes(joinPaths.joinPaths(context.artifactsDir, "**/*.ts")))) {
    json.include ??= [];
    json.include.push(joinPaths.joinPaths(context.artifactsDir, "**/*.ts"));
  }
  await chunk4UERBOUH_cjs.writeFile(log, context.options.tsconfig, stormJson.StormJSON.stringify(json));
  await hooks.callHook("init:tsconfig", context).catch((error) => {
    log(types.LogLevelLabel.ERROR, `An error occured while resolving the TypeScript options: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while resolving the TypeScript options", {
      cause: error
    });
  });
  const result = superdiff.getObjectDiff(originalTsconfigJson, await readFile.readJsonFile(context.options.tsconfig), {
    ignoreArrayOrder: true,
    showOnly: {
      statuses: [
        "added",
        "deleted",
        "updated"
      ],
      granularity: "deep"
    }
  });
  const changes = [];
  const getChanges = /* @__PURE__ */ chunkAF3E2D32_cjs.__name((difference, property) => {
    if (difference.status === "added" || difference.status === "deleted" || difference.status === "updated") {
      if (difference.diff) {
        for (const diff of difference.diff) {
          getChanges(diff, property ? `${property}.${difference.property}` : difference.property);
        }
      } else {
        changes.push({
          field: property ? `${property}.${difference.property}` : difference.property,
          status: difference.status,
          previous: difference.status === "added" ? "---" : stormJson.StormJSON.stringify(difference.previousValue),
          current: difference.status === "deleted" ? "---" : stormJson.StormJSON.stringify(difference.currentValue)
        });
      }
    }
  }, "getChanges");
  for (const diff of result.diff) {
    getChanges(diff);
  }
  if (changes.length > 0) {
    log(types.LogLevelLabel.WARN, `Updating the following configuration values in the "tsconfig.json" file:

  ${changes.map((change, i) => `${i + 1}. ${titleCase.titleCase(change.status)} the ${change.field} field:
   - Previous: ${change.previous}
   - Current: ${change.current}
  `).join("\n")}
  `);
  }
  context.tsconfig = await chunkQ2RX2PCI_cjs.getParsedTypeScriptConfig(context);
  if (!context.tsconfig) {
    throw new Error("Failed to parse the TypeScript configuration file.");
  }
}
chunkAF3E2D32_cjs.__name(initTsconfig, "initTsconfig");
var lastImportsDump;
function createUnimport(log, context) {
  log(types.LogLevelLabel.TRACE, "Creating Unimport context with Storm Stack presets");
  const unimport$1 = unimport.createUnimport({
    commentsDisable: [
      "@unimport-disable",
      "@imports-disable",
      "@storm-disable",
      "@storm-ignore"
    ],
    commentsDebug: [
      "@unimport-debug",
      "@imports-debug",
      "@storm-debug"
    ],
    injectAtEnd: true,
    presets: context.unimportPresets
  });
  async function dumpImports() {
    log(types.LogLevelLabel.TRACE, "Dumping import file...");
    const items = await unimport$1.getImports();
    const importDumpFile = index.joinPaths(context.options.projectRoot, context.artifactsDir, "imports-dump.json");
    if (!index.existsSync(index.findFilePath(importDumpFile))) {
      await helpers.createDirectory(index.findFilePath(importDumpFile));
    }
    log(types.LogLevelLabel.TRACE, `Writing imports-dump JSON file: ${importDumpFile}`);
    const content = stormJson.StormJSON.stringify(items);
    if (content.trim() !== lastImportsDump?.trim()) {
      lastImportsDump = content;
      await chunk4UERBOUH_cjs.writeFile(log, importDumpFile, content);
    }
  }
  chunkAF3E2D32_cjs.__name(dumpImports, "dumpImports");
  const dumpImportsThrottled = throttle.throttle(dumpImports, 500);
  async function injectImports(source) {
    const result = await unimport$1.injectImports(source.code, source.id);
    if (!source.code.hasChanged()) {
      return source;
    }
    await dumpImportsThrottled();
    return {
      ...source,
      code: result.s
    };
  }
  chunkAF3E2D32_cjs.__name(injectImports, "injectImports");
  return {
    ...unimport$1,
    dumpImports: dumpImportsThrottled,
    injectImports
  };
}
chunkAF3E2D32_cjs.__name(createUnimport, "createUnimport");

// src/init/unimport/index.ts
async function initUnimport(log, context, hooks) {
  log(types.LogLevelLabel.TRACE, `Initializing Unimport for the Storm Stack project.`);
  const runtimeDir = joinPaths.joinPaths(context.artifactsDir, "runtime");
  context.unimportPresets = [
    {
      imports: [
        "StormJSON"
      ],
      from: "@stryke/json"
    },
    {
      imports: [
        "StormURL"
      ],
      from: "@stryke/url"
    },
    {
      imports: [
        "parseCookie",
        "parseSetCookie",
        "serializeCookie",
        "splitSetCookieString"
      ],
      from: "@stryke/http"
    },
    {
      imports: [
        "StormError",
        "createStormError",
        "isStormError",
        "getErrorFromUnknown"
      ],
      from: joinPaths.joinPaths(runtimeDir, "error")
    },
    {
      imports: [
        "StormRequest"
      ],
      from: joinPaths.joinPaths(runtimeDir, "request")
    },
    {
      imports: [
        "StormResponse"
      ],
      from: joinPaths.joinPaths(runtimeDir, "response")
    },
    {
      imports: [
        "StormLog"
      ],
      from: joinPaths.joinPaths(runtimeDir, "log")
    },
    {
      imports: [
        "uniqueId",
        "getRandom"
      ],
      from: joinPaths.joinPaths(runtimeDir, "id")
    },
    {
      imports: [
        "storage"
      ],
      from: joinPaths.joinPaths(runtimeDir, "storage")
    }
  ];
  if (context.options.platform === "node") {
    context.unimportPresets.push({
      imports: [
        "builder"
      ],
      from: joinPaths.joinPaths(runtimeDir, "app")
    });
    context.unimportPresets.push({
      imports: [
        "envPaths",
        "getBuildInfo",
        "getRuntimeInfo",
        "useStorm",
        "STORM_ASYNC_CONTEXT"
      ].filter(Boolean),
      from: joinPaths.joinPaths(runtimeDir, "context")
    });
    context.unimportPresets.push({
      imports: [
        "StormEvent"
      ],
      from: joinPaths.joinPaths(runtimeDir, "event")
    });
  }
  await hooks.callHook("init:unimport", context).catch((error) => {
    log(types.LogLevelLabel.ERROR, `An error occured while initializing Unimport for the Storm Stack project configuration: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while initializing Unimport for the Storm Stack project configuration", {
      cause: error
    });
  });
  context.unimport = createUnimport(log, context);
  await context.unimport.init();
}
chunkAF3E2D32_cjs.__name(initUnimport, "initUnimport");

// src/init/index.ts
async function init(log, context, hooks) {
  await hooks.callHook("init:begin", context).catch((error) => {
    log(types.LogLevelLabel.ERROR, `An error occured while starting initialization for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while starting initialization for the Storm Stack project", {
      cause: error
    });
  });
  await initContext(log, context, hooks);
  await initInstalls(log, context, hooks);
  await initTsconfig(log, context, hooks);
  await initUnimport(log, context, hooks);
  const handlePreTransform = /* @__PURE__ */ chunkAF3E2D32_cjs.__name(async (context2, sourceFile) => {
    await hooks.callHook("build:pre-transform", context2, sourceFile).catch((error) => {
      log(types.LogLevelLabel.ERROR, `An error occured while pre-transforming the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
      throw new Error("An error occured while pre-transforming the Storm Stack project", {
        cause: error
      });
    });
  }, "handlePreTransform");
  const handleTransform = /* @__PURE__ */ chunkAF3E2D32_cjs.__name(async (context2, sourceFile) => {
    await hooks.callHook("build:transform", context2, sourceFile).catch((error) => {
      log(types.LogLevelLabel.ERROR, `An error occured while transforming the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
      throw new Error("An error occured while transforming the Storm Stack project", {
        cause: error
      });
    });
  }, "handleTransform");
  const handlePostTransform = /* @__PURE__ */ chunkAF3E2D32_cjs.__name(async (context2, sourceFile) => {
    await hooks.callHook("build:post-transform", context2, sourceFile).catch((error) => {
      log(types.LogLevelLabel.ERROR, `An error occured while post-transforming the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
      throw new Error("An error occured while post-transforming the Storm Stack project", {
        cause: error
      });
    });
  }, "handlePostTransform");
  context.compiler = new chunkBNXCMVRQ_cjs.Compiler(context, {
    onPreTransform: handlePreTransform,
    onTransform: handleTransform,
    onPostTransform: handlePostTransform
  });
  await initDotenv(log, context, hooks);
  await initEntry(log, context, hooks);
  await hooks.callHook("init:complete", context).catch((error) => {
    log(types.LogLevelLabel.ERROR, `An error occured while finishing initialization for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while finishing initialization for the Storm Stack project", {
      cause: error
    });
  });
}
chunkAF3E2D32_cjs.__name(init, "init");

exports.init = init;
//# sourceMappingURL=chunk-2VFFME45.cjs.map
//# sourceMappingURL=chunk-2VFFME45.cjs.map