react-email 4.0.14 → 4.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cli/index.d.mts +1 -0
  3. package/dist/cli/index.d.ts +1 -0
  4. package/dist/cli/index.js +2785 -0
  5. package/dist/cli/index.mjs +1 -1
  6. package/dist/index.d.mts +20 -0
  7. package/dist/index.d.ts +20 -0
  8. package/dist/index.js +1407 -0
  9. package/dist/index.mjs +21 -0
  10. package/dist/package/index.d.mts +33 -0
  11. package/dist/package/index.d.ts +33 -0
  12. package/dist/package/index.js +62 -0
  13. package/dist/package/index.mjs +7 -0
  14. package/dist/preview/.next/BUILD_ID +1 -1
  15. package/dist/preview/.next/app-build-manifest.json +10 -10
  16. package/dist/preview/.next/app-path-routes-manifest.json +1 -1
  17. package/dist/preview/.next/build-manifest.json +3 -3
  18. package/dist/preview/.next/next-minimal-server.js.nft.json +1 -1
  19. package/dist/preview/.next/next-server.js.nft.json +1 -1
  20. package/dist/preview/.next/prerender-manifest.json +3 -3
  21. package/dist/preview/.next/required-server-files.json +4 -4
  22. package/dist/preview/.next/server/app/_not-found/page.js +1 -1
  23. package/dist/preview/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  24. package/dist/preview/.next/server/app/favicon.ico/route.js +1 -1
  25. package/dist/preview/.next/server/app/page.js +1 -1
  26. package/dist/preview/.next/server/app/page.js.nft.json +1 -1
  27. package/dist/preview/.next/server/app/page_client-reference-manifest.js +1 -1
  28. package/dist/preview/.next/server/app/preview/[...slug]/page.js +17 -17
  29. package/dist/preview/.next/server/app/preview/[...slug]/page.js.nft.json +1 -1
  30. package/dist/preview/.next/server/app/preview/[...slug]/page_client-reference-manifest.js +1 -1
  31. package/dist/preview/.next/server/app-paths-manifest.json +1 -1
  32. package/dist/preview/.next/server/chunks/235.js +4 -4
  33. package/dist/preview/.next/server/chunks/275.js +1 -0
  34. package/dist/preview/.next/server/middleware-build-manifest.js +1 -1
  35. package/dist/preview/.next/server/next-font-manifest.js +1 -1
  36. package/dist/preview/.next/server/next-font-manifest.json +1 -1
  37. package/dist/preview/.next/server/pages/500.html +1 -1
  38. package/dist/preview/.next/server/server-reference-manifest.js +1 -1
  39. package/dist/preview/.next/server/server-reference-manifest.json +1 -1
  40. package/dist/preview/.next/static/chunks/484-e38a627386aae911.js +1 -0
  41. package/dist/preview/.next/static/chunks/app/{layout-cbdfc1cdce865f70.js → layout-269b5cbd8f4cd2e3.js} +1 -1
  42. package/dist/preview/.next/static/chunks/app/page-2dbfb5b2dc4b1191.js +1 -0
  43. package/dist/preview/.next/static/chunks/app/preview/[...slug]/page-79e0c9b528a62f8b.js +1 -0
  44. package/dist/preview/.next/static/chunks/main-app-976577a424e11c75.js +1 -0
  45. package/dist/preview/.next/static/css/ac3decd5d6736fbe.css +3 -0
  46. package/dist/preview/.next/static/media/8e9860b6e62d6359-s.woff2 +0 -0
  47. package/dist/preview/.next/static/media/e4af272ccee01ff0-s.p.woff2 +0 -0
  48. package/dist/preview/.next/trace +27 -27
  49. package/dist/preview/.next/types/app/layout.ts +1 -1
  50. package/dist/preview/.next/types/app/page.ts +1 -1
  51. package/dist/preview/.next/types/app/preview/[...slug]/page.ts +1 -1
  52. package/package.json +1 -1
  53. package/src/app/layout.tsx +8 -10
  54. package/src/commands/testing/out/notifications/yelp-recent-login.html +1 -1
  55. package/src/commands/testing/out/reset-password/twitch-reset-password.html +1 -1
  56. package/src/components/shell.tsx +4 -1
  57. package/src/components/sidebar/sidebar.tsx +1 -1
  58. package/src/components/toolbar/spam-assassin.tsx +1 -1
  59. package/src/components/toolbar.tsx +1 -1
  60. package/src/package/body/dist/index.d.mts +6 -0
  61. package/src/package/body/dist/index.d.ts +6 -0
  62. package/src/package/body/dist/index.js +79 -0
  63. package/src/package/body/dist/index.mjs +45 -0
  64. package/src/package/button/dist/index.d.mts +6 -0
  65. package/src/package/button/dist/index.d.ts +6 -0
  66. package/src/package/button/dist/index.js +252 -0
  67. package/src/package/button/dist/index.mjs +218 -0
  68. package/src/package/code-block/dist/index.d.mts +4906 -0
  69. package/src/package/code-block/dist/index.d.ts +4906 -0
  70. package/src/package/code-block/dist/index.js +18205 -0
  71. package/src/package/code-block/dist/index.mjs +18133 -0
  72. package/src/package/code-inline/dist/index.d.mts +11 -0
  73. package/src/package/code-inline/dist/index.d.ts +11 -0
  74. package/src/package/code-inline/dist/index.js +106 -0
  75. package/src/package/code-inline/dist/index.mjs +72 -0
  76. package/src/package/column/dist/index.d.mts +6 -0
  77. package/src/package/column/dist/index.d.ts +6 -0
  78. package/src/package/column/dist/index.js +79 -0
  79. package/src/package/column/dist/index.mjs +45 -0
  80. package/src/package/components/dist/index.d.mts +20 -0
  81. package/src/package/components/dist/index.d.ts +20 -0
  82. package/src/package/components/dist/index.js +62 -0
  83. package/src/package/components/dist/index.mjs +21 -0
  84. package/src/package/container/dist/index.d.mts +6 -0
  85. package/src/package/container/dist/index.d.ts +6 -0
  86. package/src/package/container/dist/index.js +93 -0
  87. package/src/package/container/dist/index.mjs +59 -0
  88. package/src/package/font/dist/index.d.mts +25 -0
  89. package/src/package/font/dist/index.d.ts +25 -0
  90. package/src/package/font/dist/index.js +55 -0
  91. package/src/package/font/dist/index.mjs +28 -0
  92. package/src/package/head/dist/index.d.mts +6 -0
  93. package/src/package/head/dist/index.d.ts +6 -0
  94. package/src/package/head/dist/index.js +83 -0
  95. package/src/package/head/dist/index.mjs +49 -0
  96. package/src/package/heading/dist/index.d.mts +43 -0
  97. package/src/package/heading/dist/index.d.ts +43 -0
  98. package/src/package/heading/dist/index.js +113 -0
  99. package/src/package/heading/dist/index.mjs +79 -0
  100. package/src/package/hr/dist/index.d.mts +6 -0
  101. package/src/package/hr/dist/index.d.ts +6 -0
  102. package/src/package/hr/dist/index.js +89 -0
  103. package/src/package/hr/dist/index.mjs +55 -0
  104. package/src/package/html/dist/index.d.mts +6 -0
  105. package/src/package/html/dist/index.d.ts +6 -0
  106. package/src/package/html/dist/index.js +79 -0
  107. package/src/package/html/dist/index.mjs +45 -0
  108. package/src/package/img/dist/index.d.mts +6 -0
  109. package/src/package/img/dist/index.d.ts +6 -0
  110. package/src/package/img/dist/index.js +94 -0
  111. package/src/package/img/dist/index.mjs +60 -0
  112. package/src/package/link/dist/index.d.mts +6 -0
  113. package/src/package/link/dist/index.d.ts +6 -0
  114. package/src/package/link/dist/index.js +90 -0
  115. package/src/package/link/dist/index.mjs +56 -0
  116. package/src/package/markdown/dist/index.d.mts +15 -0
  117. package/src/package/markdown/dist/index.d.ts +15 -0
  118. package/src/package/markdown/dist/index.js +92 -0
  119. package/src/package/markdown/dist/index.mjs +58 -0
  120. package/src/package/preview/dist/index.d.mts +12 -0
  121. package/src/package/preview/dist/index.d.ts +12 -0
  122. package/src/package/preview/dist/index.js +108 -0
  123. package/src/package/preview/dist/index.mjs +73 -0
  124. package/src/package/render/dist/browser/index.d.mts +24 -0
  125. package/src/package/render/dist/browser/index.d.ts +24 -0
  126. package/src/package/render/dist/browser/index.js +250 -0
  127. package/src/package/render/dist/browser/index.mjs +214 -0
  128. package/src/package/render/dist/index.d.mts +23 -0
  129. package/src/package/render/dist/index.d.ts +23 -0
  130. package/src/package/render/dist/index.js +768 -0
  131. package/src/package/render/dist/index.mjs +733 -0
  132. package/src/package/render/dist/node/index.d.mts +27 -0
  133. package/src/package/render/dist/node/index.d.ts +27 -0
  134. package/src/package/render/dist/node/index.js +212 -0
  135. package/src/package/render/dist/node/index.mjs +176 -0
  136. package/src/package/row/dist/index.d.mts +10 -0
  137. package/src/package/row/dist/index.d.ts +10 -0
  138. package/src/package/row/dist/index.js +93 -0
  139. package/src/package/row/dist/index.mjs +59 -0
  140. package/src/package/section/dist/index.d.mts +6 -0
  141. package/src/package/section/dist/index.d.ts +6 -0
  142. package/src/package/section/dist/index.js +93 -0
  143. package/src/package/section/dist/index.mjs +59 -0
  144. package/src/package/tailwind/dist/index.d.ts +19 -0
  145. package/src/package/tailwind/dist/index.js +48 -0
  146. package/src/package/tailwind/dist/index.mjs +17167 -0
  147. package/src/package/tailwind/dist/tailwindcss/config.d.ts +376 -0
  148. package/src/package/tailwind/dist/tailwindcss/generated/.gitkeep +0 -0
  149. package/src/package/tailwind/dist/tailwindcss/generated/colors.d.ts +298 -0
  150. package/src/package/tailwind/dist/tailwindcss/generated/corePluginList.d.ts +1 -0
  151. package/src/package/tailwind/dist/tailwindcss/generated/default-theme.d.ts +397 -0
  152. package/src/package/tailwind/dist/tailwindcss/index.d.ts +11 -0
  153. package/src/package/text/dist/index.d.mts +6 -0
  154. package/src/package/text/dist/index.d.ts +6 -0
  155. package/src/package/text/dist/index.js +89 -0
  156. package/src/package/text/dist/index.mjs +55 -0
  157. package/dist/preview/.next/server/chunks/634.js +0 -1
  158. package/dist/preview/.next/static/chunks/484-962c5c33e02a8f74.js +0 -1
  159. package/dist/preview/.next/static/chunks/app/page-ed77f0af99f8ff62.js +0 -1
  160. package/dist/preview/.next/static/chunks/app/preview/[...slug]/page-677d0276e78ce644.js +0 -1
  161. package/dist/preview/.next/static/chunks/main-app-5bc2d814f500db60.js +0 -1
  162. package/dist/preview/.next/static/css/6f42d128f111d7fa.css +0 -3
  163. package/dist/preview/.next/static/media/6d93bde91c0c2823-s.woff2 +0 -0
  164. package/dist/preview/.next/static/media/a34f9d1faa5f3315-s.p.woff2 +0 -0
  165. /package/dist/preview/.next/static/{buxMzUckvYONJstUiLteh → yxjkw7Y7HRLmRWkl3S43z}/_buildManifest.js +0 -0
  166. /package/dist/preview/.next/static/{buxMzUckvYONJstUiLteh → yxjkw7Y7HRLmRWkl3S43z}/_ssgManifest.js +0 -0
