#!/usr/bin/env node
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 __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
));

// src/cli/index.ts
var import_commander = require("commander");

// package.json
var package_default = {
  name: "react-email",
  version: "4.1.0-canary.2",
  description: "A live preview of your emails right in your browser.",
  bin: {
    email: "./dist/cli/index.js"
  },
  scripts: {
    build: "tsup-node && node ./scripts/build-preview-server.mjs && pnpm install --frozen-lockfile",
    "caniemail:fetch": "node ./scripts/fill-caniemail-data.mjs",
    clean: "rm -rf dist",
    dev: "tsup-node --watch",
    "dev:preview": "cd ../../apps/demo && tsx ../../packages/react-email/src/cli/index.ts dev",
    test: "vitest run",
    "test:watch": "vitest"
  },
  license: "MIT",
  repository: {
    type: "git",
    url: "https://github.com/resend/react-email.git",
    directory: "packages/react-email"
  },
  keywords: ["react", "email"],
  engines: {
    node: ">=18.0.0"
  },
  dependencies: {
    "@babel/parser": "^7.24.5",
    "@babel/traverse": "^7.25.6",
    chalk: "^4.1.2",
    chokidar: "^4.0.3",
    commander: "^11.1.0",
    debounce: "^2.0.0",
    esbuild: "^0.25.0",
    glob: "^10.3.4",
    "log-symbols": "^4.1.0",
    "mime-types": "^2.1.35",
    next: "^15.2.4",
    "normalize-path": "^3.0.0",
    ora: "^5.4.1",
    "socket.io": "^4.8.1"
  },
  devDependencies: {
    "@babel/core": "7.26.10",
    "@lottiefiles/dotlottie-react": "0.12.3",
    "@radix-ui/colors": "1.0.1",
    "@radix-ui/react-collapsible": "1.1.0",
    "@radix-ui/react-dropdown-menu": "2.1.4",
    "@radix-ui/react-popover": "1.1.1",
    "@radix-ui/react-slot": "1.1.0",
    "@radix-ui/react-tabs": "1.1.1",
    "@radix-ui/react-toggle-group": "1.1.0",
    "@radix-ui/react-tooltip": "1.1.2",
    "@react-email/components": "workspace:*",
    "@swc/core": "1.4.15",
    "@types/babel__core": "7.20.5",
    "@types/babel__traverse": "*",
    "@types/fs-extra": "11.0.1",
    "@types/mime-types": "2.1.4",
    "@types/node": "22.10.2",
    "@types/normalize-path": "3.0.2",
    "@types/react": "19.0.10",
    "@types/react-dom": "19.0.4",
    "@types/webpack": "5.28.5",
    "@vercel/style-guide": "5.1.0",
    autoprefixer: "10.4.20",
    clsx: "2.1.1",
    "framer-motion": "12.0.0-alpha.2",
    jiti: "2.4.2",
    json5: "2.2.3",
    "module-punycode": "npm:punycode@2.3.1",
    "node-html-parser": "6.1.13",
    postcss: "8.4.40",
    "prettier-plugin-tailwindcss": "0.6.6",
    "pretty-bytes": "6.1.1",
    "prism-react-renderer": "2.1.0",
    react: "19.0.0",
    "react-dom": "19.0.0",
    sharp: "0.33.3",
    "socket.io-client": "4.8.0",
    sonner: "1.7.1",
    "source-map-js": "1.0.2",
    spamc: "0.0.5",
    "stacktrace-parser": "0.1.10",
    "tailwind-merge": "2.2.0",
    tailwindcss: "3.4.0",
    tsup: "7.2.0",
    tsx: "4.9.0",
    typescript: "5.8.2",
    "use-debounce": "10.0.4",
    zod: "3.24.2"
  }
};

// src/cli/commands/build.ts
var import_node_child_process = require("child_process");
var import_node_fs5 = __toESM(require("fs"));
var import_node_path8 = __toESM(require("path"));
var import_log_symbols3 = __toESM(require("log-symbols"));
var import_ora2 = __toESM(require("ora"));

// src/utils/get-emails-directory-metadata.ts
var import_node_fs = __toESM(require("fs"));
var import_node_path = __toESM(require("path"));
var isFileAnEmail = (fullPath) => {
  const stat = import_node_fs.default.statSync(fullPath);
  if (stat.isDirectory())
    return false;
  const { ext } = import_node_path.default.parse(fullPath);
  if (![".js", ".tsx", ".jsx"].includes(ext))
    return false;
  if (!import_node_fs.default.existsSync(fullPath)) {
    return false;
  }
  const fileContents = import_node_fs.default.readFileSync(fullPath, "utf8");
  const hasES6DefaultExport = /\bexport\s+default\b/gm.test(fileContents);
  const hasCommonJSExport = /\bmodule\.exports\s*=/gm.test(fileContents);
  const hasNamedExport = /\bexport\s+\{[^}]*\bdefault\b[^}]*\}/gm.test(
    fileContents
  );
  return hasES6DefaultExport || hasCommonJSExport || hasNamedExport;
};
var mergeDirectoriesWithSubDirectories = (emailsDirectoryMetadata) => {
  let currentResultingMergedDirectory = emailsDirectoryMetadata;
  while (currentResultingMergedDirectory.emailFilenames.length === 0 && currentResultingMergedDirectory.subDirectories.length === 1) {
    const onlySubDirectory = currentResultingMergedDirectory.subDirectories[0];
    currentResultingMergedDirectory = {
      ...onlySubDirectory,
      directoryName: import_node_path.default.join(
        currentResultingMergedDirectory.directoryName,
        onlySubDirectory.directoryName
      )
    };
  }
  return currentResultingMergedDirectory;
};
var getEmailsDirectoryMetadata = async (absolutePathToEmailsDirectory, keepFileExtensions = false, isSubDirectory = false, baseDirectoryPath = absolutePathToEmailsDirectory) => {
  if (!import_node_fs.default.existsSync(absolutePathToEmailsDirectory))
    return;
  const dirents = await import_node_fs.default.promises.readdir(absolutePathToEmailsDirectory, {
    withFileTypes: true
  });
  const emailFilenames = dirents.filter(
    (dirent) => isFileAnEmail(import_node_path.default.join(absolutePathToEmailsDirectory, dirent.name))
  ).map(
    (dirent) => keepFileExtensions ? dirent.name : dirent.name.replace(import_node_path.default.extname(dirent.name), "")
  );
  const subDirectories = await Promise.all(
    dirents.filter(
      (dirent) => dirent.isDirectory() && !dirent.name.startsWith("_") && dirent.name !== "static"
    ).map((dirent) => {
      const direntAbsolutePath = import_node_path.default.join(
        absolutePathToEmailsDirectory,
        dirent.name
      );
      return getEmailsDirectoryMetadata(
        direntAbsolutePath,
        keepFileExtensions,
        true,
        baseDirectoryPath
      );
    })
  );
  const emailsMetadata = {
    absolutePath: absolutePathToEmailsDirectory,
    relativePath: import_node_path.default.relative(
      baseDirectoryPath,
      absolutePathToEmailsDirectory
    ),
    directoryName: absolutePathToEmailsDirectory.split(import_node_path.default.sep).pop(),
    emailFilenames,
    subDirectories
  };
  return isSubDirectory ? mergeDirectoriesWithSubDirectories(emailsMetadata) : emailsMetadata;
};

