react-email 3.0.0 → 3.0.1

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 (55) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/cli/index.js +10 -10
  3. package/dist/cli/index.mjs +9 -9
  4. package/dist/preview/.next/BUILD_ID +1 -1
  5. package/dist/preview/.next/app-build-manifest.json +9 -9
  6. package/dist/preview/.next/app-path-routes-manifest.json +1 -1
  7. package/dist/preview/.next/build-manifest.json +3 -3
  8. package/dist/preview/.next/cache/eslint/.cache_6f202j +1 -0
  9. package/dist/preview/.next/cache/webpack/client-production/0.pack +0 -0
  10. package/dist/preview/.next/cache/webpack/client-production/index.pack +0 -0
  11. package/dist/preview/.next/cache/webpack/edge-server-production/index.pack +0 -0
  12. package/dist/preview/.next/cache/webpack/server-production/0.pack +0 -0
  13. package/dist/preview/.next/cache/webpack/server-production/index.pack +0 -0
  14. package/dist/preview/.next/next-minimal-server.js.nft.json +1 -1
  15. package/dist/preview/.next/next-server.js.nft.json +1 -1
  16. package/dist/preview/.next/prerender-manifest.json +1 -1
  17. package/dist/preview/.next/required-server-files.json +1 -1
  18. package/dist/preview/.next/server/app/_not-found/page.js +1 -1
  19. package/dist/preview/.next/server/app/_not-found/page.js.nft.json +1 -1
  20. package/dist/preview/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  21. package/dist/preview/.next/server/app/favicon.ico/route.js +3 -3
  22. package/dist/preview/.next/server/app/page.js +1 -1
  23. package/dist/preview/.next/server/app/page.js.nft.json +1 -1
  24. package/dist/preview/.next/server/app/page_client-reference-manifest.js +1 -1
  25. package/dist/preview/.next/server/app/preview/[...slug]/page.js +5 -5
  26. package/dist/preview/.next/server/app/preview/[...slug]/page.js.nft.json +1 -1
  27. package/dist/preview/.next/server/app/preview/[...slug]/page_client-reference-manifest.js +1 -1
  28. package/dist/preview/.next/server/app-paths-manifest.json +1 -1
  29. package/dist/preview/.next/server/chunks/{949.js → 415.js} +1 -1
  30. package/dist/preview/.next/server/chunks/{85.js → 575.js} +4 -4
  31. package/dist/preview/.next/server/chunks/593.js +1 -1
  32. package/dist/preview/.next/server/chunks/835.js +1 -1
  33. package/dist/preview/.next/server/middleware-build-manifest.js +1 -1
  34. package/dist/preview/.next/server/next-font-manifest.js +1 -1
  35. package/dist/preview/.next/server/next-font-manifest.json +1 -1
  36. package/dist/preview/.next/server/pages/500.html +1 -1
  37. package/dist/preview/.next/server/server-reference-manifest.js +1 -1
  38. package/dist/preview/.next/server/server-reference-manifest.json +1 -1
  39. package/dist/preview/.next/static/chunks/{739-50e72482bbc45590.js → 739-2c6de7a98f0ed2f8.js} +1 -1
  40. package/dist/preview/.next/static/chunks/app/layout-5f27947cf5e208fc.js +1 -0
  41. package/dist/preview/.next/static/chunks/app/{page-ec31790465d856cb.js → page-1c752add061e09ac.js} +1 -1
  42. package/dist/preview/.next/static/chunks/app/preview/[...slug]/{page-a683d0be240013ae.js → page-e0a2bd1fabf8ccac.js} +1 -1
  43. package/dist/preview/.next/static/chunks/{main-app-3901b786a8a59cbd.js → main-app-ba9de861208f5226.js} +1 -1
  44. package/dist/preview/.next/trace +52 -52
  45. package/dist/preview/.next/types/app/layout.ts +1 -1
  46. package/dist/preview/.next/types/app/preview/[...slug]/page.ts +1 -1
  47. package/package.json +1 -1
  48. package/cli/index.d.mts +0 -1
  49. package/cli/index.d.ts +0 -1
  50. package/cli/index.js +0 -2684
  51. package/cli/index.mjs +0 -1234
  52. package/dist/preview/.next/cache/eslint/.cache_1nlfowd +0 -1
  53. package/dist/preview/.next/static/chunks/app/layout-a2a755f27614eb27.js +0 -1
  54. /package/dist/preview/.next/static/{ogc8W4T2H5KDJzjc2H1rP → AJ4wdeFcgkOgG_NW4Vcri}/_buildManifest.js +0 -0
  55. /package/dist/preview/.next/static/{ogc8W4T2H5KDJzjc2H1rP → AJ4wdeFcgkOgG_NW4Vcri}/_ssgManifest.js +0 -0