package/dist/index.js ADDED
@@ -0,0 +1,1407 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { program } from "commander";
5
+
6
+ // src/commands/build.ts
7
+ import { spawn } from "node:child_process";
8
+ import fs2 from "node:fs";
9
+ import path3 from "node:path";
10
+ import logSymbols2 from "log-symbols";
11
+ import ora from "ora";
12
+
13
+ // src/utils/get-emails-directory-metadata.ts
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ var isFileAnEmail = async (fullPath) => {
17
+ let fileHandle;
18
+ try {
19
+ fileHandle = await fs.promises.open(fullPath, "r");
20
+ } catch (exception) {
21
+ console.warn(exception);
22
+ return false;
23
+ }
24
+ const stat = await fileHandle.stat();
25
+ if (stat.isDirectory()) {
26
+ await fileHandle.close();
27
+ return false;
28
+ }
29
+ const { ext } = path.parse(fullPath);
30
+ if (![".js", ".tsx", ".jsx"].includes(ext)) {
31
+ await fileHandle.close();
32
+ return false;
33
+ }
34
+ const fileContents = await fileHandle.readFile("utf8");
35
+ await fileHandle.close();
36
+ const hasES6DefaultExport = /\bexport\s+default\b/gm.test(fileContents);
37
+ const hasCommonJSExport = /\bmodule\.exports\s*=/gm.test(fileContents);
38
+ const hasNamedExport = /\bexport\s+\{[^}]*\bdefault\b[^}]*\}/gm.test(
39
+ fileContents
40
+ );
41
+ return hasES6DefaultExport || hasCommonJSExport || hasNamedExport;
42
+ };
43
+ var mergeDirectoriesWithSubDirectories = (emailsDirectoryMetadata) => {
44
+ let currentResultingMergedDirectory = emailsDirectoryMetadata;
45
+ while (currentResultingMergedDirectory.emailFilenames.length === 0 && currentResultingMergedDirectory.subDirectories.length === 1) {
46
+ const onlySubDirectory = currentResultingMergedDirectory.subDirectories[0];
47
+ currentResultingMergedDirectory = {
48
+ ...onlySubDirectory,
49
+ directoryName: path.join(
50
+ currentResultingMergedDirectory.directoryName,
51
+ onlySubDirectory.directoryName
52
+ )
53
+ };
54
+ }
55
+ return currentResultingMergedDirectory;
56
+ };
57
+ var getEmailsDirectoryMetadata = async (absolutePathToEmailsDirectory, keepFileExtensions = false, isSubDirectory = false, baseDirectoryPath = absolutePathToEmailsDirectory) => {
58
+ if (!fs.existsSync(absolutePathToEmailsDirectory)) return;
59
+ const dirents = await fs.promises.readdir(absolutePathToEmailsDirectory, {
60
+ withFileTypes: true
61
+ });
62
+ const isEmailPredicates = await Promise.all(
63
+ dirents.map(
64
+ (dirent) => isFileAnEmail(path.join(absolutePathToEmailsDirectory, dirent.name))
65
+ )
66
+ );
67
+ const emailFilenames = dirents.filter((_, i) => isEmailPredicates[i]).map(
68
+ (dirent) => keepFileExtensions ? dirent.name : dirent.name.replace(path.extname(dirent.name), "")
69
+ );
70
+ const subDirectories = await Promise.all(
71
+ dirents.filter(
72
+ (dirent) => dirent.isDirectory() && !dirent.name.startsWith("_") && dirent.name !== "static"
73
+ ).map((dirent) => {
74
+ const direntAbsolutePath = path.join(
75
+ absolutePathToEmailsDirectory,
76
+ dirent.name
77
+ );
78
+ return getEmailsDirectoryMetadata(
79
+ direntAbsolutePath,
80
+ keepFileExtensions,
81
+ true,
82
+ baseDirectoryPath
83
+ );
84
+ })
85
+ );
86
+ const emailsMetadata = {
87
+ absolutePath: absolutePathToEmailsDirectory,
88
+ relativePath: path.relative(
89
+ baseDirectoryPath,
90
+ absolutePathToEmailsDirectory
91
+ ),
92
+ directoryName: absolutePathToEmailsDirectory.split(path.sep).pop(),
93
+ emailFilenames,
94
+ subDirectories
95
+ };
96
+ return isSubDirectory ? mergeDirectoriesWithSubDirectories(emailsMetadata) : emailsMetadata;
97
+ };
98
+
99
+ // src/utils/get-preview-server-location.ts
100
+ import path2 from "node:path";
101
+ import url from "node:url";
102
+ import { createJiti } from "jiti";
103
+ import { addDevDependency } from "nypm";
104
+ import prompts from "prompts";
105
+
106
+ // package.json
107
+ var package_default = {
108
+ name: "react-email",
109
+ version: "4.1.0-canary.9",
110
+ description: "A live preview of your emails right in your browser.",
111
+ bin: {
112
+ email: "./dist/index.js"
113
+ },
114
+ type: "module",
115
+ scripts: {
116
+ build: "tsup-node",
117
+ clean: "rm -rf dist",
118
+ dev: "tsup-node --watch src",
119
+ test: "vitest run",
120
+ "test:watch": "vitest"
121
+ },
122
+ license: "MIT",
123
+ repository: {
124
+ type: "git",
125
+ url: "https://github.com/resend/react-email.git",
126
+ directory: "packages/react-email"
127
+ },
128
+ keywords: [
129
+ "react",
130
+ "email"
131
+ ],
132
+ engines: {
133
+ node: ">=18.0.0"
134
+ },
135
+ dependencies: {
136
+ "@babel/parser": "^7.27.0",
137
+ "@babel/traverse": "^7.27.0",
138
+ chalk: "^5.0.0",
139
+ chokidar: "^4.0.3",
140
+ commander: "^13.0.0",
141
+ debounce: "^2.0.0",
142
+ esbuild: "^0.25.0",
143
+ glob: "^11.0.0",
144
+ jiti: "2.4.2",
145
+ "log-symbols": "^7.0.0",
146
+ "mime-types": "^3.0.0",
147
+ "normalize-path": "^3.0.0",
148
+ nypm: "0.6.0",
149
+ ora: "^8.0.0",
150
+ prompts: "2.4.2",
151
+ "socket.io": "^4.8.1",
152
+ "tsconfig-paths": "4.2.0"
153
+ },
154
+ devDependencies: {
155
+ "@react-email/components": "workspace:*",
156
+ "@types/babel__core": "7.20.5",
157
+ "@types/babel__traverse": "7.20.7",
158
+ "@types/mime-types": "2.1.4",
159
+ "@types/prompts": "2.4.9",
160
+ next: "^15.3.2",
161
+ react: "19.0.0",
162
+ "react-dom": "19.0.0",
163
+ tsup: "8.4.0",
164
+ tsx: "4.19.3",
165
+ typescript: "5.8.3"
166
+ }
167
+ };
168
+
169
+ // src/utils/get-preview-server-location.ts
170
+ var ensurePreviewServerInstalled = async (message) => {
171
+ const response = await prompts({
172
+ type: "confirm",
173
+ name: "installPreviewServer",
174
+ message,
175
+ initial: true
176
+ });
177
+ if (response.installPreviewServer) {
178
+ console.log('Installing "@react-email/preview-server"');
179
+ await addDevDependency(
180
+ `@react-email/preview-server@${package_default.version}`
181
+ );
182
+ process.exit(0);
183
+ } else {
184
+ process.exit(0);
185
+ }
186
+ };
187
+ var getPreviewServerLocation = async () => {
188
+ const usersProject = createJiti(process.cwd());
189
+ let previewServerLocation;
190
+ try {
191
+ previewServerLocation = path2.dirname(
192
+ url.parse(usersProject.esmResolve("@react-email/preview-server"), true).path
193
+ );
194
+ } catch (_exception) {
195
+ await ensurePreviewServerInstalled(
196
+ 'To run the preview server, the package "@react-email/preview-server" must be installed. Would you like to install it?'
197
+ );
198
+ }
199
+ const { version } = await usersProject.import("@react-email/preview-server");
200
+ if (version !== package_default.version) {
201
+ await ensurePreviewServerInstalled(
202
+ `To run the preview server, the version of "@react-email/preview-server" must match the version of "react-email" (${package_default.version}). Would you like to install it?`
203
+ );
204
+ }
205
+ return previewServerLocation;
206
+ };
207
+
208
+ // src/utils/register-spinner-autostopping.ts
209
+ import logSymbols from "log-symbols";
210
+ var spinners = /* @__PURE__ */ new Set();
211
+ process.on("SIGINT", () => {
212
+ spinners.forEach((spinner) => {
213
+ if (spinner.isSpinning) {
214
+ spinner.stop();
215
+ }
216
+ });
217
+ });
218
+ process.on("exit", (code) => {
219
+ if (code !== 0) {
220
+ spinners.forEach((spinner) => {
221
+ if (spinner.isSpinning) {
222
+ spinner.stopAndPersist({
223
+ symbol: logSymbols.error
224
+ });
225
+ }
226
+ });
227
+ }
228
+ });
229
+ var registerSpinnerAutostopping = (spinner) => {
230
+ spinners.add(spinner);
231
+ };
232
+
233
+ // src/commands/build.ts
234
+ var buildPreviewApp = (absoluteDirectory) => {
235
+ return new Promise((resolve, reject) => {
236
+ const nextBuild = spawn("npm", ["run", "build"], {
237
+ cwd: absoluteDirectory,
238
+ shell: true
239
+ });
240
+ nextBuild.stdout.pipe(process.stdout);
241
+ nextBuild.stderr.pipe(process.stderr);
242
+ nextBuild.on("close", (code) => {
243
+ if (code === 0) {
244
+ resolve();
245
+ } else {
246
+ reject(
247
+ new Error(
248
+ `Unable to build the Next app and it exited with code: ${code}`
249
+ )
250
+ );
251
+ }
252
+ });
253
+ });
254
+ };
255
+ var npmInstall = async (builtPreviewAppPath, packageManager) => {
256
+ return new Promise((resolve, reject) => {
257
+ const childProc = spawn(
258
+ packageManager,
259
+ [
260
+ "install",
261
+ packageManager === "deno" ? "" : "--include=dev",
262
+ packageManager === "deno" ? "--quiet" : "--silent"
263
+ ],
264
+ {
265
+ cwd: builtPreviewAppPath,
266
+ shell: true
267
+ }
268
+ );
269
+ childProc.stdout.pipe(process.stdout);
270
+ childProc.stderr.pipe(process.stderr);
271
+ childProc.on("close", (code) => {
272
+ if (code === 0) {
273
+ resolve();
274
+ } else {
275
+ reject(
276
+ new Error(
277
+ `Unable to install the dependencies and it exited with code: ${code}`
278
+ )
279
+ );
280
+ }
281
+ });
282
+ });
283
+ };
284
+ var setNextEnvironmentVariablesForBuild = async (emailsDirRelativePath, builtPreviewAppPath) => {
285
+ const nextConfigContents = `
286
+ const path = require('path');
287
+ const emailsDirRelativePath = path.normalize('${emailsDirRelativePath}');
288
+ const userProjectLocation = '${process.cwd()}';
289
+ /** @type {import('next').NextConfig} */
290
+ module.exports = {
291
+ env: {
292
+ NEXT_PUBLIC_IS_BUILDING: 'true',
293
+ EMAILS_DIR_RELATIVE_PATH: emailsDirRelativePath,
294
+ EMAILS_DIR_ABSOLUTE_PATH: path.resolve(userProjectLocation, emailsDirRelativePath),
295
+ USER_PROJECT_LOCATION: userProjectLocation
296
+ },
297
+ // this is needed so that the code for building emails works properly
298
+ webpack: (
299
+ /** @type {import('webpack').Configuration & { externals: string[] }} */
300
+ config,
301
+ { isServer }
302
+ ) => {
303
+ if (isServer) {
304
+ config.externals.push('esbuild');
305
+ }
306
+
307
+ return config;
308
+ },
309
+ typescript: {
310
+ ignoreBuildErrors: true
311
+ },
312
+ eslint: {
313
+ ignoreDuringBuilds: true
314
+ },
315
+ experimental: {
316
+ webpackBuildWorker: true
317
+ },
318
+ }`;
319
+ await fs2.promises.writeFile(
320
+ path3.resolve(builtPreviewAppPath, "./next.config.js"),
321
+ nextConfigContents,
322
+ "utf8"
323
+ );
324
+ };
325
+ var getEmailSlugsFromEmailDirectory = (emailDirectory, emailsDirectoryAbsolutePath) => {
326
+ const directoryPathRelativeToEmailsDirectory = emailDirectory.absolutePath.replace(emailsDirectoryAbsolutePath, "").trim();
327
+ const slugs = [];
328
+ emailDirectory.emailFilenames.forEach(
329
+ (filename3) => slugs.push(
330
+ path3.join(directoryPathRelativeToEmailsDirectory, filename3).split(path3.sep).filter((segment) => segment.length > 0)
331
+ )
332
+ );
333
+ emailDirectory.subDirectories.forEach((directory) => {
334
+ slugs.push(
335
+ ...getEmailSlugsFromEmailDirectory(
336
+ directory,
337
+ emailsDirectoryAbsolutePath
338
+ )
339
+ );
340
+ });
341
+ return slugs;
342
+ };
343
+ var forceSSGForEmailPreviews = async (emailsDirPath, builtPreviewAppPath) => {
344
+ const emailDirectoryMetadata = (
345
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
346
+ await getEmailsDirectoryMetadata(emailsDirPath)
347
+ );
348
+ const parameters = getEmailSlugsFromEmailDirectory(
349
+ emailDirectoryMetadata,
350
+ emailsDirPath
351
+ ).map((slug) => ({ slug }));
352
+ const removeForceDynamic = async (filePath) => {
353
+ const contents = await fs2.promises.readFile(filePath, "utf8");
354
+ await fs2.promises.writeFile(
355
+ filePath,
356
+ contents.replace("export const dynamic = 'force-dynamic';", ""),
357
+ "utf8"
358
+ );
359
+ };
360
+ await removeForceDynamic(
361
+ path3.resolve(builtPreviewAppPath, "./src/app/layout.tsx")
362
+ );
363
+ await removeForceDynamic(
364
+ path3.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx")
365
+ );
366
+ await fs2.promises.appendFile(
367
+ path3.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx"),
368
+ `
369
+
370
+ export function generateStaticParams() {
371
+ return Promise.resolve(
372
+ ${JSON.stringify(parameters)}
373
+ );
374
+ }`,
375
+ "utf8"
376
+ );
377
+ };
378
+ var updatePackageJson = async (builtPreviewAppPath) => {
379
+ const packageJsonPath = path3.resolve(builtPreviewAppPath, "./package.json");
380
+ const packageJson = JSON.parse(
381
+ await fs2.promises.readFile(packageJsonPath, "utf8")
382
+ );
383
+ packageJson.scripts.build = "next build";
384
+ packageJson.scripts.start = "next start";
385
+ delete packageJson.scripts.postbuild;
386
+ packageJson.name = "preview-server";
387
+ delete packageJson.devDependencies["@react-email/render"];
388
+ delete packageJson.devDependencies["@react-email/components"];
389
+ delete packageJson.scripts.prepare;
390
+ await fs2.promises.writeFile(
391
+ packageJsonPath,
392
+ JSON.stringify(packageJson),
393
+ "utf8"
394
+ );
395
+ };
396
+ var build = async ({
397
+ dir: emailsDirRelativePath,
398
+ packageManager
399
+ }) => {
400
+ try {
401
+ const previewServerLocation = await getPreviewServerLocation();
402
+ const spinner = ora({
403
+ text: "Starting build process...",
404
+ prefixText: " "
405
+ }).start();
406
+ registerSpinnerAutostopping(spinner);
407
+ spinner.text = `Checking if ${emailsDirRelativePath} folder exists`;
408
+ if (!fs2.existsSync(emailsDirRelativePath)) {
409
+ process.exit(1);
410
+ }
411
+ const emailsDirPath = path3.join(process.cwd(), emailsDirRelativePath);
412
+ const staticPath = path3.join(emailsDirPath, "static");
413
+ const builtPreviewAppPath = path3.join(process.cwd(), ".react-email");
414
+ if (fs2.existsSync(builtPreviewAppPath)) {
415
+ spinner.text = "Deleting pre-existing `.react-email` folder";
416
+ await fs2.promises.rm(builtPreviewAppPath, { recursive: true });
417
+ }
418
+ spinner.text = "Copying preview app from CLI to `.react-email`";
419
+ await fs2.promises.cp(previewServerLocation, builtPreviewAppPath, {
420
+ recursive: true,
421
+ filter: (source) => {
422
+ return !/(\/|\\)cli(\/|\\)?/.test(source) && !/(\/|\\)\.next(\/|\\)?/.test(source) && !/(\/|\\)\.turbo(\/|\\)?/.test(source) && !/(\/|\\)node_modules(\/|\\)?$/.test(source);
423
+ }
424
+ });
425
+ if (fs2.existsSync(staticPath)) {
426
+ spinner.text = "Copying `static` folder into `.react-email/public/static`";
427
+ const builtStaticDirectory = path3.resolve(
428
+ builtPreviewAppPath,
429
+ "./public/static"
430
+ );
431
+ await fs2.promises.cp(staticPath, builtStaticDirectory, {
432
+ recursive: true
433
+ });
434
+ }
435
+ spinner.text = "Setting Next environment variables for preview app to work properly";
436
+ await setNextEnvironmentVariablesForBuild(
437
+ emailsDirRelativePath,
438
+ builtPreviewAppPath
439
+ );
440
+ spinner.text = "Setting server side generation for the email preview pages";
441
+ await forceSSGForEmailPreviews(emailsDirPath, builtPreviewAppPath);
442
+ spinner.text = "Updating package.json's build and start scripts";
443
+ await updatePackageJson(builtPreviewAppPath);
444
+ spinner.text = "Installing dependencies on `.react-email`";
445
+ await npmInstall(builtPreviewAppPath, packageManager);
446
+ spinner.stopAndPersist({
447
+ text: "Successfully prepared `.react-email` for `next build`",
448
+ symbol: logSymbols2.success
449
+ });
450
+ await buildPreviewApp(builtPreviewAppPath);
451
+ } catch (error) {
452
+ console.log(error);
453
+ process.exit(1);
454
+ }
455
+ };
456
+
457
+ // src/commands/dev.ts
458
+ import fs6 from "node:fs";
459
+
460
+ // src/utils/preview/hot-reloading/setup-hot-reloading.ts
461
+ import path9 from "node:path";
462
+ import { watch } from "chokidar";
463
+ import debounce from "debounce";
464
+ import { Server as SocketServer } from "socket.io";
465
+
466
+ // src/utils/preview/hot-reloading/create-dependency-graph.ts
467
+ import { existsSync as existsSync2, promises as fs4, statSync } from "node:fs";
468
+ import path8 from "node:path";
469
+
470
+ // src/utils/preview/start-dev-server.ts
471
+ import http from "node:http";
472
+ import path6 from "node:path";
473
+ import url2 from "node:url";
474
+ import chalk from "chalk";
475
+ import { createJiti as createJiti2 } from "jiti";
476
+ import logSymbols3 from "log-symbols";
477
+ import ora2 from "ora";
478
+
479
+ // src/utils/preview/get-env-variables-for-preview-app.ts
480
+ import path4 from "node:path";
481
+ var getEnvVariablesForPreviewApp = (relativePathToEmailsDirectory, cwd) => {
482
+ return {
483
+ EMAILS_DIR_RELATIVE_PATH: relativePathToEmailsDirectory,
484
+ EMAILS_DIR_ABSOLUTE_PATH: path4.resolve(cwd, relativePathToEmailsDirectory),
485
+ USER_PROJECT_LOCATION: cwd,
486
+ NEXT_PUBLIC_IS_PREVIEW_DEVELOPMENT: isDev ? "true" : "false"
487
+ };
488
+ };
489
+
490
+ // src/utils/preview/serve-static-file.ts
491
+ import { existsSync, promises as fs3 } from "node:fs";
492
+ import path5 from "node:path";
493
+ import { lookup } from "mime-types";
494
+ var serveStaticFile = async (res, parsedUrl, staticDirRelativePath) => {
495
+ const pathname = parsedUrl.pathname.replace("/static", "./static");
496
+ const ext = path5.parse(pathname).ext;
497
+ const staticBaseDir = path5.resolve(process.cwd(), staticDirRelativePath);
498
+ const fileAbsolutePath = path5.resolve(staticBaseDir, pathname);
499
+ if (!fileAbsolutePath.startsWith(staticBaseDir)) {
500
+ res.statusCode = 403;
501
+ res.end();
502
+ return;
503
+ }
504
+ try {
505
+ const fileHandle = await fs3.open(fileAbsolutePath, "r");
506
+ const fileData = await fs3.readFile(fileHandle);
507
+ res.setHeader("Content-type", lookup(ext) || "text/plain");
508
+ res.end(fileData);
509
+ fileHandle.close();
510
+ } catch (exception) {
511
+ if (!existsSync(fileAbsolutePath)) {
512
+ res.statusCode = 404;
513
+ res.end();
514
+ } else {
515
+ const sanitizedFilePath = fileAbsolutePath.replace(/\n|\r/g, "");
516
+ console.error(
517
+ `Could not read file at ${sanitizedFilePath} to be served, here's the exception:`,
518
+ exception
519
+ );
520
+ res.statusCode = 500;
521
+ res.end(
522
+ "Could not read file to be served! Check your terminal for more information."
523
+ );
524
+ }
525
+ }
526
+ };
527
+
528
+ // src/utils/preview/start-dev-server.ts
529
+ var devServer;
530
+ var safeAsyncServerListen = (server, port) => {
531
+ return new Promise((resolve) => {
532
+ server.listen(port, () => {
533
+ resolve({ portAlreadyInUse: false });
534
+ });
535
+ server.on("error", (e) => {
536
+ if (e.code === "EADDRINUSE") {
537
+ resolve({ portAlreadyInUse: true });
538
+ }
539
+ });
540
+ });
541
+ };
542
+ var filename = url2.fileURLToPath(import.meta.url);
543
+ var dirname = path6.dirname(filename);
544
+ var isDev = !dirname.includes("dist");
545
+ var startDevServer = async (emailsDirRelativePath, staticBaseDirRelativePath, port) => {
546
+ const [majorNodeVersion] = process.versions.node.split(".");
547
+ if (majorNodeVersion && Number.parseInt(majorNodeVersion) < 18) {
548
+ console.error(
549
+ ` ${logSymbols3.error} Node ${majorNodeVersion} is not supported. Please upgrade to Node 18 or higher.`
550
+ );
551
+ process.exit(1);
552
+ }
553
+ const previewServerLocation = await getPreviewServerLocation();
554
+ const previewServer = createJiti2(previewServerLocation);
555
+ const { default: next } = await previewServer.import("next");
556
+ devServer = http.createServer((req, res) => {
557
+ if (!req.url) {
558
+ res.end(404);
559
+ return;
560
+ }
561
+ const parsedUrl = url2.parse(req.url, true);
562
+ res.setHeader(
563
+ "Cache-Control",
564
+ "no-cache, max-age=0, must-revalidate, no-store"
565
+ );
566
+ res.setHeader("Pragma", "no-cache");
567
+ res.setHeader("Expires", "-1");
568
+ try {
569
+ if (parsedUrl.path?.includes("static/") && !parsedUrl.path.includes("_next/static/")) {
570
+ void serveStaticFile(res, parsedUrl, staticBaseDirRelativePath);
571
+ } else if (!isNextReady) {
572
+ void nextReadyPromise.then(
573
+ () => nextHandleRequest?.(req, res, parsedUrl)
574
+ );
575
+ } else {
576
+ void nextHandleRequest?.(req, res, parsedUrl);
577
+ }
578
+ } catch (e) {
579
+ console.error("caught error", e);
580
+ res.writeHead(500);
581
+ res.end();
582
+ }
583
+ });
584
+ const { portAlreadyInUse } = await safeAsyncServerListen(devServer, port);
585
+ if (!portAlreadyInUse) {
586
+ console.log(chalk.greenBright(` React Email ${package_default.version}`));
587
+ console.log(` Running preview at: http://localhost:${port}
588
+ `);
589
+ } else {
590
+ const nextPortToTry = port + 1;
591
+ console.warn(
592
+ ` ${logSymbols3.warning} Port ${port} is already in use, trying ${nextPortToTry}`
593
+ );
594
+ return startDevServer(
595
+ emailsDirRelativePath,
596
+ staticBaseDirRelativePath,
597
+ nextPortToTry
598
+ );
599
+ }
600
+ devServer.on("close", async () => {
601
+ await app.close();
602
+ });
603
+ devServer.on("error", (e) => {
604
+ spinner.stopAndPersist({
605
+ symbol: logSymbols3.error,
606
+ text: `Preview Server had an error: ${e}`
607
+ });
608
+ process.exit(1);
609
+ });
610
+ const spinner = ora2({
611
+ text: "Getting react-email preview server ready...\n",
612
+ prefixText: " "
613
+ }).start();
614
+ registerSpinnerAutostopping(spinner);
615
+ const timeBeforeNextReady = performance.now();
616
+ process.env = {
617
+ NODE_ENV: "development",
618
+ ...process.env,
619
+ ...getEnvVariablesForPreviewApp(
620
+ // If we don't do normalization here, stuff like https://github.com/resend/react-email/issues/1354 happens.
621
+ path6.normalize(emailsDirRelativePath),
622
+ process.cwd()
623
+ )
624
+ };
625
+ const app = next({
626
+ // passing in env here does not get the environment variables there
627
+ dev: isDev,
628
+ conf: {
629
+ images: {
630
+ // This is to avoid the warning with sharp
631
+ unoptimized: true
632
+ }
633
+ },
634
+ hostname: "localhost",
635
+ port,
636
+ dir: previewServerLocation
637
+ });
638
+ let isNextReady = false;
639
+ const nextReadyPromise = app.prepare();
640
+ try {
641
+ await nextReadyPromise;
642
+ } catch (exception) {
643
+ spinner.stopAndPersist({
644
+ symbol: logSymbols3.error,
645
+ text: ` Preview Server had an error: ${exception}`
646
+ });
647
+ process.exit(1);
648
+ }
649
+ isNextReady = true;
650
+ const nextHandleRequest = app.getRequestHandler();
651
+ const secondsToNextReady = ((performance.now() - timeBeforeNextReady) / 1e3).toFixed(1);
652
+ spinner.stopAndPersist({
653
+ text: `Ready in ${secondsToNextReady}s
654
+ `,
655
+ symbol: logSymbols3.success
656
+ });
657
+ return devServer;
658
+ };
659
+ var makeExitHandler = (options) => (codeSignalOrError) => {
660
+ if (typeof devServer !== "undefined") {
661
+ console.log("\nshutting down dev server");
662
+ devServer.close();
663
+ devServer = void 0;
664
+ }
665
+ if (codeSignalOrError instanceof Error) {
666
+ console.error(codeSignalOrError);
667
+ }
668
+ if (options?.shouldKillProcess) {
669
+ process.exit(options.killWithErrorCode ? 1 : 0);
670
+ }
671
+ };
672
+ process.on("exit", makeExitHandler());
673
+ process.on(
674
+ "SIGINT",
675
+ makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
676
+ );
677
+ process.on(
678
+ "SIGUSR1",
679
+ makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
680
+ );
681
+ process.on(
682
+ "SIGUSR2",
683
+ makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
684
+ );
685
+ process.on(
686
+ "uncaughtException",
687
+ makeExitHandler({ shouldKillProcess: true, killWithErrorCode: true })
688
+ );
689
+
690
+ // src/utils/preview/hot-reloading/get-imported-modules.ts
691
+ import { parse } from "@babel/parser";
692
+ import traverseModule from "@babel/traverse";
693
+ var traverse = (
694
+ // we keep this check here so that this still works with the dev:preview
695
+ // script's use of tsx
696
+ typeof traverseModule === "function" ? traverseModule : traverseModule.default
697
+ );
698
+ var getImportedModules = (contents) => {
699
+ const importedPaths = [];
700
+ const parsedContents = parse(contents, {
701
+ sourceType: "unambiguous",
702
+ strictMode: false,
703
+ errorRecovery: true,
704
+ plugins: ["jsx", "typescript", "decorators"]
705
+ });
706
+ traverse(parsedContents, {
707
+ ImportDeclaration({ node }) {
708
+ importedPaths.push(node.source.value);
709
+ },
710
+ ExportAllDeclaration({ node }) {
711
+ importedPaths.push(node.source.value);
712
+ },
713
+ ExportNamedDeclaration({ node }) {
714
+ if (node.source) {
715
+ importedPaths.push(node.source.value);
716
+ }
717
+ },
718
+ TSExternalModuleReference({ node }) {
719
+ importedPaths.push(node.expression.value);
720
+ },
721
+ CallExpression({ node }) {
722
+ if ("name" in node.callee && node.callee.name === "require") {
723
+ if (node.arguments.length === 1) {
724
+ const importPathNode = node.arguments[0];
725
+ if (importPathNode.type === "StringLiteral") {
726
+ importedPaths.push(importPathNode.value);
727
+ }
728
+ }
729
+ }
730
+ }
731
+ });
732
+ return importedPaths;
733
+ };
734
+
735
+ // src/utils/preview/hot-reloading/resolve-path-aliases.ts
736
+ import path7 from "node:path";
737
+ import { createMatchPath, loadConfig } from "tsconfig-paths";
738
+ var resolvePathAliases = (importPaths, projectPath) => {
739
+ const configLoadResult = loadConfig(projectPath);
740
+ if (configLoadResult.resultType === "success") {
741
+ const matchPath = createMatchPath(
742
+ configLoadResult.absoluteBaseUrl,
743
+ configLoadResult.paths
744
+ );
745
+ return importPaths.map((importedPath) => {
746
+ const unaliasedPath = matchPath(importedPath, void 0, void 0, [
747
+ ".tsx",
748
+ ".ts",
749
+ ".js",
750
+ ".jsx",
751
+ ".cjs",
752
+ ".mjs"
753
+ ]);
754
+ if (unaliasedPath) {
755
+ return `./${path7.relative(projectPath, unaliasedPath)}`;
756
+ }
757
+ return importedPath;
758
+ });
759
+ }
760
+ return importPaths;
761
+ };
762
+
763
+ // src/utils/preview/hot-reloading/create-dependency-graph.ts
764
+ var readAllFilesInsideDirectory = async (directory) => {
765
+ let allFilePaths = [];
766
+ const topLevelDirents = await fs4.readdir(directory, { withFileTypes: true });
767
+ for await (const dirent of topLevelDirents) {
768
+ const pathToDirent = path8.join(directory, dirent.name);
769
+ if (dirent.isDirectory()) {
770
+ allFilePaths = allFilePaths.concat(
771
+ await readAllFilesInsideDirectory(pathToDirent)
772
+ );
773
+ } else {
774
+ allFilePaths.push(pathToDirent);
775
+ }
776
+ }
777
+ return allFilePaths;
778
+ };
779
+ var isJavascriptModule = (filePath) => {
780
+ const extensionName = path8.extname(filePath);
781
+ return [".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs"].includes(extensionName);
782
+ };
783
+ var checkFileExtensionsUntilItExists = (pathWithoutExtension) => {
784
+ if (existsSync2(`${pathWithoutExtension}.ts`)) {
785
+ return `${pathWithoutExtension}.ts`;
786
+ }
787
+ if (existsSync2(`${pathWithoutExtension}.tsx`)) {
788
+ return `${pathWithoutExtension}.tsx`;
789
+ }
790
+ if (existsSync2(`${pathWithoutExtension}.js`)) {
791
+ return `${pathWithoutExtension}.js`;
792
+ }
793
+ if (existsSync2(`${pathWithoutExtension}.jsx`)) {
794
+ return `${pathWithoutExtension}.jsx`;
795
+ }
796
+ if (existsSync2(`${pathWithoutExtension}.mjs`)) {
797
+ return `${pathWithoutExtension}.mjs`;
798
+ }
799
+ if (existsSync2(`${pathWithoutExtension}.cjs`)) {
800
+ return `${pathWithoutExtension}.cjs`;
801
+ }
802
+ };
803
+ var createDependencyGraph = async (directory) => {
804
+ const filePaths = await readAllFilesInsideDirectory(directory);
805
+ const modulePaths = filePaths.filter(isJavascriptModule);
806
+ const graph = Object.fromEntries(
807
+ modulePaths.map((path14) => [
808
+ path14,
809
+ {
810
+ path: path14,
811
+ dependencyPaths: [],
812
+ dependentPaths: [],
813
+ moduleDependencies: []
814
+ }
815
+ ])
816
+ );
817
+ const getDependencyPaths = async (filePath) => {
818
+ const contents = await fs4.readFile(filePath, "utf8");
819
+ const importedPaths = isJavascriptModule(filePath) ? resolvePathAliases(getImportedModules(contents), path8.dirname(filePath)) : [];
820
+ const importedPathsRelativeToDirectory = importedPaths.map(
821
+ (dependencyPath) => {
822
+ const isModulePath = !dependencyPath.startsWith(".");
823
+ if (isModulePath || path8.isAbsolute(dependencyPath)) {
824
+ return dependencyPath;
825
+ }
826
+ let pathToDependencyFromDirectory = path8.resolve(
827
+ /*
828
+ path.resolve resolves paths differently from what imports on javascript do.
829
+
830
+ So if we wouldn't do this, for an email at "/path/to/email.tsx" with a dependency path of "./other-email"
831
+ would end up going into /path/to/email.tsx/other-email instead of /path/to/other-email which is the
832
+ one the import is meant to go to
833
+ */
834
+ path8.dirname(filePath),
835
+ dependencyPath
836
+ );
837
+ let isDirectory = false;
838
+ try {
839
+ isDirectory = statSync(pathToDependencyFromDirectory).isDirectory();
840
+ } catch (_) {
841
+ }
842
+ if (isDirectory) {
843
+ const pathToSubDirectory = pathToDependencyFromDirectory;
844
+ const pathWithExtension = checkFileExtensionsUntilItExists(
845
+ `${pathToSubDirectory}/index`
846
+ );
847
+ if (pathWithExtension) {
848
+ pathToDependencyFromDirectory = pathWithExtension;
849
+ } else if (isDev) {
850
+ console.warn(
851
+ `Could not find index file for directory at ${pathToDependencyFromDirectory}. This is probably going to cause issues with both hot reloading and your code.`
852
+ );
853
+ }
854
+ }
855
+ const extension = path8.extname(pathToDependencyFromDirectory);
856
+ const pathWithEnsuredExtension = (() => {
857
+ if (extension.length > 0 && existsSync2(pathToDependencyFromDirectory)) {
858
+ return pathToDependencyFromDirectory;
859
+ }
860
+ return checkFileExtensionsUntilItExists(
861
+ pathToDependencyFromDirectory.replace(extension, "")
862
+ );
863
+ })();
864
+ if (pathWithEnsuredExtension) {
865
+ pathToDependencyFromDirectory = pathWithEnsuredExtension;
866
+ } else if (isDev) {
867
+ console.warn(
868
+ `Could not find file at ${pathToDependencyFromDirectory}`
869
+ );
870
+ }
871
+ return pathToDependencyFromDirectory;
872
+ }
873
+ );
874
+ const moduleDependencies = importedPathsRelativeToDirectory.filter(
875
+ (dependencyPath) => !dependencyPath.startsWith(".") && !path8.isAbsolute(dependencyPath)
876
+ );
877
+ const nonNodeModuleImportPathsRelativeToDirectory = importedPathsRelativeToDirectory.filter(
878
+ (dependencyPath) => dependencyPath.startsWith(".") || path8.isAbsolute(dependencyPath)
879
+ );
880
+ return {
881
+ dependencyPaths: nonNodeModuleImportPathsRelativeToDirectory,
882
+ moduleDependencies
883
+ };
884
+ };
885
+ const updateModuleDependenciesInGraph = async (moduleFilePath) => {
886
+ if (graph[moduleFilePath] === void 0) {
887
+ graph[moduleFilePath] = {
888
+ path: moduleFilePath,
889
+ dependencyPaths: [],
890
+ dependentPaths: [],
891
+ moduleDependencies: []
892
+ };
893
+ }
894
+ const { moduleDependencies, dependencyPaths: newDependencyPaths } = await getDependencyPaths(moduleFilePath);
895
+ graph[moduleFilePath].moduleDependencies = moduleDependencies;
896
+ for (const dependencyPath of graph[moduleFilePath].dependencyPaths) {
897
+ if (newDependencyPaths.includes(dependencyPath)) continue;
898
+ const dependencyModule = graph[dependencyPath];
899
+ if (dependencyModule !== void 0) {
900
+ dependencyModule.dependentPaths = dependencyModule.dependentPaths.filter(
901
+ (dependentPath) => dependentPath !== moduleFilePath
902
+ );
903
+ }
904
+ }
905
+ graph[moduleFilePath].dependencyPaths = newDependencyPaths;
906
+ for await (const dependencyPath of newDependencyPaths) {
907
+ if (graph[dependencyPath] === void 0) {
908
+ await updateModuleDependenciesInGraph(dependencyPath);
909
+ }
910
+ const dependencyModule = graph[dependencyPath];
911
+ if (dependencyModule === void 0) {
912
+ throw new Error(
913
+ `Loading the dependency path ${dependencyPath} did not initialize it at all. This is a bug in React Email.`
914
+ );
915
+ }
916
+ if (!dependencyModule.dependentPaths.includes(moduleFilePath)) {
917
+ dependencyModule.dependentPaths.push(moduleFilePath);
918
+ }
919
+ }
920
+ };
921
+ for (const filePath of modulePaths) {
922
+ await updateModuleDependenciesInGraph(filePath);
923
+ }
924
+ const removeModuleFromGraph = (filePath) => {
925
+ const module = graph[filePath];
926
+ if (module) {
927
+ for (const dependencyPath of module.dependencyPaths) {
928
+ if (graph[dependencyPath]) {
929
+ graph[dependencyPath].dependentPaths = graph[dependencyPath].dependentPaths.filter(
930
+ (dependentPath) => dependentPath !== filePath
931
+ );
932
+ }
933
+ }
934
+ delete graph[filePath];
935
+ }
936
+ };
937
+ return [
938
+ graph,
939
+ async (event, pathToModified) => {
940
+ switch (event) {
941
+ case "change":
942
+ if (isJavascriptModule(pathToModified)) {
943
+ await updateModuleDependenciesInGraph(pathToModified);
944
+ }
945
+ break;
946
+ case "add":
947
+ if (isJavascriptModule(pathToModified)) {
948
+ await updateModuleDependenciesInGraph(pathToModified);
949
+ }
950
+ break;
951
+ case "addDir": {
952
+ const filesInsideAddedDirectory = await readAllFilesInsideDirectory(pathToModified);
953
+ const modulesInsideAddedDirectory = filesInsideAddedDirectory.filter(isJavascriptModule);
954
+ for await (const filePath of modulesInsideAddedDirectory) {
955
+ await updateModuleDependenciesInGraph(filePath);
956
+ }
957
+ break;
958
+ }
959
+ case "unlink":
960
+ if (isJavascriptModule(pathToModified)) {
961
+ removeModuleFromGraph(pathToModified);
962
+ }
963
+ break;
964
+ case "unlinkDir": {
965
+ const filesInsideDeletedDirectory = await readAllFilesInsideDirectory(pathToModified);
966
+ const modulesInsideDeletedDirectory = filesInsideDeletedDirectory.filter(isJavascriptModule);
967
+ for await (const filePath of modulesInsideDeletedDirectory) {
968
+ removeModuleFromGraph(filePath);
969
+ }
970
+ break;
971
+ }
972
+ }
973
+ },
974
+ {
975
+ resolveDependentsOf: function resolveDependentsOf(pathToModule) {
976
+ const moduleEntry = graph[pathToModule];
977
+ const dependentPaths = [];
978
+ if (moduleEntry) {
979
+ for (const dependentPath of moduleEntry.dependentPaths) {
980
+ const dependentsOfDependent = resolveDependentsOf(dependentPath);
981
+ dependentPaths.push(...dependentsOfDependent);
982
+ dependentPaths.push(dependentPath);
983
+ }
984
+ }
985
+ return dependentPaths;
986
+ }
987
+ }
988
+ ];
989
+ };
990
+
991
+ // src/utils/preview/hot-reloading/setup-hot-reloading.ts
992
+ var setupHotreloading = async (devServer2, emailDirRelativePath) => {
993
+ let clients = [];
994
+ const io = new SocketServer(devServer2);
995
+ io.on("connection", (client) => {
996
+ clients.push(client);
997
+ client.on("disconnect", () => {
998
+ clients = clients.filter((item) => item !== client);
999
+ });
1000
+ });
1001
+ let changes = [];
1002
+ const reload = debounce(() => {
1003
+ clients.forEach((client) => {
1004
+ client.emit(
1005
+ "reload",
1006
+ changes.filter(
1007
+ (change) => (
1008
+ // Ensures only changes inside the emails directory are emitted
1009
+ path9.resolve(absolutePathToEmailsDirectory, change.filename).startsWith(absolutePathToEmailsDirectory)
1010
+ )
1011
+ )
1012
+ );
1013
+ });
1014
+ changes = [];
1015
+ }, 150);
1016
+ const absolutePathToEmailsDirectory = path9.resolve(
1017
+ process.cwd(),
1018
+ emailDirRelativePath
1019
+ );
1020
+ const [dependencyGraph, updateDependencyGraph, { resolveDependentsOf }] = await createDependencyGraph(absolutePathToEmailsDirectory);
1021
+ const watcher = watch("", {
1022
+ ignoreInitial: true,
1023
+ cwd: absolutePathToEmailsDirectory
1024
+ });
1025
+ const getFilesOutsideEmailsDirectory = () => Object.keys(dependencyGraph).filter(
1026
+ (p) => path9.relative(absolutePathToEmailsDirectory, p).startsWith("..")
1027
+ );
1028
+ let filesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
1029
+ for (const p of filesOutsideEmailsDirectory) {
1030
+ watcher.add(p);
1031
+ }
1032
+ const exit = async () => {
1033
+ await watcher.close();
1034
+ };
1035
+ process.on("SIGINT", exit);
1036
+ process.on("uncaughtException", exit);
1037
+ watcher.on("all", async (event, relativePathToChangeTarget) => {
1038
+ const file = relativePathToChangeTarget.split(path9.sep);
1039
+ if (file.length === 0) {
1040
+ return;
1041
+ }
1042
+ const pathToChangeTarget = path9.resolve(
1043
+ absolutePathToEmailsDirectory,
1044
+ relativePathToChangeTarget
1045
+ );
1046
+ await updateDependencyGraph(event, pathToChangeTarget);
1047
+ const newFilesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
1048
+ for (const p of filesOutsideEmailsDirectory) {
1049
+ if (!newFilesOutsideEmailsDirectory.includes(p)) {
1050
+ watcher.unwatch(p);
1051
+ }
1052
+ }
1053
+ for (const p of newFilesOutsideEmailsDirectory) {
1054
+ if (!filesOutsideEmailsDirectory.includes(p)) {
1055
+ watcher.add(p);
1056
+ }
1057
+ }
1058
+ filesOutsideEmailsDirectory = newFilesOutsideEmailsDirectory;
1059
+ changes.push({
1060
+ event,
1061
+ filename: relativePathToChangeTarget
1062
+ });
1063
+ for (const dependentPath of resolveDependentsOf(pathToChangeTarget)) {
1064
+ changes.push({
1065
+ event: "change",
1066
+ filename: path9.relative(absolutePathToEmailsDirectory, dependentPath)
1067
+ });
1068
+ }
1069
+ reload();
1070
+ });
1071
+ return watcher;
1072
+ };
1073
+
1074
+ // src/utils/tree.ts
1075
+ import { promises as fs5 } from "node:fs";
1076
+ import os from "node:os";
1077
+ import path10 from "node:path";
1078
+ var SYMBOLS = {
1079
+ BRANCH: "\u251C\u2500\u2500 ",
1080
+ EMPTY: "",
1081
+ INDENT: " ",
1082
+ LAST_BRANCH: "\u2514\u2500\u2500 ",
1083
+ VERTICAL: "\u2502 "
1084
+ };
1085
+ var getTreeLines = async (dirPath, depth, currentDepth = 0) => {
1086
+ const base = process.cwd();
1087
+ const dirFullpath = path10.resolve(base, dirPath);
1088
+ const dirname2 = path10.basename(dirFullpath);
1089
+ let lines = [dirname2];
1090
+ const dirStat = await fs5.stat(dirFullpath);
1091
+ if (dirStat.isDirectory() && currentDepth < depth) {
1092
+ const childDirents = await fs5.readdir(dirFullpath, { withFileTypes: true });
1093
+ childDirents.sort((a, b) => {
1094
+ if (a.isDirectory() && b.isFile()) {
1095
+ return -1;
1096
+ }
1097
+ if (a.isFile() && b.isDirectory()) {
1098
+ return 1;
1099
+ }
1100
+ return b.name > a.name ? -1 : 1;
1101
+ });
1102
+ for (let i = 0; i < childDirents.length; i++) {
1103
+ const dirent = childDirents[i];
1104
+ const isLast = i === childDirents.length - 1;
1105
+ const branchingSymbol = isLast ? SYMBOLS.LAST_BRANCH : SYMBOLS.BRANCH;
1106
+ const verticalSymbol = isLast ? SYMBOLS.INDENT : SYMBOLS.VERTICAL;
1107
+ if (dirent.isFile()) {
1108
+ lines.push(`${branchingSymbol}${dirent.name}`);
1109
+ } else {
1110
+ const pathToDirectory = path10.join(dirFullpath, dirent.name);
1111
+ const treeLinesForSubDirectory = await getTreeLines(
1112
+ pathToDirectory,
1113
+ depth,
1114
+ currentDepth + 1
1115
+ );
1116
+ lines = lines.concat(
1117
+ treeLinesForSubDirectory.map(
1118
+ (line, index) => index === 0 ? `${branchingSymbol}${line}` : `${verticalSymbol}${line}`
1119
+ )
1120
+ );
1121
+ }
1122
+ }
1123
+ }
1124
+ return lines;
1125
+ };
1126
+ var tree = async (dirPath, depth) => {
1127
+ const lines = await getTreeLines(dirPath, depth);
1128
+ return lines.join(os.EOL);
1129
+ };
1130
+
1131
+ // src/commands/dev.ts
1132
+ var dev = async ({ dir: emailsDirRelativePath, port }) => {
1133
+ try {
1134
+ if (!fs6.existsSync(emailsDirRelativePath)) {
1135
+ console.error(`Missing ${emailsDirRelativePath} folder`);
1136
+ process.exit(1);
1137
+ }
1138
+ const devServer2 = await startDevServer(
1139
+ emailsDirRelativePath,
1140
+ emailsDirRelativePath,
1141
+ // defaults to ./emails/static for the static files that are served to the preview
1142
+ Number.parseInt(port)
1143
+ );
1144
+ await setupHotreloading(devServer2, emailsDirRelativePath);
1145
+ } catch (error) {
1146
+ console.log(error);
1147
+ process.exit(1);
1148
+ }
1149
+ };
1150
+
1151
+ // src/commands/export.ts
1152
+ import fs8, { unlinkSync, writeFileSync } from "node:fs";
1153
+ import { createRequire } from "node:module";
1154
+ import path12 from "node:path";
1155
+ import url3 from "node:url";
1156
+ import { build as build2 } from "esbuild";
1157
+ import { glob } from "glob";
1158
+ import logSymbols4 from "log-symbols";
1159
+ import normalize from "normalize-path";
1160
+ import ora3 from "ora";
1161
+
1162
+ // src/utils/esbuild/renderring-utilities-exporter.ts
1163
+ import { promises as fs7 } from "node:fs";
1164
+ import path11 from "node:path";
1165
+
1166
+ // src/utils/esbuild/escape-string-for-regex.ts
1167
+ function escapeStringForRegex(string) {
1168
+ return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
1169
+ }
1170
+
1171
+ // src/utils/esbuild/renderring-utilities-exporter.ts
1172
+ var renderingUtilitiesExporter = (emailTemplates) => ({
1173
+ name: "rendering-utilities-exporter",
1174
+ setup: (b) => {
1175
+ b.onLoad(
1176
+ {
1177
+ filter: new RegExp(
1178
+ emailTemplates.map((emailPath) => escapeStringForRegex(emailPath)).join("|")
1179
+ )
1180
+ },
1181
+ async ({ path: pathToFile }) => {
1182
+ return {
1183
+ contents: `${await fs7.readFile(pathToFile, "utf8")};
1184
+ export { render } from 'react-email-module-that-will-export-render'
1185
+ export { createElement as reactEmailCreateReactElement } from 'react';
1186
+ `,
1187
+ loader: path11.extname(pathToFile).slice(1)
1188
+ };
1189
+ }
1190
+ );
1191
+ b.onResolve(
1192
+ { filter: /^react-email-module-that-will-export-render$/ },
1193
+ async (args) => {
1194
+ const options = {
1195
+ kind: "import-statement",
1196
+ importer: args.importer,
1197
+ resolveDir: args.resolveDir,
1198
+ namespace: args.namespace
1199
+ };
1200
+ let result = await b.resolve("@react-email/render", options);
1201
+ if (result.errors.length === 0) {
1202
+ return result;
1203
+ }
1204
+ result = await b.resolve("@react-email/components", options);
1205
+ if (result.errors.length > 0 && result.errors[0]) {
1206
+ 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?";
1207
+ }
1208
+ return result;
1209
+ }
1210
+ );
1211
+ }
1212
+ });
1213
+
1214
+ // src/commands/export.ts
1215
+ var getEmailTemplatesFromDirectory = (emailDirectory) => {
1216
+ const templatePaths = [];
1217
+ emailDirectory.emailFilenames.forEach(
1218
+ (filename3) => templatePaths.push(path12.join(emailDirectory.absolutePath, filename3))
1219
+ );
1220
+ emailDirectory.subDirectories.forEach((directory) => {
1221
+ templatePaths.push(...getEmailTemplatesFromDirectory(directory));
1222
+ });
1223
+ return templatePaths;
1224
+ };
1225
+ var filename2 = url3.fileURLToPath(import.meta.url);
1226
+ var require2 = createRequire(filename2);
1227
+ var exportTemplates = async (pathToWhereEmailMarkupShouldBeDumped, emailsDirectoryPath, options) => {
1228
+ if (fs8.existsSync(pathToWhereEmailMarkupShouldBeDumped)) {
1229
+ fs8.rmSync(pathToWhereEmailMarkupShouldBeDumped, { recursive: true });
1230
+ }
1231
+ let spinner;
1232
+ if (!options.silent) {
1233
+ spinner = ora3("Preparing files...\n").start();
1234
+ registerSpinnerAutostopping(spinner);
1235
+ }
1236
+ const emailsDirectoryMetadata = await getEmailsDirectoryMetadata(
1237
+ path12.resolve(process.cwd(), emailsDirectoryPath),
1238
+ true
1239
+ );
1240
+ if (typeof emailsDirectoryMetadata === "undefined") {
1241
+ if (spinner) {
1242
+ spinner.stopAndPersist({
1243
+ symbol: logSymbols4.error,
1244
+ text: `Could not find the directory at ${emailsDirectoryPath}`
1245
+ });
1246
+ }
1247
+ return;
1248
+ }
1249
+ const allTemplates = getEmailTemplatesFromDirectory(emailsDirectoryMetadata);
1250
+ try {
1251
+ await build2({
1252
+ bundle: true,
1253
+ entryPoints: allTemplates,
1254
+ format: "cjs",
1255
+ jsx: "transform",
1256
+ loader: { ".js": "jsx" },
1257
+ logLevel: "silent",
1258
+ outExtension: { ".js": ".cjs" },
1259
+ outdir: pathToWhereEmailMarkupShouldBeDumped,
1260
+ platform: "node",
1261
+ plugins: [renderingUtilitiesExporter(allTemplates)],
1262
+ write: true
1263
+ });
1264
+ } catch (exception) {
1265
+ if (spinner) {
1266
+ spinner.stopAndPersist({
1267
+ symbol: logSymbols4.error,
1268
+ text: "Failed to build emails"
1269
+ });
1270
+ }
1271
+ const buildFailure = exception;
1272
+ console.error(`
1273
+ ${buildFailure.message}`);
1274
+ process.exit(1);
1275
+ }
1276
+ if (spinner) {
1277
+ spinner.succeed();
1278
+ }
1279
+ const allBuiltTemplates = glob.sync(
1280
+ normalize(`${pathToWhereEmailMarkupShouldBeDumped}/**/*.cjs`),
1281
+ {
1282
+ absolute: true
1283
+ }
1284
+ );
1285
+ for await (const template of allBuiltTemplates) {
1286
+ try {
1287
+ if (spinner) {
1288
+ spinner.text = `rendering ${template.split("/").pop()}`;
1289
+ spinner.render();
1290
+ }
1291
+ delete require2.cache[template];
1292
+ const emailModule = require2(template);
1293
+ const rendered = await emailModule.render(
1294
+ emailModule.reactEmailCreateReactElement(emailModule.default, {}),
1295
+ options
1296
+ );
1297
+ const htmlPath = template.replace(
1298
+ ".cjs",
1299
+ options.plainText ? ".txt" : ".html"
1300
+ );
1301
+ writeFileSync(htmlPath, rendered);
1302
+ unlinkSync(template);
1303
+ } catch (exception) {
1304
+ if (spinner) {
1305
+ spinner.stopAndPersist({
1306
+ symbol: logSymbols4.error,
1307
+ text: `failed when rendering ${template.split("/").pop()}`
1308
+ });
1309
+ }
1310
+ console.error(exception);
1311
+ process.exit(1);
1312
+ }
1313
+ }
1314
+ if (spinner) {
1315
+ spinner.succeed("Rendered all files");
1316
+ spinner.text = "Copying static files";
1317
+ spinner.render();
1318
+ }
1319
+ const staticDirectoryPath = path12.join(emailsDirectoryPath, "static");
1320
+ if (fs8.existsSync(staticDirectoryPath)) {
1321
+ const pathToDumpStaticFilesInto = path12.join(
1322
+ pathToWhereEmailMarkupShouldBeDumped,
1323
+ "static"
1324
+ );
1325
+ if (fs8.existsSync(pathToDumpStaticFilesInto))
1326
+ await fs8.promises.rm(pathToDumpStaticFilesInto, { recursive: true });
1327
+ try {
1328
+ await fs8.promises.cp(staticDirectoryPath, pathToDumpStaticFilesInto, {
1329
+ recursive: true
1330
+ });
1331
+ } catch (exception) {
1332
+ console.error(exception);
1333
+ if (spinner) {
1334
+ spinner.stopAndPersist({
1335
+ symbol: logSymbols4.error,
1336
+ text: "Failed to copy static files"
1337
+ });
1338
+ }
1339
+ console.error(
1340
+ `Something went wrong while copying the file to ${pathToWhereEmailMarkupShouldBeDumped}/static, ${exception}`
1341
+ );
1342
+ process.exit(1);
1343
+ }
1344
+ }
1345
+ if (spinner && !options.silent) {
1346
+ spinner.succeed();
1347
+ const fileTree = await tree(pathToWhereEmailMarkupShouldBeDumped, 4);
1348
+ console.log(fileTree);
1349
+ spinner.stopAndPersist({
1350
+ symbol: logSymbols4.success,
1351
+ text: "Successfully exported emails"
1352
+ });
1353
+ }
1354
+ };
1355
+
1356
+ // src/commands/start.ts
1357
+ import { spawn as spawn2 } from "node:child_process";
1358
+ import fs9 from "node:fs";
1359
+ import path13 from "node:path";
1360
+ var start = async () => {
1361
+ try {
1362
+ const previewServerLocation = await getPreviewServerLocation();
1363
+ const usersProjectLocation = process.cwd();
1364
+ const builtPreviewPath = path13.resolve(
1365
+ usersProjectLocation,
1366
+ "./.react-email"
1367
+ );
1368
+ if (!fs9.existsSync(builtPreviewPath)) {
1369
+ console.error(
1370
+ "Could not find .react-email, maybe you haven't ran email build?"
1371
+ );
1372
+ process.exit(1);
1373
+ }
1374
+ const nextStart = spawn2("npx", ["next", "start", builtPreviewPath], {
1375
+ cwd: previewServerLocation,
1376
+ stdio: "inherit"
1377
+ });
1378
+ process.on("SIGINT", () => {
1379
+ nextStart.kill("SIGINT");
1380
+ });
1381
+ nextStart.on("exit", (code) => {
1382
+ process.exit(code ?? 0);
1383
+ });
1384
+ } catch (error) {
1385
+ console.log(error);
1386
+ process.exit(1);
1387
+ }
1388
+ };
1389
+
1390
+ // src/index.ts
1391
+ var PACKAGE_NAME = "react-email";
1392
+ program.name(PACKAGE_NAME).description("A live preview of your emails right in your browser").version(package_default.version);
1393
+ 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);
1394
+ 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(
1395
+ "-p --packageManager <name>",
1396
+ "Package name to use on installation on `.react-email`",
1397
+ "npm"
1398
+ ).action(build);
1399
+ program.command("start").description('Runs the built preview app that is inside of ".react-email"').action(start);
1400
+ 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(
1401
+ "-s, --silent",
1402
+ "To, or not to show a spinner with process information",
1403
+ false
1404
+ ).action(
1405
+ ({ outDir, pretty, plainText, silent, dir: srcDir }) => exportTemplates(outDir, srcDir, { silent, plainText, pretty })
1406
+ );
1407
+ program.parse();