// src/utils/register-spinner-autostopping.ts
var import_log_symbols = __toESM(require("log-symbols"));
var spinners = /* @__PURE__ */ new Set();
process.on("SIGINT", () => {
  spinners.forEach((spinner) => {
    if (spinner.isSpinning) {
      spinner.stop();
    }
  });
});
process.on("exit", (code) => {
  if (code !== 0) {
    spinners.forEach((spinner) => {
      if (spinner.isSpinning) {
        spinner.stopAndPersist({
          symbol: import_log_symbols.default.error
        });
      }
    });
  }
});
var registerSpinnerAutostopping = (spinner) => {
  spinners.add(spinner);
};

// src/cli/utils/tree.ts
var import_node_fs2 = require("fs");
var import_node_os = __toESM(require("os"));
var import_node_path2 = __toESM(require("path"));
var SYMBOLS = {
  BRANCH: "\u251C\u2500\u2500 ",
  EMPTY: "",
  INDENT: "    ",
  LAST_BRANCH: "\u2514\u2500\u2500 ",
  VERTICAL: "\u2502   "
};
var getTreeLines = async (dirPath, depth, currentDepth = 0) => {
  const base = process.cwd();
  const dirFullpath = import_node_path2.default.resolve(base, dirPath);
  const dirname = import_node_path2.default.basename(dirFullpath);
  let lines = [dirname];
  const dirStat = await import_node_fs2.promises.stat(dirFullpath);
  if (dirStat.isDirectory() && currentDepth < depth) {
    const childDirents = await import_node_fs2.promises.readdir(dirFullpath, { withFileTypes: true });
    childDirents.sort((a, b) => {
      if (a.isDirectory() && b.isFile()) {
        return -1;
      }
      if (a.isFile() && b.isDirectory()) {
        return 1;
      }
      return b.name > a.name ? -1 : 1;
    });
    for (let i = 0; i < childDirents.length; i++) {
      const dirent = childDirents[i];
      const isLast = i === childDirents.length - 1;
      const branchingSymbol = isLast ? SYMBOLS.LAST_BRANCH : SYMBOLS.BRANCH;
      const verticalSymbol = isLast ? SYMBOLS.INDENT : SYMBOLS.VERTICAL;
      if (dirent.isFile()) {
        lines.push(`${branchingSymbol}${dirent.name}`);
      } else {
        const pathToDirectory = import_node_path2.default.join(dirFullpath, dirent.name);
        const treeLinesForSubDirectory = await getTreeLines(
          pathToDirectory,
          depth,
          currentDepth + 1
        );
        lines = lines.concat(
          treeLinesForSubDirectory.map(
            (line, index) => index === 0 ? `${branchingSymbol}${line}` : `${verticalSymbol}${line}`
          )
        );
      }
    }
  }
  return lines;
};
var tree = async (dirPath, depth) => {
  const lines = await getTreeLines(dirPath, depth);
  return lines.join(import_node_os.default.EOL);
};

// src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
var import_node_path7 = __toESM(require("path"));
var import_chokidar = require("chokidar");
var import_debounce = __toESM(require("debounce"));
var import_socket = require("socket.io");

// src/cli/utils/preview/hot-reloading/create-dependency-graph.ts
var import_node_fs4 = require("fs");
var import_node_path6 = __toESM(require("path"));

// src/cli/utils/preview/start-dev-server.ts
var import_node_http = __toESM(require("http"));
var import_node_path5 = __toESM(require("path"));
var import_node_url = __toESM(require("url"));
var import_chalk = __toESM(require("chalk"));
var import_log_symbols2 = __toESM(require("log-symbols"));
var import_next = __toESM(require("next"));
var import_ora = __toESM(require("ora"));

// src/cli/utils/preview/get-env-variables-for-preview-app.ts
var import_node_path3 = __toESM(require("path"));
var getEnvVariablesForPreviewApp = (relativePathToEmailsDirectory, cwd) => {
  return {
    EMAILS_DIR_RELATIVE_PATH: relativePathToEmailsDirectory,
    EMAILS_DIR_ABSOLUTE_PATH: import_node_path3.default.resolve(cwd, relativePathToEmailsDirectory),
    USER_PROJECT_LOCATION: cwd,
    NEXT_PUBLIC_IS_PREVIEW_DEVELOPMENT: isDev ? "true" : "false"
  };
};