package/cli/index.mjs DELETED
@@ -1,1234 +0,0 @@
1
- #!/usr/bin/env node
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined")
6
- return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
-
10
- // src/cli/index.ts
11
- import { program } from "commander";
12
-
13
- // package.json
14
- var package_default = {
15
- name: "react-email",
16
- version: "2.1.7-canary.2",
17
- description: "A live preview of your emails right in your browser.",
18
- bin: {
19
- email: "./cli/index.js"
20
- },
21
- scripts: {
22
- build: "tsup",
23
- dev: "tsup --watch",
24
- test: "vitest run",
25
- "test:watch": "vitest",
26
- clean: "rm -rf dist",
27
- lint: "eslint . && tsc"
28
- },
29
- license: "MIT",
30
- repository: {
31
- type: "git",
32
- url: "https://github.com/resend/react-email.git",
33
- directory: "packages/react-email"
34
- },
35
- keywords: [
36
- "react",
37
- "email"
38
- ],
39
- engines: {
40
- node: ">=18.0.0"
41
- },
42
- dependencies: {
43
- "@babel/core": "7.24.5",
44
- "@babel/parser": "7.24.5",
45
- "@radix-ui/colors": "1.0.1",
46
- "@radix-ui/react-collapsible": "1.1.0",
47
- "@radix-ui/react-popover": "1.1.1",
48
- "@radix-ui/react-slot": "1.1.0",
49
- "@radix-ui/react-toggle-group": "1.1.0",
50
- "@radix-ui/react-tooltip": "1.1.1",
51
- "@swc/core": "1.3.101",
52
- "@types/react": "^18.2.0",
53
- "@types/react-dom": "^18.2.0",
54
- "@types/webpack": "5.28.5",
55
- autoprefixer: "10.4.14",
56
- chalk: "4.1.2",
57
- chokidar: "3.6.0",
58
- clsx: "2.1.0",
59
- commander: "11.1.0",
60
- debounce: "2.0.0",
61
- esbuild: "0.19.11",
62
- "eslint-config-prettier": "9.0.0",
63
- "eslint-config-turbo": "1.10.12",
64
- "framer-motion": "12.0.0-alpha.0",
65
- glob: "10.3.4",
66
- "log-symbols": "4.1.0",
67
- "mime-types": "2.1.35",
68
- next: "14.2.3",
69
- "normalize-path": "3.0.0",
70
- ora: "5.4.1",
71
- postcss: "8.4.40",
72
- "prism-react-renderer": "2.1.0",
73
- react: "18.3.1",
74
- "react-dom": "18.3.1",
75
- "socket.io": "4.7.5",
76
- "socket.io-client": "4.7.5",
77
- sonner: "1.3.1",
78
- "source-map-js": "1.0.2",
79
- "stacktrace-parser": "0.1.10",
80
- "tailwind-merge": "2.2.0",
81
- tailwindcss: "3.4.0",
82
- typescript: "5.1.6"
83
- },
84
- devDependencies: {
85
- "@react-email/components": "workspace:*",
86
- "@react-email/render": "workspace:*",
87
- "@types/babel__core": "7.20.5",
88
- "@types/fs-extra": "11.0.1",
89
- "@types/mime-types": "2.1.4",
90
- "@types/node": "18.0.0",
91
- "@types/normalize-path": "3.0.2",
92
- "@vercel/style-guide": "5.1.0",
93
- eslint: "8.50.0",
94
- tsup: "7.2.0",
95
- tsx: "4.9.0",
96
- vitest: "1.1.3"
97
- }
98
- };
99
-
100
- // src/cli/commands/dev.ts
101
- import fs4 from "fs";
102
-
103
- // src/cli/utils/tree.ts
104
- import { promises as fs } from "fs";
105
- import os from "os";
106
- import path from "path";
107
- var SYMBOLS = {
108
- BRANCH: "\u251C\u2500\u2500 ",
109
- EMPTY: "",
110
- INDENT: " ",
111
- LAST_BRANCH: "\u2514\u2500\u2500 ",
112
- VERTICAL: "\u2502 "
113
- };
114
- var getTreeLines = async (dirPath, depth, currentDepth = 0) => {
115
- const base = process.cwd();
116
- const dirFullpath = path.resolve(base, dirPath);
117
- const dirname = path.basename(dirFullpath);
118
- let lines = [dirname];
119
- const dirStat = await fs.stat(dirFullpath);
120
- if (dirStat.isDirectory() && currentDepth < depth) {
121
- const childDirents = await fs.readdir(dirFullpath, { withFileTypes: true });
122
- childDirents.sort((a, b) => {
123
- if (a.isDirectory() && b.isFile()) {
124
- return -1;
125
- } else if (a.isFile() && b.isDirectory()) {
126
- return 1;
127
- }
128
- return b.name > a.name ? -1 : 1;
129
- });
130
- for (let i = 0; i < childDirents.length; i++) {
131
- const dirent = childDirents[i];
132
- const isLast = i === childDirents.length - 1;
133
- const branchingSymbol = isLast ? SYMBOLS.LAST_BRANCH : SYMBOLS.BRANCH;
134
- const verticalSymbol = isLast ? SYMBOLS.INDENT : SYMBOLS.VERTICAL;
135
- if (dirent.isFile()) {
136
- lines.push(`${branchingSymbol}${dirent.name}`);
137
- } else {
138
- const pathToDirectory = path.join(dirFullpath, dirent.name);
139
- const treeLinesForSubDirectory = await getTreeLines(
140
- pathToDirectory,
141
- depth,
142
- currentDepth + 1
143
- );
144
- lines = lines.concat(
145
- treeLinesForSubDirectory.map(
146
- (line, index) => index === 0 ? `${branchingSymbol}${line}` : `${verticalSymbol}${line}`
147
- )
148
- );
149
- }
150
- }
151
- }
152
- return lines;
153
- };
154
- var tree = async (dirPath, depth) => {
155
- const lines = await getTreeLines(dirPath, depth);
156
- return lines.join(os.EOL);
157
- };
158
-
159
- // src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
160
- import path6 from "path";
161
- import { Server as SocketServer } from "socket.io";
162
- import { watch } from "chokidar";
163
- import debounce from "debounce";
164
-
165
- // src/cli/utils/preview/hot-reloading/create-dependency-graph.ts
166
- import path5 from "path";
167
- import { existsSync, promises as fs3, statSync } from "fs";
168
-
169
- // src/cli/utils/preview/hot-reloading/get-imported-modules.ts
170
- import { traverse } from "@babel/core";
171
- import { parse } from "@babel/parser";
172
- var getImportedModules = (contents) => {
173
- const importedPaths = [];
174
- const parsedContents = parse(contents, {
175
- sourceType: "unambiguous",
176
- strictMode: false,
177
- errorRecovery: true,
178
- plugins: ["jsx", "typescript", "decorators"]
179
- });
180
- traverse(parsedContents, {
181
- ImportDeclaration({ node }) {
182
- importedPaths.push(node.source.value);
183
- },
184
- ExportAllDeclaration({ node }) {
185
- importedPaths.push(node.source.value);
186
- },
187
- ExportNamedDeclaration({ node }) {
188
- if (node.source) {
189
- importedPaths.push(node.source.value);
190
- }
191
- },
192
- CallExpression({ node }) {
193
- if ("name" in node.callee && node.callee.name === "require") {
194
- if (node.arguments.length === 1) {
195
- const importPathNode = node.arguments[0];
196
- if (importPathNode.type === "StringLiteral") {
197
- importedPaths.push(importPathNode.value);
198
- }
199
- }
200
- }
201
- }
202
- });
203
- return importedPaths;
204
- };
205
-
206
- // src/cli/utils/preview/start-dev-server.ts
207
- import path4 from "path";
208
- import http from "http";
209
- import url from "url";
210
- import next from "next";
211
- import ora from "ora";
212
- import logSymbols from "log-symbols";
213
- import chalk from "chalk";
214
-
215
- // src/cli/utils/close-ora-on-sigint.ts
216
- var closeOraOnSIGNIT = (spinner) => {
217
- process.on("SIGINT", () => {
218
- spinner.stop();
219
- });
220
- };
221
-
222
- // src/cli/utils/preview/serve-static-file.ts
223
- import path2 from "path";
224
- import { promises as fs2 } from "fs";
225
- import { lookup } from "mime-types";
226
- var serveStaticFile = async (res, parsedUrl, staticDirRelativePath) => {
227
- const staticBaseDir = path2.join(process.cwd(), staticDirRelativePath);
228
- const pathname = parsedUrl.pathname;
229
- const ext = path2.parse(pathname).ext;
230
- let fileAbsolutePath = path2.join(staticBaseDir, pathname);
231
- const fileHandle = await fs2.open(fileAbsolutePath, "r");
232
- try {
233
- const fileData = await fs2.readFile(fileHandle);
234
- res.setHeader("Content-type", lookup(ext) || "text/plain");
235
- res.end(fileData);
236
- } catch (exception) {
237
- console.error(
238
- `Could not read file at ${fileAbsolutePath} to be served, here's the exception:`,
239
- exception
240
- );
241
- res.statusCode = 500;
242
- res.end(
243
- `Could not read file to be served! Check your terminal for more information.`
244
- );
245
- } finally {
246
- fileHandle.close();
247
- }
248
- };
249
-
250
- // src/cli/utils/preview/get-env-variables-for-preview-app.ts
251
- import path3 from "path";
252
- var getEnvVariablesForPreviewApp = (relativePathToEmailsDirectory, cliPackageLocation, cwd) => {
253
- return {
254
- NEXT_PUBLIC_EMAILS_DIR_RELATIVE_PATH: relativePathToEmailsDirectory,
255
- NEXT_PUBLIC_CLI_PACKAGE_LOCATION: cliPackageLocation,
256
- NEXT_PUBLIC_OS_PATH_SEPARATOR: path3.sep,
257
- NEXT_PUBLIC_USER_PROJECT_LOCATION: cwd
258
- };
259
- };
260
-
261
- // src/cli/utils/preview/start-dev-server.ts
262
- var devServer;
263
- var safeAsyncServerListen = (server, port) => {
264
- return new Promise((resolve2) => {
265
- server.listen(port, () => {
266
- resolve2({ portAlreadyInUse: false });
267
- });
268
- server.on("error", (e) => {
269
- if (e.code === "EADDRINUSE") {
270
- resolve2({ portAlreadyInUse: true });
271
- }
272
- });
273
- });
274
- };
275
- var isRunningBuilt = __filename.endsWith(path4.join("cli", "index.js"));
276
- var cliPacakgeLocation = isRunningBuilt ? path4.resolve(__dirname, "..") : path4.resolve(__dirname, "../../../..");
277
- var startDevServer = async (emailsDirRelativePath, staticBaseDirRelativePath, port) => {
278
- devServer = http.createServer((req, res) => {
279
- if (!req.url) {
280
- res.end(404);
281
- return;
282
- }
283
- const parsedUrl = url.parse(req.url, true);
284
- res.setHeader(
285
- "Cache-Control",
286
- "no-cache, max-age=0, must-revalidate, no-store"
287
- );
288
- res.setHeader("Pragma", "no-cache");
289
- res.setHeader("Expires", "-1");
290
- try {
291
- if (parsedUrl.path && parsedUrl.path.includes("static/") && !parsedUrl.path.includes("_next/static/")) {
292
- void serveStaticFile(res, parsedUrl, staticBaseDirRelativePath);
293
- } else if (!isNextReady) {
294
- void nextReadyPromise.then(
295
- () => nextHandleRequest?.(req, res, parsedUrl)
296
- );
297
- } else {
298
- void nextHandleRequest?.(req, res, parsedUrl);
299
- }
300
- } catch (e) {
301
- console.error("caught error", e);
302
- res.writeHead(500);
303
- res.end();
304
- }
305
- });
306
- const { portAlreadyInUse } = await safeAsyncServerListen(devServer, port);
307
- if (!portAlreadyInUse) {
308
- console.log(chalk.greenBright(` React Email ${package_default.version}`));
309
- console.log(` Running preview at: http://localhost:${port}
310
- `);
311
- } else {
312
- const nextPortToTry = port + 1;
313
- console.warn(
314
- ` ${logSymbols.warning} Port ${port} is already in use, trying ${nextPortToTry}`
315
- );
316
- return startDevServer(
317
- emailsDirRelativePath,
318
- staticBaseDirRelativePath,
319
- nextPortToTry
320
- );
321
- }
322
- devServer.on("close", async () => {
323
- await app.close();
324
- });
325
- devServer.on("error", (e) => {
326
- console.error(
327
- ` ${logSymbols.error} preview server error: `,
328
- JSON.stringify(e)
329
- );
330
- process.exit(1);
331
- });
332
- const spinner = ora({
333
- text: "Getting react-email preview server ready...\n",
334
- prefixText: " "
335
- }).start();
336
- closeOraOnSIGNIT(spinner);
337
- const timeBeforeNextReady = performance.now();
338
- process.env = {
339
- ...process.env,
340
- ...getEnvVariablesForPreviewApp(
341
- // If we don't do normalization here, stuff like https://github.com/resend/react-email/issues/1354 happens.
342
- path4.normalize(emailsDirRelativePath),
343
- cliPacakgeLocation,
344
- process.cwd()
345
- )
346
- };
347
- const app = next({
348
- // passing in env here does not get the environment variables there
349
- dev: true,
350
- hostname: "localhost",
351
- port,
352
- dir: cliPacakgeLocation
353
- });
354
- let isNextReady = false;
355
- const nextReadyPromise = app.prepare();
356
- await nextReadyPromise;
357
- isNextReady = true;
358
- const nextHandleRequest = app.getRequestHandler();
359
- const secondsToNextReady = ((performance.now() - timeBeforeNextReady) / 1e3).toFixed(1);
360
- spinner.stopAndPersist({
361
- text: `Ready in ${secondsToNextReady}s
362
- `,
363
- symbol: logSymbols.success
364
- });
365
- return devServer;
366
- };
367
- var makeExitHandler = (options) => (_codeOrSignal) => {
368
- if (typeof devServer !== "undefined") {
369
- console.log("\nshutting down dev server");
370
- devServer.close();
371
- devServer = void 0;
372
- }
373
- if (options?.shouldKillProcess) {
374
- process.exit(options.killWithErrorCode ? 1 : 0);
375
- }
376
- };
377
- process.on("exit", makeExitHandler());
378
- process.on(
379
- "SIGINT",
380
- makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
381
- );
382
- process.on(
383
- "SIGUSR1",
384
- makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
385
- );
386
- process.on(
387
- "SIGUSR2",
388
- makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
389
- );
390
- process.on(
391
- "uncaughtException",
392
- makeExitHandler({ shouldKillProcess: true, killWithErrorCode: true })
393
- );
394
-
395
- // src/cli/utils/preview/hot-reloading/create-dependency-graph.ts
396
- var readAllFilesInsideDirectory = async (directory) => {
397
- let allFilePaths = [];
398
- const topLevelDirents = await fs3.readdir(directory, { withFileTypes: true });
399
- for await (const dirent of topLevelDirents) {
400
- const pathToDirent = path5.join(directory, dirent.name);
401
- if (dirent.isDirectory()) {
402
- allFilePaths = allFilePaths.concat(
403
- await readAllFilesInsideDirectory(pathToDirent)
404
- );
405
- } else {
406
- allFilePaths.push(pathToDirent);
407
- }
408
- }
409
- return allFilePaths;
410
- };
411
- var isJavascriptModule = (filePath) => {
412
- const extensionName = path5.extname(filePath);
413
- return [".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs"].includes(extensionName);
414
- };
415
- var checkFileExtensionsUntilItExists = (pathWithoutExtension) => {
416
- if (existsSync(`${pathWithoutExtension}.ts`)) {
417
- return `${pathWithoutExtension}.ts`;
418
- } else if (existsSync(`${pathWithoutExtension}.tsx`)) {
419
- return `${pathWithoutExtension}.tsx`;
420
- } else if (existsSync(`${pathWithoutExtension}.js`)) {
421
- return `${pathWithoutExtension}.js`;
422
- } else if (existsSync(`${pathWithoutExtension}.jsx`)) {
423
- return `${pathWithoutExtension}.jsx`;
424
- } else if (existsSync(`${pathWithoutExtension}.mjs`)) {
425
- return `${pathWithoutExtension}.mjs`;
426
- } else if (existsSync(`${pathWithoutExtension}.cjs`)) {
427
- return `${pathWithoutExtension}.cjs`;
428
- }
429
- };
430
- var createDependencyGraph = async (directory) => {
431
- const filePaths = await readAllFilesInsideDirectory(directory);
432
- const modulePaths = filePaths.filter(isJavascriptModule);
433
- const graph = Object.fromEntries(
434
- modulePaths.map((path12) => [
435
- path12,
436
- {
437
- path: path12,
438
- dependencyPaths: [],
439
- dependentPaths: [],
440
- moduleDependencies: []
441
- }
442
- ])
443
- );
444
- const getDependencyPaths = async (filePath) => {
445
- const contents = await fs3.readFile(filePath, "utf8");
446
- const importedPaths = getImportedModules(contents);
447
- const importedPathsRelativeToDirectory = importedPaths.map(
448
- (dependencyPath) => {
449
- const isModulePath = !dependencyPath.startsWith(".");
450
- if (!isModulePath && !path5.isAbsolute(dependencyPath)) {
451
- let pathToDependencyFromDirectory = path5.resolve(
452
- /*
453
- path.resolve resolves paths differently from what imports on javascript do.
454
-
455
- So if we wouldn't do this, for an email at "/path/to/email.tsx" with a dependecy path of "./other-email"
456
- would end up going into /path/to/email.tsx/other-email instead of /path/to/other-email which is the
457
- one the import is meant to go to
458
- */
459
- path5.dirname(filePath),
460
- dependencyPath
461
- );
462
- let isDirectory = false;
463
- try {
464
- isDirectory = statSync(pathToDependencyFromDirectory).isDirectory();
465
- } catch (_) {
466
- }
467
- if (isDirectory) {
468
- const pathToSubDirectory = pathToDependencyFromDirectory;
469
- const pathWithExtension = checkFileExtensionsUntilItExists(
470
- `${pathToSubDirectory}/index`
471
- );
472
- if (pathWithExtension) {
473
- pathToDependencyFromDirectory = pathWithExtension;
474
- } else if (!isRunningBuilt) {
475
- console.warn(
476
- `Could not find index file for directory at ${pathToDependencyFromDirectory}. This is probably going to cause issues with both hot reloading and your code.`
477
- );
478
- }
479
- }
480
- if (!isJavascriptModule(pathToDependencyFromDirectory)) {
481
- const pathWithExtension = checkFileExtensionsUntilItExists(
482
- pathToDependencyFromDirectory
483
- );
484
- if (pathWithExtension) {
485
- pathToDependencyFromDirectory = pathWithExtension;
486
- } else if (!isRunningBuilt) {
487
- console.warn(
488
- `Could not determine the file extension for the file at ${pathWithExtension}`
489
- );
490
- }
491
- }
492
- return pathToDependencyFromDirectory;
493
- } else {
494
- return dependencyPath;
495
- }
496
- }
497
- );
498
- const moduleDependencies = importedPathsRelativeToDirectory.filter(
499
- (dependencyPath) => !dependencyPath.startsWith(".") && !path5.isAbsolute(dependencyPath)
500
- );
501
- const nonNodeModuleImportPathsRelativeToDirectory = importedPathsRelativeToDirectory.filter(
502
- (dependencyPath) => dependencyPath.startsWith(".") || path5.isAbsolute(dependencyPath)
503
- );
504
- return {
505
- dependencyPaths: nonNodeModuleImportPathsRelativeToDirectory,
506
- moduleDependencies
507
- };
508
- };
509
- const updateModuleDependenciesInGraph = async (moduleFilePath) => {
510
- const module = graph[moduleFilePath] ?? {
511
- path: moduleFilePath,
512
- dependencyPaths: [],
513
- dependentPaths: [],
514
- moduleDependencies: []
515
- };
516
- const { moduleDependencies, dependencyPaths: newDependencyPaths } = await getDependencyPaths(moduleFilePath);
517
- module.moduleDependencies = moduleDependencies;
518
- for (const dependencyPath of module.dependencyPaths) {
519
- if (newDependencyPaths.includes(dependencyPath))
520
- continue;
521
- const dependencyModule = graph[dependencyPath];
522
- if (dependencyModule !== void 0) {
523
- dependencyModule.dependentPaths = dependencyModule.dependentPaths.filter(
524
- (dependentPath) => dependentPath !== moduleFilePath
525
- );
526
- }
527
- }
528
- module.dependencyPaths = newDependencyPaths;
529
- for (const dependencyPath of newDependencyPaths) {
530
- const dependencyModule = graph[dependencyPath];
531
- if (dependencyModule !== void 0 && !dependencyModule.dependentPaths.includes(moduleFilePath)) {
532
- dependencyModule.dependentPaths.push(moduleFilePath);
533
- } else {
534
- graph[dependencyPath] = {
535
- path: dependencyPath,
536
- moduleDependencies: [],
537
- dependencyPaths: [],
538
- dependentPaths: [moduleFilePath]
539
- };
540
- }
541
- }
542
- graph[moduleFilePath] = module;
543
- };
544
- for (const filePath of modulePaths) {
545
- await updateModuleDependenciesInGraph(filePath);
546
- }
547
- const removeModuleFromGraph = (filePath) => {
548
- const module = graph[filePath];
549
- if (module) {
550
- for (const dependencyPath of module.dependencyPaths) {
551
- if (graph[dependencyPath]) {
552
- graph[dependencyPath].dependentPaths = graph[dependencyPath].dependentPaths.filter(
553
- (dependentPath) => dependentPath !== filePath
554
- );
555
- }
556
- }
557
- delete graph[filePath];
558
- }
559
- };
560
- return [
561
- graph,
562
- async (event, pathToModified) => {
563
- switch (event) {
564
- case "change":
565
- if (isJavascriptModule(pathToModified)) {
566
- await updateModuleDependenciesInGraph(pathToModified);
567
- }
568
- break;
569
- case "add":
570
- if (isJavascriptModule(pathToModified)) {
571
- await updateModuleDependenciesInGraph(pathToModified);
572
- }
573
- break;
574
- case "addDir":
575
- const filesInsideAddedDirectory = await readAllFilesInsideDirectory(pathToModified);
576
- const modulesInsideAddedDirectory = filesInsideAddedDirectory.filter(isJavascriptModule);
577
- for await (const filePath of modulesInsideAddedDirectory) {
578
- await updateModuleDependenciesInGraph(filePath);
579
- }
580
- break;
581
- case "unlink":
582
- if (isJavascriptModule(pathToModified)) {
583
- removeModuleFromGraph(pathToModified);
584
- }
585
- break;
586
- case "unlinkDir":
587
- const filesInsideDeletedDirectory = await readAllFilesInsideDirectory(pathToModified);
588
- const modulesInsideDeletedDirectory = filesInsideDeletedDirectory.filter(isJavascriptModule);
589
- for await (const filePath of modulesInsideDeletedDirectory) {
590
- removeModuleFromGraph(filePath);
591
- }
592
- break;
593
- }
594
- },
595
- {
596
- resolveDependentsOf: function resolveDependentsOf(pathToModule) {
597
- const moduleEntry = graph[pathToModule];
598
- const dependentPaths = [];
599
- if (moduleEntry) {
600
- for (const dependentPath of moduleEntry.dependentPaths) {
601
- const dependentsOfDependent = resolveDependentsOf(dependentPath);
602
- dependentPaths.push(...dependentsOfDependent);
603
- dependentPaths.push(dependentPath);
604
- }
605
- }
606
- return dependentPaths;
607
- }
608
- }
609
- ];
610
- };
611
-
612
- // src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
613
- var setupHotreloading = async (devServer2, emailDirRelativePath) => {
614
- let clients = [];
615
- const io = new SocketServer(devServer2);
616
- io.on("connection", (client) => {
617
- clients.push(client);
618
- client.on("disconnect", () => {
619
- clients = clients.filter((item) => item !== client);
620
- });
621
- });
622
- let changes = [];
623
- const reload = debounce(() => {
624
- clients.forEach((client) => {
625
- client.emit("reload", changes);
626
- });
627
- changes = [];
628
- }, 150);
629
- const absolutePathToEmailsDirectory = path6.resolve(
630
- process.cwd(),
631
- emailDirRelativePath
632
- );
633
- const [dependencyGraph, updateDependencyGraph, { resolveDependentsOf }] = await createDependencyGraph(absolutePathToEmailsDirectory);
634
- const watcher = watch(emailDirRelativePath, {
635
- ignoreInitial: true,
636
- cwd: process.cwd(),
637
- // eslint-disable-next-line prefer-named-capture-group
638
- ignored: /(^|[/\\])\../
639
- // ignore dotfiles
640
- });
641
- const getFilesOutsideEmailsDirectory = () => Object.keys(dependencyGraph).filter(
642
- (p) => path6.relative(absolutePathToEmailsDirectory, p).startsWith("..")
643
- );
644
- let filesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
645
- for (const p of filesOutsideEmailsDirectory) {
646
- watcher.add(p);
647
- }
648
- const exit = async () => {
649
- await watcher.close();
650
- };
651
- process.on("SIGINT", exit);
652
- process.on("uncaughtException", exit);
653
- watcher.on("all", async (event, relativePathToChangeTarget) => {
654
- const file = relativePathToChangeTarget.split(path6.sep);
655
- if (file.length === 0) {
656
- return;
657
- }
658
- const pathToChangeTarget = path6.resolve(
659
- process.cwd(),
660
- relativePathToChangeTarget
661
- );
662
- await updateDependencyGraph(event, pathToChangeTarget);
663
- const newFilesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
664
- for (const p of filesOutsideEmailsDirectory) {
665
- if (!newFilesOutsideEmailsDirectory.includes(p)) {
666
- watcher.unwatch(p);
667
- }
668
- }
669
- for (const p of newFilesOutsideEmailsDirectory) {
670
- if (!filesOutsideEmailsDirectory.includes(p)) {
671
- watcher.add(p);
672
- }
673
- }
674
- filesOutsideEmailsDirectory = newFilesOutsideEmailsDirectory;
675
- changes.push({
676
- event,
677
- filename: relativePathToChangeTarget
678
- });
679
- for (const dependentPath of resolveDependentsOf(pathToChangeTarget)) {
680
- changes.push({
681
- event: "change",
682
- filename: path6.relative(absolutePathToEmailsDirectory, dependentPath)
683
- });
684
- }
685
- reload();
686
- });
687
- return watcher;
688
- };
689
-
690
- // src/cli/commands/dev.ts
691
- var dev = async ({ dir: emailsDirRelativePath, port }) => {
692
- try {
693
- if (!fs4.existsSync(emailsDirRelativePath)) {
694
- throw new Error(`Missing ${emailsDirRelativePath} folder`);
695
- }
696
- const devServer2 = await startDevServer(
697
- emailsDirRelativePath,
698
- emailsDirRelativePath,
699
- // defaults to ./emails/static for the static files that are served to the preview
700
- parseInt(port)
701
- );
702
- await setupHotreloading(devServer2, emailsDirRelativePath);
703
- } catch (error) {
704
- console.log(error);
705
- process.exit(1);
706
- }
707
- };
708
-
709
- // src/cli/commands/export.ts
710
- import fs7, { unlinkSync, writeFileSync } from "fs";
711
- import path9 from "path";
712
- import { glob } from "glob";
713
- import { build } from "esbuild";
714
- import ora2 from "ora";
715
- import logSymbols2 from "log-symbols";
716
- import normalize from "normalize-path";
717
-
718
- // src/actions/get-emails-directory-metadata.ts
719
- import fs5 from "fs";
720
- import path7 from "path";
721
- var isFileAnEmail = (fullPath) => {
722
- const stat = fs5.statSync(fullPath);
723
- if (stat.isDirectory())
724
- return false;
725
- const { ext } = path7.parse(fullPath);
726
- if (![".js", ".tsx", ".jsx"].includes(ext))
727
- return false;
728
- if (!fs5.existsSync(fullPath)) {
729
- return false;
730
- }
731
- const fileContents = fs5.readFileSync(fullPath, "utf8");
732
- return /\bexport\s+default\b/gm.test(fileContents);
733
- };
734
- var mergeDirectoriesWithSubDirectories = (emailsDirectoryMetadata) => {
735
- let currentResultingMergedDirectory = emailsDirectoryMetadata;
736
- while (currentResultingMergedDirectory.emailFilenames.length === 0 && currentResultingMergedDirectory.subDirectories.length === 1) {
737
- const onlySubDirectory = currentResultingMergedDirectory.subDirectories[0];
738
- currentResultingMergedDirectory = {
739
- subDirectories: onlySubDirectory.subDirectories,
740
- emailFilenames: onlySubDirectory.emailFilenames,
741
- absolutePath: onlySubDirectory.absolutePath,
742
- directoryName: path7.join(
743
- currentResultingMergedDirectory.directoryName,
744
- onlySubDirectory.directoryName
745
- )
746
- };
747
- }
748
- return currentResultingMergedDirectory;
749
- };
750
- var getEmailsDirectoryMetadata = async (absolutePathToEmailsDirectory, keepFileExtensions = false, isSubDirectory = false) => {
751
- if (!fs5.existsSync(absolutePathToEmailsDirectory))
752
- return;
753
- const dirents = await fs5.promises.readdir(absolutePathToEmailsDirectory, {
754
- withFileTypes: true
755
- });
756
- const emailFilenames = dirents.filter(
757
- (dirent) => isFileAnEmail(path7.join(absolutePathToEmailsDirectory, dirent.name))
758
- ).map(
759
- (dirent) => keepFileExtensions ? dirent.name : dirent.name.replace(path7.extname(dirent.name), "")
760
- );
761
- const subDirectories = await Promise.all(
762
- dirents.filter(
763
- (dirent) => dirent.isDirectory() && !dirent.name.startsWith("_") && dirent.name !== "static"
764
- ).map(
765
- (dirent) => getEmailsDirectoryMetadata(
766
- path7.join(absolutePathToEmailsDirectory, dirent.name),
767
- keepFileExtensions,
768
- true
769
- )
770
- )
771
- );
772
- const emailsMetadata = {
773
- absolutePath: absolutePathToEmailsDirectory,
774
- directoryName: absolutePathToEmailsDirectory.split(path7.sep).pop(),
775
- emailFilenames,
776
- subDirectories
777
- };
778
- return isSubDirectory ? mergeDirectoriesWithSubDirectories(emailsMetadata) : emailsMetadata;
779
- };
780
-
781
- // src/utils/esbuild/renderring-utilities-exporter.ts
782
- import path8 from "path";
783
- import { promises as fs6 } from "fs";
784
-
785
- // src/utils/esbuild/escape-string-for-regex.ts
786
- function escapeStringForRegex(string) {
787
- return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
788
- }
789
-
790
- // src/utils/esbuild/renderring-utilities-exporter.ts
791
- var renderingUtilitiesExporter = (emailTemplates) => ({
792
- name: "rendering-utilities-exporter",
793
- setup: (b) => {
794
- b.onLoad(
795
- {
796
- filter: new RegExp(
797
- emailTemplates.map((emailPath) => escapeStringForRegex(emailPath)).join("|")
798
- )
799
- },
800
- async ({ path: pathToFile }) => {
801
- return {
802
- contents: `${await fs6.readFile(pathToFile, "utf8")};
803
- export { renderAsync } from 'react-email-module-that-will-export-render'
804
- export { createElement as reactEmailCreateReactElement } from 'react';
805
- `,
806
- loader: path8.extname(pathToFile).slice(1)
807
- };
808
- }
809
- );
810
- b.onResolve(
811
- { filter: /^react-email-module-that-will-export-render$/ },
812
- async (args) => {
813
- const options = {
814
- kind: "import-statement",
815
- importer: args.importer,
816
- resolveDir: args.resolveDir,
817
- namespace: args.namespace
818
- };
819
- let result = await b.resolve("@react-email/render", options);
820
- if (result.errors.length === 0) {
821
- return result;
822
- }
823
- result = await b.resolve("@react-email/components", options);
824
- if (result.errors.length > 0 && result.errors[0]) {
825
- result.errors[0].text = "Failed trying to import `renderAsync` 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?";
826
- }
827
- return result;
828
- }
829
- );
830
- }
831
- });
832
-
833
- // src/cli/commands/export.ts
834
- var getEmailTemplatesFromDirectory = (emailDirectory) => {
835
- const templatePaths = [];
836
- emailDirectory.emailFilenames.forEach(
837
- (filename) => templatePaths.push(path9.join(emailDirectory.absolutePath, filename))
838
- );
839
- emailDirectory.subDirectories.forEach((directory) => {
840
- templatePaths.push(...getEmailTemplatesFromDirectory(directory));
841
- });
842
- return templatePaths;
843
- };
844
- var exportTemplates = async (pathToWhereEmailMarkupShouldBeDumped, emailsDirectoryPath, options) => {
845
- if (fs7.existsSync(pathToWhereEmailMarkupShouldBeDumped)) {
846
- fs7.rmSync(pathToWhereEmailMarkupShouldBeDumped, { recursive: true });
847
- }
848
- let spinner;
849
- if (!options.silent) {
850
- spinner = ora2("Preparing files...\n").start();
851
- closeOraOnSIGNIT(spinner);
852
- }
853
- const emailsDirectoryMetadata = await getEmailsDirectoryMetadata(
854
- path9.resolve(process.cwd(), emailsDirectoryPath),
855
- true
856
- );
857
- if (typeof emailsDirectoryMetadata === "undefined") {
858
- if (spinner) {
859
- spinner.stopAndPersist({
860
- symbol: logSymbols2.error,
861
- text: `Could not find the directory at ${emailsDirectoryPath}`
862
- });
863
- }
864
- return;
865
- }
866
- const allTemplates = getEmailTemplatesFromDirectory(emailsDirectoryMetadata);
867
- try {
868
- await build({
869
- bundle: true,
870
- entryPoints: allTemplates,
871
- plugins: [renderingUtilitiesExporter(allTemplates)],
872
- platform: "node",
873
- format: "cjs",
874
- loader: { ".js": "jsx" },
875
- outExtension: { ".js": ".cjs" },
876
- jsx: "transform",
877
- write: true,
878
- outdir: pathToWhereEmailMarkupShouldBeDumped
879
- });
880
- } catch (exception) {
881
- const buildFailure = exception;
882
- if (spinner) {
883
- spinner.stopAndPersist({
884
- symbol: logSymbols2.error,
885
- text: "Failed to build emails"
886
- });
887
- }
888
- console.warn(buildFailure.warnings);
889
- console.error(buildFailure.errors);
890
- throw new Error(
891
- `esbuild bundling process for email templates failed:
892
- ${allTemplates.map((p) => `- ${p}`).join("\n")}`
893
- );
894
- }
895
- if (spinner) {
896
- spinner.succeed();
897
- }
898
- const allBuiltTemplates = glob.sync(
899
- normalize(`${pathToWhereEmailMarkupShouldBeDumped}/**/*.cjs`),
900
- {
901
- absolute: true
902
- }
903
- );
904
- for (const template of allBuiltTemplates) {
905
- try {
906
- if (spinner) {
907
- spinner.text = `rendering ${template.split("/").pop()}`;
908
- spinner.render();
909
- }
910
- delete __require.cache[template];
911
- const emailModule = __require(template);
912
- const rendered = await emailModule.renderAsync(
913
- emailModule.reactEmailCreateReactElement(emailModule.default, {}),
914
- options
915
- );
916
- const htmlPath = template.replace(
917
- ".cjs",
918
- options.plainText ? ".txt" : ".html"
919
- );
920
- writeFileSync(htmlPath, rendered);
921
- unlinkSync(template);
922
- } catch (exception) {
923
- if (spinner) {
924
- spinner.stopAndPersist({
925
- symbol: logSymbols2.error,
926
- text: `failed when rendering ${template.split("/").pop()}`
927
- });
928
- }
929
- console.error(exception);
930
- throw exception;
931
- }
932
- }
933
- if (spinner) {
934
- spinner.succeed("Rendered all files");
935
- spinner.text = `Copying static files`;
936
- spinner.render();
937
- }
938
- const staticDirectoryPath = path9.join(emailsDirectoryPath, "static");
939
- if (fs7.existsSync(staticDirectoryPath)) {
940
- const pathToDumpStaticFilesInto = path9.join(
941
- pathToWhereEmailMarkupShouldBeDumped,
942
- "static"
943
- );
944
- if (fs7.existsSync(pathToDumpStaticFilesInto))
945
- await fs7.promises.rm(pathToDumpStaticFilesInto, { recursive: true });
946
- try {
947
- await fs7.promises.cp(staticDirectoryPath, pathToDumpStaticFilesInto, {
948
- recursive: true
949
- });
950
- } catch (exception) {
951
- console.error(exception);
952
- if (spinner) {
953
- spinner.stopAndPersist({
954
- symbol: logSymbols2.error,
955
- text: "Failed to copy static files"
956
- });
957
- }
958
- throw new Error(
959
- `Something went wrong while copying the file to ${pathToWhereEmailMarkupShouldBeDumped}/static, ${exception}`
960
- );
961
- }
962
- }
963
- if (spinner && !options.silent) {
964
- spinner.succeed();
965
- const fileTree = await tree(pathToWhereEmailMarkupShouldBeDumped, 4);
966
- console.log(fileTree);
967
- spinner.stopAndPersist({
968
- symbol: logSymbols2.success,
969
- text: "Successfully exported emails"
970
- });
971
- }
972
- };
973
-
974
- // src/cli/commands/build.ts
975
- import fs8 from "fs";
976
- import path10 from "path";
977
- import ora3 from "ora";
978
- import { spawn } from "child_process";
979
- import logSymbols3 from "log-symbols";
980
- var buildPreviewApp = (absoluteDirectory) => {
981
- return new Promise((resolve2, reject) => {
982
- const nextBuild = spawn("npm", ["run", "build"], {
983
- cwd: absoluteDirectory,
984
- shell: true
985
- });
986
- nextBuild.stdout.pipe(process.stdout);
987
- nextBuild.stderr.pipe(process.stderr);
988
- nextBuild.on("close", (code) => {
989
- if (code === 0) {
990
- resolve2();
991
- } else {
992
- reject(
993
- new Error(
994
- `Unable to build the Next app and it exited with code: ${code}`
995
- )
996
- );
997
- }
998
- });
999
- });
1000
- };
1001
- var setNextEnvironmentVariablesForBuild = async (emailsDirRelativePath, builtPreviewAppPath) => {
1002
- const envVariables = {
1003
- ...getEnvVariablesForPreviewApp(
1004
- // If we don't do normalization here, stuff like https://github.com/resend/react-email/issues/1354 happens.
1005
- path10.normalize(emailsDirRelativePath),
1006
- "PLACEHOLDER",
1007
- "PLACEHOLDER"
1008
- ),
1009
- NEXT_PUBLIC_IS_BUILDING: "true"
1010
- };
1011
- const nextConfigContents = `
1012
- const path = require('path');
1013
- /** @type {import('next').NextConfig} */
1014
- module.exports = {
1015
- env: {
1016
- ...${JSON.stringify(envVariables)},
1017
- NEXT_PUBLIC_USER_PROJECT_LOCATION: path.resolve(process.cwd(), '../'),
1018
- NEXT_PUBLIC_CLI_PACKAGE_LOCATION: process.cwd(),
1019
- },
1020
- // this is needed so that the code for building emails works properly
1021
- webpack: (
1022
- /** @type {import('webpack').Configuration & { externals: string[] }} */
1023
- config,
1024
- { isServer }
1025
- ) => {
1026
- if (isServer) {
1027
- config.externals.push('esbuild');
1028
- }
1029
-
1030
- return config;
1031
- },
1032
- typescript: {
1033
- ignoreBuildErrors: true
1034
- },
1035
- eslint: {
1036
- ignoreDuringBuilds: true
1037
- },
1038
- experimental: {
1039
- webpackBuildWorker: true
1040
- },
1041
- }`;
1042
- await fs8.promises.writeFile(
1043
- path10.resolve(builtPreviewAppPath, "./next.config.js"),
1044
- nextConfigContents,
1045
- "utf8"
1046
- );
1047
- };
1048
- var getEmailSlugsFromEmailDirectory = (emailDirectory, emailsDirectoryAbsolutePath) => {
1049
- const directoryPathRelativeToEmailsDirectory = emailDirectory.absolutePath.replace(emailsDirectoryAbsolutePath, "").trim();
1050
- const slugs = [];
1051
- emailDirectory.emailFilenames.forEach(
1052
- (filename) => slugs.push(
1053
- path10.join(directoryPathRelativeToEmailsDirectory, filename).split(path10.sep).filter((segment) => segment.length > 0)
1054
- )
1055
- );
1056
- emailDirectory.subDirectories.forEach((directory) => {
1057
- slugs.push(
1058
- ...getEmailSlugsFromEmailDirectory(
1059
- directory,
1060
- emailsDirectoryAbsolutePath
1061
- )
1062
- );
1063
- });
1064
- return slugs;
1065
- };
1066
- var forceSSGForEmailPreviews = async (emailsDirPath, builtPreviewAppPath) => {
1067
- const emailDirectoryMetadata = (
1068
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1069
- await getEmailsDirectoryMetadata(emailsDirPath)
1070
- );
1071
- const parameters = getEmailSlugsFromEmailDirectory(
1072
- emailDirectoryMetadata,
1073
- emailsDirPath
1074
- ).map((slug) => ({ slug }));
1075
- await fs8.promises.appendFile(
1076
- path10.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx"),
1077
- `
1078
-
1079
- export function generateStaticParams() {
1080
- return Promise.resolve(
1081
- ${JSON.stringify(parameters)}
1082
- );
1083
- }`,
1084
- "utf8"
1085
- );
1086
- };
1087
- var updatePackageJson = async (builtPreviewAppPath) => {
1088
- const packageJsonPath = path10.resolve(builtPreviewAppPath, "./package.json");
1089
- const packageJson = JSON.parse(
1090
- await fs8.promises.readFile(packageJsonPath, "utf8")
1091
- );
1092
- packageJson.scripts.build = "next build";
1093
- packageJson.scripts.start = "next start";
1094
- packageJson.name = "preview-server";
1095
- delete packageJson.devDependencies["@react-email/render"];
1096
- delete packageJson.devDependencies["@react-email/components"];
1097
- packageJson.dependencies.sharp = "0.33.2";
1098
- await fs8.promises.writeFile(
1099
- packageJsonPath,
1100
- JSON.stringify(packageJson),
1101
- "utf8"
1102
- );
1103
- };
1104
- var npmInstall = async (builtPreviewAppPath, packageManager) => {
1105
- return new Promise(async (resolve2, reject) => {
1106
- const childProc = spawn(
1107
- packageManager,
1108
- ["install", "--silent", "--force"],
1109
- {
1110
- cwd: builtPreviewAppPath,
1111
- shell: true
1112
- }
1113
- );
1114
- childProc.stdout.pipe(process.stdout);
1115
- childProc.stderr.pipe(process.stderr);
1116
- childProc.on("close", (code) => {
1117
- if (code === 0) {
1118
- resolve2();
1119
- } else {
1120
- reject(
1121
- new Error(
1122
- `Unable to install the dependencies and it exited with code: ${code}`
1123
- )
1124
- );
1125
- }
1126
- });
1127
- });
1128
- };
1129
- var build2 = async ({
1130
- dir: emailsDirRelativePath,
1131
- packageManager
1132
- }) => {
1133
- try {
1134
- const spinner = ora3({
1135
- text: "Starting build process...",
1136
- prefixText: " "
1137
- }).start();
1138
- closeOraOnSIGNIT(spinner);
1139
- spinner.text = "Checking if emails folder exists";
1140
- if (!fs8.existsSync(emailsDirRelativePath)) {
1141
- throw new Error(`Missing ${emailsDirRelativePath} folder`);
1142
- }
1143
- const emailsDirPath = path10.join(process.cwd(), emailsDirRelativePath);
1144
- const staticPath = path10.join(emailsDirPath, "static");
1145
- const builtPreviewAppPath = path10.join(process.cwd(), ".react-email");
1146
- if (fs8.existsSync(builtPreviewAppPath)) {
1147
- spinner.text = "Deleting pre-existing `.react-email` folder";
1148
- await fs8.promises.rm(builtPreviewAppPath, { recursive: true });
1149
- }
1150
- spinner.text = "Copying preview app from CLI to `.react-email`";
1151
- await fs8.promises.cp(cliPacakgeLocation, builtPreviewAppPath, {
1152
- recursive: true,
1153
- filter: (source) => {
1154
- return !/(\/|\\)cli(\/|\\)?/.test(source) && !/(\/|\\)\.next(\/|\\)?/.test(source) && !/(\/|\\)\.turbo(\/|\\)?/.test(source) && !/(\/|\\)node_modules(\/|\\)?$/.test(source);
1155
- }
1156
- });
1157
- if (fs8.existsSync(staticPath)) {
1158
- spinner.text = "Copying `static` folder into `.react-email/public/static`";
1159
- const builtStaticDirectory = path10.resolve(
1160
- builtPreviewAppPath,
1161
- "./public/static"
1162
- );
1163
- await fs8.promises.cp(staticPath, builtStaticDirectory, {
1164
- recursive: true
1165
- });
1166
- }
1167
- spinner.text = "Setting Next environment variables for preview app to work properly";
1168
- await setNextEnvironmentVariablesForBuild(
1169
- emailsDirRelativePath,
1170
- builtPreviewAppPath
1171
- );
1172
- spinner.text = "Setting server side generation for the email preview pages";
1173
- await forceSSGForEmailPreviews(emailsDirPath, builtPreviewAppPath);
1174
- spinner.text = "Updating package.json's build and start scripts";
1175
- await updatePackageJson(builtPreviewAppPath);
1176
- spinner.text = "Installing dependencies on `.react-email`";
1177
- await npmInstall(builtPreviewAppPath, packageManager);
1178
- spinner.stopAndPersist({
1179
- text: "Successfully prepared `.react-email` for `next build`",
1180
- symbol: logSymbols3.success
1181
- });
1182
- await buildPreviewApp(builtPreviewAppPath);
1183
- } catch (error) {
1184
- console.log(error);
1185
- process.exit(1);
1186
- }
1187
- };
1188
-
1189
- // src/cli/commands/start.ts
1190
- import fs9 from "fs";
1191
- import path11 from "path";
1192
- import { spawn as spawn2 } from "child_process";
1193
- var start = async () => {
1194
- try {
1195
- const usersProjectLocation = process.cwd();
1196
- const builtPreviewPath = path11.resolve(
1197
- usersProjectLocation,
1198
- "./.react-email"
1199
- );
1200
- if (!fs9.existsSync(builtPreviewPath)) {
1201
- throw new Error(
1202
- "Could not find `.react-email`, maybe you haven't ran `email build`?"
1203
- );
1204
- }
1205
- const nextStart = spawn2("npm", ["start"], {
1206
- cwd: builtPreviewPath,
1207
- shell: true
1208
- });
1209
- nextStart.stdout.pipe(process.stdout);
1210
- nextStart.stderr.pipe(process.stderr);
1211
- } catch (error) {
1212
- console.log(error);
1213
- process.exit(1);
1214
- }
1215
- };
1216
-
1217
- // src/cli/index.ts
1218
- var PACKAGE_NAME = "react-email";
1219
- program.name(PACKAGE_NAME).description("A live preview of your emails right in your browser").version(package_default.version);
1220
- 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);
1221
- 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(
1222
- "-p --packageManager <name>",
1223
- "Package name to use on installation on `.react-email`",
1224
- "npm"
1225
- ).action(build2);
1226
- program.command("start").description('Runs the built preview app that is inside of ".react-email"').action(start);
1227
- 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(
1228
- "-s, --silent",
1229
- "To, or not to show a spinner with process information",
1230
- false
1231
- ).action(
1232
- ({ outDir, pretty, plainText, silent, dir: srcDir }) => exportTemplates(outDir, srcDir, { pretty, silent, plainText })
1233
- );
1234
- program.parse();