// src/cli/utils/preview/serve-static-file.ts
var import_node_fs3 = require("fs");
var import_node_path4 = __toESM(require("path"));
var import_mime_types = require("mime-types");
var serveStaticFile = async (res, parsedUrl, staticDirRelativePath) => {
  const staticBaseDir = import_node_path4.default.join(process.cwd(), staticDirRelativePath);
  const pathname = parsedUrl.pathname;
  const ext = import_node_path4.default.parse(pathname).ext;
  const fileAbsolutePath = import_node_path4.default.join(staticBaseDir, pathname);
  try {
    const fileHandle = await import_node_fs3.promises.open(fileAbsolutePath, "r");
    const fileData = await import_node_fs3.promises.readFile(fileHandle);
    res.setHeader("Content-type", (0, import_mime_types.lookup)(ext) || "text/plain");
    res.end(fileData);
    fileHandle.close();
  } catch (exception) {
    if (!(0, import_node_fs3.existsSync)(fileAbsolutePath)) {
      res.statusCode = 404;
      res.end();
    } else {
      const sanitizedFilePath = fileAbsolutePath.replace(/\n|\r/g, "");
      console.error(
        `Could not read file at ${sanitizedFilePath} to be served, here's the exception:`,
        exception
      );
      res.statusCode = 500;
      res.end(
        "Could not read file to be served! Check your terminal for more information."
      );
    }
  }
};

// src/cli/utils/preview/start-dev-server.ts
var devServer;
var safeAsyncServerListen = (server, port) => {
  return new Promise((resolve) => {
    server.listen(port, () => {
      resolve({ portAlreadyInUse: false });
    });
    server.on("error", (e) => {
      if (e.code === "EADDRINUSE") {
        resolve({ portAlreadyInUse: true });
      }
    });
  });
};
var isDev = !__filename.endsWith(import_node_path5.default.join("cli", "index.js"));
var cliPackageLocation = isDev ? import_node_path5.default.resolve(__dirname, "../../../..") : import_node_path5.default.resolve(__dirname, "../..");
var previewServerLocation = isDev ? import_node_path5.default.resolve(__dirname, "../../../..") : import_node_path5.default.resolve(__dirname, "../preview");
var startDevServer = async (emailsDirRelativePath, staticBaseDirRelativePath, port) => {
  devServer = import_node_http.default.createServer((req, res) => {
    if (!req.url) {
      res.end(404);
      return;
    }
    const parsedUrl = import_node_url.default.parse(req.url, true);
    res.setHeader(
      "Cache-Control",
      "no-cache, max-age=0, must-revalidate, no-store"
    );
    res.setHeader("Pragma", "no-cache");
    res.setHeader("Expires", "-1");
    try {
      if (parsedUrl.path?.includes("static/") && !parsedUrl.path.includes("_next/static/")) {
        void serveStaticFile(res, parsedUrl, staticBaseDirRelativePath);
      } else if (!isNextReady) {
        void nextReadyPromise.then(
          () => nextHandleRequest?.(req, res, parsedUrl)
        );
      } else {
        void nextHandleRequest?.(req, res, parsedUrl);
      }
    } catch (e) {
      console.error("caught error", e);
      res.writeHead(500);
      res.end();
    }
  });
  const { portAlreadyInUse } = await safeAsyncServerListen(devServer, port);
  if (!portAlreadyInUse) {
    console.log(import_chalk.default.greenBright(`    React Email ${package_default.version}`));
    console.log(`    Running preview at:          http://localhost:${port}
`);
  } else {
    const nextPortToTry = port + 1;
    console.warn(
      ` ${import_log_symbols2.default.warning} Port ${port} is already in use, trying ${nextPortToTry}`
    );
    return startDevServer(
      emailsDirRelativePath,
      staticBaseDirRelativePath,
      nextPortToTry
    );
  }
  devServer.on("close", async () => {
    await app.close();
  });
  devServer.on("error", (e) => {
    console.error(
      ` ${import_log_symbols2.default.error} preview server error: `,
      JSON.stringify(e)
    );
    process.exit(1);
  });
  const spinner = (0, import_ora.default)({
    text: "Getting react-email preview server ready...\n",
    prefixText: " "
  }).start();
  registerSpinnerAutostopping(spinner);
  const timeBeforeNextReady = performance.now();
  process.env = {
    NODE_ENV: "development",
    ...process.env,
    ...getEnvVariablesForPreviewApp(
      // If we don't do normalization here, stuff like https://github.com/resend/react-email/issues/1354 happens.
      import_node_path5.default.normalize(emailsDirRelativePath),
      process.cwd()
    )
  };
  const app = (0, import_next.default)({
    // passing in env here does not get the environment variables there
    dev: isDev,
    conf: {
      images: {
        // This is to avoid the warning with sharp
        unoptimized: true
      }
    },
    hostname: "localhost",
    port,
    dir: previewServerLocation
  });
  let isNextReady = false;
  const nextReadyPromise = app.prepare();
  await nextReadyPromise;
  isNextReady = true;
  const nextHandleRequest = app.getRequestHandler();
  const secondsToNextReady = ((performance.now() - timeBeforeNextReady) / 1e3).toFixed(1);
  spinner.stopAndPersist({
    text: `Ready in ${secondsToNextReady}s
`,
    symbol: import_log_symbols2.default.success
  });
  return devServer;
};
var makeExitHandler = (options) => (_codeOrSignal) => {
  if (typeof devServer !== "undefined") {
    console.log("\nshutting down dev server");
    devServer.close();
    devServer = void 0;
  }
  if (options?.shouldKillProcess) {
    process.exit(options.killWithErrorCode ? 1 : 0);
  }
};
process.on("exit", makeExitHandler());
process.on(
  "SIGINT",
  makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
);
process.on(
  "SIGUSR1",
  makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
);
process.on(
  "SIGUSR2",
  makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
);
process.on(
  "uncaughtException",
  makeExitHandler({ shouldKillProcess: true, killWithErrorCode: true })
);

// src/cli/utils/preview/hot-reloading/get-imported-modules.ts
var import_parser = require("@babel/parser");
var import_traverse = __toESM(require("@babel/traverse"));
var getImportedModules = (contents) => {
  const importedPaths = [];
  const parsedContents = (0, import_parser.parse)(contents, {
    sourceType: "unambiguous",
    strictMode: false,
    errorRecovery: true,
    plugins: ["jsx", "typescript", "decorators"]
  });
  (0, import_traverse.default)(parsedContents, {
    ImportDeclaration({ node }) {
      importedPaths.push(node.source.value);
    },
    ExportAllDeclaration({ node }) {
      importedPaths.push(node.source.value);
    },
    ExportNamedDeclaration({ node }) {
      if (node.source) {
        importedPaths.push(node.source.value);
      }
    },
    CallExpression({ node }) {
      if ("name" in node.callee && node.callee.name === "require") {
        if (node.arguments.length === 1) {
          const importPathNode = node.arguments[0];
          if (importPathNode.type === "StringLiteral") {
            importedPaths.push(importPathNode.value);
          }
        }
      }
    }
  });
  return importedPaths;
};

// src/cli/utils/preview/hot-reloading/create-dependency-graph.ts
var readAllFilesInsideDirectory = async (directory) => {
  let allFilePaths = [];
  const topLevelDirents = await import_node_fs4.promises.readdir(directory, { withFileTypes: true });
  for await (const dirent of topLevelDirents) {
    const pathToDirent = import_node_path6.default.join(directory, dirent.name);
    if (dirent.isDirectory()) {
      allFilePaths = allFilePaths.concat(
        await readAllFilesInsideDirectory(pathToDirent)
      );
    } else {
      allFilePaths.push(pathToDirent);
    }
  }
  return allFilePaths;
};
var isJavascriptModule = (filePath) => {
  const extensionName = import_node_path6.default.extname(filePath);
  return [".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs"].includes(extensionName);
};
var checkFileExtensionsUntilItExists = (pathWithoutExtension) => {
  if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.ts`)) {
    return `${pathWithoutExtension}.ts`;
  }
  if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.tsx`)) {
    return `${pathWithoutExtension}.tsx`;
  }
  if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.js`)) {
    return `${pathWithoutExtension}.js`;
  }
  if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.jsx`)) {
    return `${pathWithoutExtension}.jsx`;
  }
  if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.mjs`)) {
    return `${pathWithoutExtension}.mjs`;
  }
  if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.cjs`)) {
    return `${pathWithoutExtension}.cjs`;
  }
};
var createDependencyGraph = async (directory) => {
  const filePaths = await readAllFilesInsideDirectory(directory);
  const modulePaths = filePaths.filter(isJavascriptModule);
  const graph = Object.fromEntries(
    modulePaths.map((path12) => [
      path12,
      {
        path: path12,
        dependencyPaths: [],
        dependentPaths: [],
        moduleDependencies: []
      }
    ])
  );
  const getDependencyPaths = async (filePath) => {
    const contents = await import_node_fs4.promises.readFile(filePath, "utf8");
    const importedPaths = getImportedModules(contents);
    const importedPathsRelativeToDirectory = importedPaths.map(
      (dependencyPath) => {
        const isModulePath = !dependencyPath.startsWith(".");
        if (isModulePath || import_node_path6.default.isAbsolute(dependencyPath)) {
          return dependencyPath;
        }
        let pathToDependencyFromDirectory = import_node_path6.default.resolve(
          /*
                      path.resolve resolves paths differently from what imports on javascript do.
          
                      So if we wouldn't do this, for an email at "/path/to/email.tsx" with a dependecy path of "./other-email" 
                      would end up going into /path/to/email.tsx/other-email instead of /path/to/other-email which is the
                      one the import is meant to go to
                    */
          import_node_path6.default.dirname(filePath),
          dependencyPath
        );
        let isDirectory = false;
        try {
          isDirectory = (0, import_node_fs4.statSync)(pathToDependencyFromDirectory).isDirectory();
        } catch (_) {
        }
        if (isDirectory) {
          const pathToSubDirectory = pathToDependencyFromDirectory;
          const pathWithExtension = checkFileExtensionsUntilItExists(
            `${pathToSubDirectory}/index`
          );
          if (pathWithExtension) {
            pathToDependencyFromDirectory = pathWithExtension;
          } else if (isDev) {
            console.warn(
              `Could not find index file for directory at ${pathToDependencyFromDirectory}. This is probably going to cause issues with both hot reloading and your code.`
            );
          }
        }
        if (!isJavascriptModule(pathToDependencyFromDirectory)) {
          const pathWithExtension = checkFileExtensionsUntilItExists(
            pathToDependencyFromDirectory
          );
          if (pathWithExtension) {
            pathToDependencyFromDirectory = pathWithExtension;
          } else if (isDev) {
            console.warn(
              `Could not determine the file extension for the file at ${pathToDependencyFromDirectory}`
            );
          }
        }
        return pathToDependencyFromDirectory;
      }
    );
    const moduleDependencies = importedPathsRelativeToDirectory.filter(
      (dependencyPath) => !dependencyPath.startsWith(".") && !import_node_path6.default.isAbsolute(dependencyPath)
    );
    const nonNodeModuleImportPathsRelativeToDirectory = importedPathsRelativeToDirectory.filter(
      (dependencyPath) => dependencyPath.startsWith(".") || import_node_path6.default.isAbsolute(dependencyPath)
    );
    return {
      dependencyPaths: nonNodeModuleImportPathsRelativeToDirectory,
      moduleDependencies
    };
  };
  const updateModuleDependenciesInGraph = async (moduleFilePath) => {
    const module2 = graph[moduleFilePath] ?? {
      path: moduleFilePath,
      dependencyPaths: [],
      dependentPaths: [],
      moduleDependencies: []
    };
    const { moduleDependencies, dependencyPaths: newDependencyPaths } = await getDependencyPaths(moduleFilePath);
    module2.moduleDependencies = moduleDependencies;
    for (const dependencyPath of module2.dependencyPaths) {
      if (newDependencyPaths.includes(dependencyPath))
        continue;
      const dependencyModule = graph[dependencyPath];
      if (dependencyModule !== void 0) {
        dependencyModule.dependentPaths = dependencyModule.dependentPaths.filter(
          (dependentPath) => dependentPath !== moduleFilePath
        );
      }
    }
    module2.dependencyPaths = newDependencyPaths;
    for (const dependencyPath of newDependencyPaths) {
      const dependencyModule = graph[dependencyPath];
      if (dependencyModule !== void 0 && !dependencyModule.dependentPaths.includes(moduleFilePath)) {
        dependencyModule.dependentPaths.push(moduleFilePath);
      } else {
        graph[dependencyPath] = {
          path: dependencyPath,
          moduleDependencies: [],
          dependencyPaths: [],
          dependentPaths: [moduleFilePath]
        };
      }
    }
    graph[moduleFilePath] = module2;
  };
  for (const filePath of modulePaths) {
    await updateModuleDependenciesInGraph(filePath);
  }
  const removeModuleFromGraph = (filePath) => {
    const module2 = graph[filePath];
    if (module2) {
      for (const dependencyPath of module2.dependencyPaths) {
        if (graph[dependencyPath]) {
          graph[dependencyPath].dependentPaths = graph[dependencyPath].dependentPaths.filter(
            (dependentPath) => dependentPath !== filePath
          );
        }
      }
      delete graph[filePath];
    }
  };
  return [
    graph,
    async (event, pathToModified) => {
      switch (event) {
        case "change":
          if (isJavascriptModule(pathToModified)) {
            await updateModuleDependenciesInGraph(pathToModified);
          }
          break;
        case "add":
          if (isJavascriptModule(pathToModified)) {
            await updateModuleDependenciesInGraph(pathToModified);
          }
          break;
        case "addDir": {
          const filesInsideAddedDirectory = await readAllFilesInsideDirectory(pathToModified);
          const modulesInsideAddedDirectory = filesInsideAddedDirectory.filter(isJavascriptModule);
          for await (const filePath of modulesInsideAddedDirectory) {
            await updateModuleDependenciesInGraph(filePath);
          }
          break;
        }
        case "unlink":
          if (isJavascriptModule(pathToModified)) {
            removeModuleFromGraph(pathToModified);
          }
          break;
        case "unlinkDir": {
          const filesInsideDeletedDirectory = await readAllFilesInsideDirectory(pathToModified);
          const modulesInsideDeletedDirectory = filesInsideDeletedDirectory.filter(isJavascriptModule);
          for await (const filePath of modulesInsideDeletedDirectory) {
            removeModuleFromGraph(filePath);
          }
          break;
        }
      }
    },
    {
      resolveDependentsOf: function resolveDependentsOf(pathToModule) {
        const moduleEntry = graph[pathToModule];
        const dependentPaths = [];
        if (moduleEntry) {
          for (const dependentPath of moduleEntry.dependentPaths) {
            const dependentsOfDependent = resolveDependentsOf(dependentPath);
            dependentPaths.push(...dependentsOfDependent);
            dependentPaths.push(dependentPath);
          }
        }
        return dependentPaths;
      }
    }
  ];
};

// src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
var setupHotreloading = async (devServer2, emailDirRelativePath) => {
  let clients = [];
  const io = new import_socket.Server(devServer2);
  io.on("connection", (client) => {
    clients.push(client);
    client.on("disconnect", () => {
      clients = clients.filter((item) => item !== client);
    });
  });
  let changes = [];
  const reload = (0, import_debounce.default)(() => {
    clients.forEach((client) => {
      client.emit("reload", changes);
    });
    changes = [];
  }, 150);
  const absolutePathToEmailsDirectory = import_node_path7.default.resolve(
    process.cwd(),
    emailDirRelativePath
  );
  const [dependencyGraph, updateDependencyGraph, { resolveDependentsOf }] = await createDependencyGraph(absolutePathToEmailsDirectory);
  const watcher = (0, import_chokidar.watch)("", {
    ignoreInitial: true,
    cwd: absolutePathToEmailsDirectory
  });
  const getFilesOutsideEmailsDirectory = () => Object.keys(dependencyGraph).filter(
    (p) => import_node_path7.default.relative(absolutePathToEmailsDirectory, p).startsWith("..")
  );
  let filesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
  for (const p of filesOutsideEmailsDirectory) {
    watcher.add(p);
  }
  const exit = async () => {
    await watcher.close();
  };
  process.on("SIGINT", exit);
  process.on("uncaughtException", exit);
  watcher.on("all", async (event, relativePathToChangeTarget) => {
    const file = relativePathToChangeTarget.split(import_node_path7.default.sep);
    if (file.length === 0) {
      return;
    }
    const pathToChangeTarget = import_node_path7.default.resolve(
      absolutePathToEmailsDirectory,
      relativePathToChangeTarget
    );
    await updateDependencyGraph(event, pathToChangeTarget);
    const newFilesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
    for (const p of filesOutsideEmailsDirectory) {
      if (!newFilesOutsideEmailsDirectory.includes(p)) {
        watcher.unwatch(p);
      }
    }
    for (const p of newFilesOutsideEmailsDirectory) {
      if (!filesOutsideEmailsDirectory.includes(p)) {
        watcher.add(p);
      }
    }
    filesOutsideEmailsDirectory = newFilesOutsideEmailsDirectory;
    changes.push({
      event,
      filename: relativePathToChangeTarget
    });
    for (const dependentPath of resolveDependentsOf(pathToChangeTarget)) {
      changes.push({
        event: "change",
        filename: import_node_path7.default.relative(absolutePathToEmailsDirectory, dependentPath)
      });
    }
    reload();
  });
  return watcher;
};

// src/cli/commands/build.ts
var buildPreviewApp = (absoluteDirectory) => {
  return new Promise((resolve, reject) => {
    const nextBuild = (0, import_node_child_process.spawn)("npm", ["run", "build"], {
      cwd: absoluteDirectory,
      shell: true
    });
    nextBuild.stdout.pipe(process.stdout);
    nextBuild.stderr.pipe(process.stderr);
    nextBuild.on("close", (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(
          new Error(
            `Unable to build the Next app and it exited with code: ${code}`
          )
        );
      }
    });
  });
};
var setNextEnvironmentVariablesForBuild = async (emailsDirRelativePath, builtPreviewAppPath) => {
  const nextConfigContents = `
const path = require('path');
const emailsDirRelativePath = path.normalize('${emailsDirRelativePath}');
const userProjectLocation = path.resolve(process.cwd(), '../');
/** @type {import('next').NextConfig} */
module.exports = {
  env: {
    NEXT_PUBLIC_IS_BUILDING: 'true',
    EMAILS_DIR_RELATIVE_PATH: emailsDirRelativePath,
    EMAILS_DIR_ABSOLUTE_PATH: path.resolve(userProjectLocation, emailsDirRelativePath),
    USER_PROJECT_LOCATION: userProjectLocation
  },
  // this is needed so that the code for building emails works properly
  webpack: (
    /** @type {import('webpack').Configuration & { externals: string[] }} */
    config,
    { isServer }
  ) => {
    if (isServer) {
      config.externals.push('esbuild');
    }

    return config;
  },
  typescript: {
    ignoreBuildErrors: true
  },
  eslint: {
    ignoreDuringBuilds: true
  },
  experimental: {
    webpackBuildWorker: true
  },
}`;
  await import_node_fs5.default.promises.writeFile(
    import_node_path8.default.resolve(builtPreviewAppPath, "./next.config.js"),
    nextConfigContents,
    "utf8"
  );
};
var getEmailSlugsFromEmailDirectory = (emailDirectory, emailsDirectoryAbsolutePath) => {
  const directoryPathRelativeToEmailsDirectory = emailDirectory.absolutePath.replace(emailsDirectoryAbsolutePath, "").trim();
  const slugs = [];
  emailDirectory.emailFilenames.forEach(
    (filename) => slugs.push(
      import_node_path8.default.join(directoryPathRelativeToEmailsDirectory, filename).split(import_node_path8.default.sep).filter((segment) => segment.length > 0)
    )
  );
  emailDirectory.subDirectories.forEach((directory) => {
    slugs.push(
      ...getEmailSlugsFromEmailDirectory(
        directory,
        emailsDirectoryAbsolutePath
      )
    );
  });
  return slugs;
};
var forceSSGForEmailPreviews = async (emailsDirPath, builtPreviewAppPath) => {
  const emailDirectoryMetadata = (
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    await getEmailsDirectoryMetadata(emailsDirPath)
  );
  const parameters = getEmailSlugsFromEmailDirectory(
    emailDirectoryMetadata,
    emailsDirPath
  ).map((slug) => ({ slug }));
  const removeForceDynamic = async (filePath) => {
    const contents = await import_node_fs5.default.promises.readFile(filePath, "utf8");
    await import_node_fs5.default.promises.writeFile(
      filePath,
      contents.replace("export const dynamic = 'force-dynamic';", ""),
      "utf8"
    );
  };
  await removeForceDynamic(
    import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/layout.tsx")
  );
  await removeForceDynamic(
    import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx")
  );
  await import_node_fs5.default.promises.appendFile(
    import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx"),
    `

export function generateStaticParams() { 
  return Promise.resolve(
    ${JSON.stringify(parameters)}
  );
}`,
    "utf8"
  );
};
var updatePackageJson = async (builtPreviewAppPath) => {
  const packageJsonPath = import_node_path8.default.resolve(builtPreviewAppPath, "./package.json");
  const packageJson = JSON.parse(
    await import_node_fs5.default.promises.readFile(packageJsonPath, "utf8")
  );
  packageJson.scripts.build = "next build";
  packageJson.scripts.start = "next start";
  packageJson.name = "preview-server";
  delete packageJson.devDependencies["@react-email/render"];
  delete packageJson.devDependencies["@react-email/components"];
  delete packageJson.scripts.prepare;
  await import_node_fs5.default.promises.writeFile(
    packageJsonPath,
    JSON.stringify(packageJson),
    "utf8"
  );
};
var npmInstall = async (builtPreviewAppPath, packageManager) => {
  return new Promise((resolve, reject) => {
    const childProc = (0, import_node_child_process.spawn)(
      packageManager,
      [
        "install",
        packageManager === "deno" ? "" : "--include=dev",
        packageManager === "deno" ? "--quiet" : "--silent"
      ],
      {
        cwd: builtPreviewAppPath,
        shell: true
      }
    );
    childProc.stdout.pipe(process.stdout);
    childProc.stderr.pipe(process.stderr);
    childProc.on("close", (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(
          new Error(
            `Unable to install the dependencies and it exited with code: ${code}`
          )
        );
      }
    });
  });
};
var build = async ({
  dir: emailsDirRelativePath,
  packageManager
}) => {
  try {
    const spinner = (0, import_ora2.default)({
      text: "Starting build process...",
      prefixText: "  "
    }).start();
    registerSpinnerAutostopping(spinner);
    spinner.text = `Checking if ${emailsDirRelativePath} folder exists`;
    if (!import_node_fs5.default.existsSync(emailsDirRelativePath)) {
      process.exit(1);
    }
    const emailsDirPath = import_node_path8.default.join(process.cwd(), emailsDirRelativePath);
    const staticPath = import_node_path8.default.join(emailsDirPath, "static");
    const builtPreviewAppPath = import_node_path8.default.join(process.cwd(), ".react-email");
    if (import_node_fs5.default.existsSync(builtPreviewAppPath)) {
      spinner.text = "Deleting pre-existing `.react-email` folder";
      await import_node_fs5.default.promises.rm(builtPreviewAppPath, { recursive: true });
    }
    spinner.text = "Copying preview app from CLI to `.react-email`";
    await import_node_fs5.default.promises.cp(cliPackageLocation, builtPreviewAppPath, {
      recursive: true,
      filter: (source) => {
        return !/(\/|\\)cli(\/|\\)?/.test(source) && !/(\/|\\)\.next(\/|\\)?/.test(source) && !/(\/|\\)\.turbo(\/|\\)?/.test(source) && !/(\/|\\)node_modules(\/|\\)?$/.test(source);
      }
    });
    if (import_node_fs5.default.existsSync(staticPath)) {
      spinner.text = "Copying `static` folder into `.react-email/public/static`";
      const builtStaticDirectory = import_node_path8.default.resolve(
        builtPreviewAppPath,
        "./public/static"
      );
      await import_node_fs5.default.promises.cp(staticPath, builtStaticDirectory, {
        recursive: true
      });
    }
    spinner.text = "Setting Next environment variables for preview app to work properly";
    await setNextEnvironmentVariablesForBuild(
      emailsDirRelativePath,
      builtPreviewAppPath
    );
    spinner.text = "Setting server side generation for the email preview pages";
    await forceSSGForEmailPreviews(emailsDirPath, builtPreviewAppPath);
    spinner.text = "Updating package.json's build and start scripts";
    await updatePackageJson(builtPreviewAppPath);
    spinner.text = "Installing dependencies on `.react-email`";
    await npmInstall(builtPreviewAppPath, packageManager);
    spinner.stopAndPersist({
      text: "Successfully prepared `.react-email` for `next build`",
      symbol: import_log_symbols3.default.success
    });
    await buildPreviewApp(builtPreviewAppPath);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
};

// src/cli/commands/dev.ts
var import_node_fs6 = __toESM(require("fs"));
var dev = async ({ dir: emailsDirRelativePath, port }) => {
  try {
    if (!import_node_fs6.default.existsSync(emailsDirRelativePath)) {
      console.error(`Missing ${emailsDirRelativePath} folder`);
      process.exit(1);
    }
    const devServer2 = await startDevServer(
      emailsDirRelativePath,
      emailsDirRelativePath,
      // defaults to ./emails/static for the static files that are served to the preview
      Number.parseInt(port)
    );
    await setupHotreloading(devServer2, emailsDirRelativePath);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
};

// src/cli/commands/export.ts
var import_node_fs8 = __toESM(require("fs"));
var import_node_path10 = __toESM(require("path"));
var import_esbuild = require("esbuild");
var import_glob = require("glob");
var import_log_symbols4 = __toESM(require("log-symbols"));
var import_normalize_path = __toESM(require("normalize-path"));
var import_ora3 = __toESM(require("ora"));

// src/utils/esbuild/renderring-utilities-exporter.ts
var import_node_fs7 = require("fs");
var import_node_path9 = __toESM(require("path"));

// src/utils/esbuild/escape-string-for-regex.ts
function escapeStringForRegex(string) {
  return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
}

// src/utils/esbuild/renderring-utilities-exporter.ts
var renderingUtilitiesExporter = (emailTemplates) => ({
  name: "rendering-utilities-exporter",
  setup: (b) => {
    b.onLoad(
      {
        filter: new RegExp(
          emailTemplates.map((emailPath) => escapeStringForRegex(emailPath)).join("|")
        )
      },
      async ({ path: pathToFile }) => {
        return {
          contents: `${await import_node_fs7.promises.readFile(pathToFile, "utf8")};
          export { render, pretty } from 'react-email-module-that-will-export-render'
          export { createElement as reactEmailCreateReactElement } from 'react';
        `,
          loader: import_node_path9.default.extname(pathToFile).slice(1)
        };
      }
    );
    b.onResolve(
      { filter: /^react-email-module-that-will-export-render$/ },
      async (args) => {
        const options = {
          kind: "import-statement",
          importer: args.importer,
          resolveDir: args.resolveDir,
          namespace: args.namespace
        };
        let result = await b.resolve("@react-email/render", options);
        if (result.errors.length === 0) {
          return result;
        }
        result = await b.resolve("@react-email/components", options);
        if (result.errors.length > 0 && result.errors[0]) {
          result.errors[0].text = "Failed trying to import `render` from either `@react-email/render` or `@react-email/components` to be able to render your email template.\n Maybe you don't have either of them installed?";
        }
        return result;
      }
    );
  }
});

// src/cli/commands/export.ts
var getEmailTemplatesFromDirectory = (emailDirectory) => {
  const templatePaths = [];
  emailDirectory.emailFilenames.forEach(
    (filename) => templatePaths.push(import_node_path10.default.join(emailDirectory.absolutePath, filename))
  );
  emailDirectory.subDirectories.forEach((directory) => {
    templatePaths.push(...getEmailTemplatesFromDirectory(directory));
  });
  return templatePaths;
};
var exportTemplates = async (pathToWhereEmailMarkupShouldBeDumped, emailsDirectoryPath, options) => {
  if (import_node_fs8.default.existsSync(pathToWhereEmailMarkupShouldBeDumped)) {
    import_node_fs8.default.rmSync(pathToWhereEmailMarkupShouldBeDumped, { recursive: true });
  }
  let spinner;
  if (!options.silent) {
    spinner = (0, import_ora3.default)("Preparing files...\n").start();
    registerSpinnerAutostopping(spinner);
  }
  const emailsDirectoryMetadata = await getEmailsDirectoryMetadata(
    import_node_path10.default.resolve(process.cwd(), emailsDirectoryPath),
    true
  );
  if (typeof emailsDirectoryMetadata === "undefined") {
    if (spinner) {
      spinner.stopAndPersist({
        symbol: import_log_symbols4.default.error,
        text: `Could not find the directory at ${emailsDirectoryPath}`
      });
    }
    return;
  }
  const allTemplates = getEmailTemplatesFromDirectory(emailsDirectoryMetadata);
  try {
    await (0, import_esbuild.build)({
      bundle: true,
      entryPoints: allTemplates,
      plugins: [renderingUtilitiesExporter(allTemplates)],
      platform: "node",
      format: "cjs",
      loader: { ".js": "jsx" },
      outExtension: { ".js": ".cjs" },
      jsx: "transform",
      write: true,
      outdir: pathToWhereEmailMarkupShouldBeDumped
    });
  } catch (exception) {
    const buildFailure = exception;
    if (spinner) {
      spinner.stopAndPersist({
        symbol: import_log_symbols4.default.error,
        text: "Failed to build emails"
      });
    }
    process.exit(1);
  }
  if (spinner) {
    spinner.succeed();
  }
  const allBuiltTemplates = import_glob.glob.sync(
    (0, import_normalize_path.default)(`${pathToWhereEmailMarkupShouldBeDumped}/**/*.cjs`),
    {
      absolute: true
    }
  );
  for await (const template of allBuiltTemplates) {
    try {
      if (spinner) {
        spinner.text = `rendering ${template.split("/").pop()}`;
        spinner.render();
      }
      delete require.cache[template];
      const emailModule = require(template);
      let rendered = await emailModule.render(
        emailModule.reactEmailCreateReactElement(emailModule.default, {}),
        options
      );
      if (!options.plainText && options.pretty)
        rendered = await emailModule.pretty(rendered);
      const htmlPath = template.replace(
        ".cjs",
        options.plainText ? ".txt" : ".html"
      );
      (0, import_node_fs8.writeFileSync)(htmlPath, rendered);
      (0, import_node_fs8.unlinkSync)(template);
    } catch (exception) {
      if (spinner) {
        spinner.stopAndPersist({
          symbol: import_log_symbols4.default.error,
          text: `failed when rendering ${template.split("/").pop()}`
        });
      }
      console.error(exception);
      process.exit(1);
    }
  }
  if (spinner) {
    spinner.succeed("Rendered all files");
    spinner.text = "Copying static files";
    spinner.render();
  }
  const staticDirectoryPath = import_node_path10.default.join(emailsDirectoryPath, "static");
  if (import_node_fs8.default.existsSync(staticDirectoryPath)) {
    const pathToDumpStaticFilesInto = import_node_path10.default.join(
      pathToWhereEmailMarkupShouldBeDumped,
      "static"
    );
    if (import_node_fs8.default.existsSync(pathToDumpStaticFilesInto))
      await import_node_fs8.default.promises.rm(pathToDumpStaticFilesInto, { recursive: true });
    try {
      await import_node_fs8.default.promises.cp(staticDirectoryPath, pathToDumpStaticFilesInto, {
        recursive: true
      });
    } catch (exception) {
      console.error(exception);
      if (spinner) {
        spinner.stopAndPersist({
          symbol: import_log_symbols4.default.error,
          text: "Failed to copy static files"
        });
      }
      console.error(
        `Something went wrong while copying the file to ${pathToWhereEmailMarkupShouldBeDumped}/static, ${exception}`
      );
      process.exit(1);
    }
  }
  if (spinner && !options.silent) {
    spinner.succeed();
    const fileTree = await tree(pathToWhereEmailMarkupShouldBeDumped, 4);
    console.log(fileTree);
    spinner.stopAndPersist({
      symbol: import_log_symbols4.default.success,
      text: "Successfully exported emails"
    });
  }
};

// src/cli/commands/start.ts
var import_node_child_process2 = require("child_process");
var import_node_fs9 = __toESM(require("fs"));
var import_node_path11 = __toESM(require("path"));
var start = async () => {
  try {
    const usersProjectLocation = process.cwd();
    const builtPreviewPath = import_node_path11.default.resolve(
      usersProjectLocation,
      "./.react-email"
    );
    if (!import_node_fs9.default.existsSync(builtPreviewPath)) {
      console.error(
        "Could not find .react-email, maybe you haven't ran email build?"
      );
      process.exit(1);
    }
    const nextStart = (0, import_node_child_process2.spawn)("npm", ["start"], {
      cwd: builtPreviewPath,
      stdio: "inherit"
    });
    process.on("SIGINT", () => {
      nextStart.kill("SIGINT");
    });
    nextStart.on("exit", (code) => {
      process.exit(code ?? 0);
    });
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
};

// src/cli/index.ts
var PACKAGE_NAME = "react-email";
import_commander.program.name(PACKAGE_NAME).description("A live preview of your emails right in your browser").version(package_default.version);
import_commander.program.command("dev").description("Starts the preview email development app").option("-d, --dir <path>", "Directory with your email templates", "./emails").option("-p --port <port>", "Port to run dev server on", "3000").action(dev);
import_commander.program.command("build").description("Copies the preview app for onto .react-email and builds it").option("-d, --dir <path>", "Directory with your email templates", "./emails").option(
  "-p --packageManager <name>",
  "Package name to use on installation on `.react-email`",
  "npm"
).action(build);
import_commander.program.command("start").description('Runs the built preview app that is inside of ".react-email"').action(start);
import_commander.program.command("export").description("Build the templates to the `out` directory").option("--outDir <path>", "Output directory", "out").option("-p, --pretty", "Pretty print the output", false).option("-t, --plainText", "Set output format as plain text", false).option("-d, --dir <path>", "Directory with your email templates", "./emails").option(
  "-s, --silent",
  "To, or not to show a spinner with process information",
  false
).action(
  ({ outDir, pretty, plainText, silent, dir: srcDir }) => exportTemplates(outDir, srcDir, { silent, plainText, pretty })
);
import_commander.program.parse();
