react-email 4.0.0-alpha.4 → 4.0.0-alpha.6

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 (189) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cli/index.js +1175 -2658
  3. package/dist/cli/index.mjs +18 -12
  4. package/dist/preview/.next/BUILD_ID +1 -1
  5. package/dist/preview/.next/app-build-manifest.json +31 -34
  6. package/dist/preview/.next/app-path-routes-manifest.json +6 -1
  7. package/dist/preview/.next/build-manifest.json +14 -14
  8. package/dist/preview/.next/cache/.rscinfo +1 -1
  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/diagnostics/framework.json +1 -1
  15. package/dist/preview/.next/export-marker.json +6 -1
  16. package/dist/preview/.next/images-manifest.json +57 -1
  17. package/dist/preview/.next/next-minimal-server.js.nft.json +1 -1
  18. package/dist/preview/.next/next-server.js.nft.json +1 -1
  19. package/dist/preview/.next/prerender-manifest.json +41 -1
  20. package/dist/preview/.next/required-server-files.json +310 -1
  21. package/dist/preview/.next/routes-manifest.json +64 -1
  22. package/dist/preview/.next/server/app/_not-found/page.js +1 -1
  23. package/dist/preview/.next/server/app/_not-found/page.js.nft.json +1 -1
  24. package/dist/preview/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  25. package/dist/preview/.next/server/app/favicon.ico/route.js +1 -1
  26. package/dist/preview/.next/server/app/favicon.ico/route.js.nft.json +1 -1
  27. package/dist/preview/.next/server/app/page.js +1 -1
  28. package/dist/preview/.next/server/app/page.js.nft.json +1 -1
  29. package/dist/preview/.next/server/app/page_client-reference-manifest.js +1 -1
  30. package/dist/preview/.next/server/app/preview/[...slug]/page.js +47 -10
  31. package/dist/preview/.next/server/app/preview/[...slug]/page.js.nft.json +1 -1
  32. package/dist/preview/.next/server/app/preview/[...slug]/page_client-reference-manifest.js +1 -1
  33. package/dist/preview/.next/server/app-paths-manifest.json +1 -1
  34. package/dist/preview/.next/server/chunks/171.js +14 -0
  35. package/dist/preview/.next/server/chunks/446.js +6 -0
  36. package/dist/preview/.next/server/chunks/600.js +8 -0
  37. package/dist/preview/.next/server/chunks/811.js +13 -0
  38. package/dist/preview/.next/server/chunks/833.js +1 -0
  39. package/dist/preview/.next/server/functions-config-manifest.json +4 -1
  40. package/dist/preview/.next/server/middleware-build-manifest.js +1 -1
  41. package/dist/preview/.next/server/next-font-manifest.js +1 -1
  42. package/dist/preview/.next/server/next-font-manifest.json +1 -1
  43. package/dist/preview/.next/server/pages/500.html +1 -1
  44. package/dist/preview/.next/server/pages/_app.js +1 -1
  45. package/dist/preview/.next/server/pages/_app.js.nft.json +1 -1
  46. package/dist/preview/.next/server/pages/_document.js +1 -1
  47. package/dist/preview/.next/server/pages/_document.js.nft.json +1 -1
  48. package/dist/preview/.next/server/pages/_error.js +1 -1
  49. package/dist/preview/.next/server/pages/_error.js.nft.json +1 -1
  50. package/dist/preview/.next/server/pages-manifest.json +5 -1
  51. package/dist/preview/.next/server/server-reference-manifest.js +1 -1
  52. package/dist/preview/.next/server/server-reference-manifest.json +1 -1
  53. package/dist/preview/.next/server/webpack-runtime.js +1 -1
  54. package/dist/preview/.next/static/chunks/416-56f79fc7e689f06f.js +1 -0
  55. package/dist/preview/.next/static/chunks/683-8bbfd191e5105f01.js +1 -0
  56. package/dist/preview/.next/static/chunks/744-79730358b37b2212.js +1 -0
  57. package/dist/preview/.next/static/chunks/781-5f16c6bc9d9d4cc1.js +1 -0
  58. package/dist/preview/.next/static/chunks/832ad4be-cb988facfb8f955f.js +1 -0
  59. package/dist/preview/.next/static/chunks/87-38e35f08507de015.js +1 -0
  60. package/dist/preview/.next/static/chunks/{afa401a5-9ebf2515b1397993.js → afa401a5-3e949a1cfd317dd3.js} +3 -3
  61. package/dist/preview/.next/static/chunks/app/_not-found/page-09d694081cc9d4dc.js +1 -0
  62. package/dist/preview/.next/static/chunks/app/layout-a6640e62690d8fd6.js +1 -0
  63. package/dist/preview/.next/static/chunks/app/page-ba68f50b287e7478.js +1 -0
  64. package/dist/preview/.next/static/chunks/app/preview/[...slug]/page-4a5b026ab543e27f.js +1 -0
  65. package/dist/preview/.next/static/chunks/framework-c2bd6d936e3077bc.js +1 -0
  66. package/dist/preview/.next/static/chunks/main-44463a8301435b64.js +1 -0
  67. package/dist/preview/.next/static/chunks/main-app-c2e686acf8d370d7.js +1 -0
  68. package/dist/preview/.next/static/chunks/pages/_app-f3011d3f00bb8dba.js +1 -0
  69. package/dist/preview/.next/static/chunks/pages/_error-39a87dee2e97a2a3.js +1 -0
  70. package/dist/preview/.next/static/chunks/{webpack-9255716c9496e606.js → webpack-41e2667c9f086a4f.js} +1 -1
  71. package/dist/preview/.next/static/css/d7df9cfc3e182163.css +3 -0
  72. package/dist/preview/.next/static/gFk9UfWL8joM4iD7-wlKF/_buildManifest.js +1 -0
  73. package/dist/preview/.next/static/media/05613964ce6c782e-s.p.otf +0 -0
  74. package/dist/preview/.next/static/media/11c6126b9369e85e-s.p.otf +0 -0
  75. package/dist/preview/.next/static/media/26cb97734d8cb717-s.p.otf +0 -0
  76. package/dist/preview/.next/static/media/bb6462617151f6b7-s.p.otf +0 -0
  77. package/dist/preview/.next/static/media/cf6daef822ab0142-s.p.otf +0 -0
  78. package/dist/preview/.next/static/media/e4051546b3043204-s.p.otf +0 -0
  79. package/dist/preview/.next/trace +26 -22
  80. package/dist/preview/.next/types/cache-life.d.ts +3 -3
  81. package/package.json +17 -11
  82. package/scripts/build-preview-server.mjs +32 -0
  83. package/scripts/fill-caniemail-data.mjs +36 -0
  84. package/src/actions/email-validation/caniemail-data.ts +85993 -0
  85. package/src/actions/email-validation/check-compatibility.ts +322 -0
  86. package/src/actions/email-validation/check-images.spec.tsx +21 -12
  87. package/src/actions/email-validation/check-images.ts +88 -86
  88. package/src/actions/email-validation/check-links.spec.tsx +24 -14
  89. package/src/actions/email-validation/check-links.ts +59 -56
  90. package/src/actions/get-email-path-from-slug.ts +1 -1
  91. package/src/actions/render-email-by-path.tsx +2 -1
  92. package/src/{utils/emails-directory-absolute-path.ts → app/env.ts} +2 -0
  93. package/src/app/fonts/SFMono/SFMonoBold.otf +0 -0
  94. package/src/app/fonts/SFMono/SFMonoBoldItalic.otf +0 -0
  95. package/src/app/fonts/SFMono/SFMonoHeavy.otf +0 -0
  96. package/src/app/fonts/SFMono/SFMonoHeavyItalic.otf +0 -0
  97. package/src/app/fonts/SFMono/SFMonoLight.otf +0 -0
  98. package/src/app/fonts/SFMono/SFMonoLightItalic.otf +0 -0
  99. package/src/app/fonts/SFMono/SFMonoMedium.otf +0 -0
  100. package/src/app/fonts/SFMono/SFMonoMediumItalic.otf +0 -0
  101. package/src/app/fonts/SFMono/SFMonoRegular.otf +0 -0
  102. package/src/app/fonts/SFMono/SFMonoRegularItalic.otf +0 -0
  103. package/src/app/fonts/SFMono/SFMonoSemibold.otf +0 -0
  104. package/src/app/fonts/SFMono/SFMonoSemiboldItalic.otf +0 -0
  105. package/src/app/fonts.ts +39 -0
  106. package/src/app/layout.tsx +6 -3
  107. package/src/app/page.tsx +4 -4
  108. package/src/app/preview/[...slug]/page.tsx +73 -16
  109. package/src/app/preview/[...slug]/preview.tsx +49 -77
  110. package/src/components/code.tsx +0 -1
  111. package/src/components/icons/icon-base.tsx +4 -2
  112. package/src/components/icons/icon-reload.tsx +19 -0
  113. package/src/components/icons/icon-scanner.tsx +19 -0
  114. package/src/components/icons/icon-scissors.tsx +19 -0
  115. package/src/components/icons/icon-warning.tsx +31 -0
  116. package/src/components/send.tsx +1 -2
  117. package/src/components/shell.tsx +52 -88
  118. package/src/components/sidebar/file-tree-directory-children.tsx +1 -1
  119. package/src/components/sidebar/file-tree.tsx +1 -1
  120. package/src/components/sidebar/sidebar.tsx +23 -378
  121. package/src/components/toolbar/linter.tsx +310 -0
  122. package/src/components/toolbar/results-table.tsx +0 -0
  123. package/src/components/toolbar/results.tsx +48 -0
  124. package/src/components/toolbar/spam-assassin.tsx +144 -0
  125. package/src/components/toolbar/toolbar-button.tsx +50 -0
  126. package/src/components/toolbar/use-cached-state.ts +33 -0
  127. package/src/components/toolbar.tsx +197 -0
  128. package/src/components/tooltip-content.tsx +1 -2
  129. package/src/components/topbar/view-size-controls.tsx +1 -0
  130. package/src/components/topbar.tsx +29 -48
  131. package/src/contexts/emails.tsx +2 -1
  132. package/src/contexts/preview.tsx +81 -0
  133. package/src/hooks/use-email-rendering-result.ts +2 -1
  134. package/src/utils/__snapshots__/get-email-component.spec.ts.snap +1 -1
  135. package/src/utils/caniemail/all-css-properties.ts +358 -0
  136. package/src/utils/caniemail/ast/get-object-variables.ts +61 -0
  137. package/src/utils/caniemail/ast/get-used-style-properties.ts +91 -0
  138. package/src/utils/caniemail/get-compatibility-stats-for-entry.ts +118 -0
  139. package/src/utils/caniemail/get-css-functions.ts +25 -0
  140. package/src/utils/caniemail/get-css-property-names.ts +32 -0
  141. package/src/utils/caniemail/get-css-property-with-value.ts +14 -0
  142. package/src/utils/caniemail/get-css-unit.ts +3 -0
  143. package/src/utils/caniemail/get-element-attributes.ts +7 -0
  144. package/src/utils/caniemail/get-element-names.ts +20 -0
  145. package/src/utils/caniemail/tailwind/generate-tailwind-rules.ts +30 -0
  146. package/src/utils/caniemail/tailwind/get-tailwind-config.ts +205 -0
  147. package/src/utils/caniemail/tailwind/get-tailwind-metadata.spec.ts +25 -0
  148. package/src/utils/caniemail/tailwind/get-tailwind-metadata.ts +45 -0
  149. package/src/utils/caniemail/tailwind/setup-tailwind-context.ts +15 -0
  150. package/src/utils/get-email-component.ts +34 -67
  151. package/src/utils/linting.ts +85 -0
  152. package/src/utils/result.ts +49 -0
  153. package/src/utils/run-bundled-code.ts +64 -0
  154. package/tailwind-internals.d.ts +133 -0
  155. package/tailwind.config.ts +1 -0
  156. package/tsconfig.json +9 -3
  157. package/build-preview-server.mjs +0 -25
  158. package/dist/preview/.next/server/chunks/196.js +0 -5
  159. package/dist/preview/.next/server/chunks/300.js +0 -13
  160. package/dist/preview/.next/server/chunks/631.js +0 -6
  161. package/dist/preview/.next/server/chunks/644.js +0 -1
  162. package/dist/preview/.next/server/chunks/734.js +0 -15
  163. package/dist/preview/.next/static/Pt6wqIrWnQxbiyqaKNFOx/_buildManifest.js +0 -1
  164. package/dist/preview/.next/static/chunks/285-dbf6306a0d45c33d.js +0 -1
  165. package/dist/preview/.next/static/chunks/447-886131c35ca42b91.js +0 -1
  166. package/dist/preview/.next/static/chunks/490-d5745684930d49e0.js +0 -1
  167. package/dist/preview/.next/static/chunks/5fec7a0a-5179023f3f5a9421.js +0 -1
  168. package/dist/preview/.next/static/chunks/603-36207c8905355e23.js +0 -1
  169. package/dist/preview/.next/static/chunks/797-46f6c20952f0a280.js +0 -2
  170. package/dist/preview/.next/static/chunks/app/_not-found/page-96d3eac723be3ee2.js +0 -1
  171. package/dist/preview/.next/static/chunks/app/layout-d06046b8a368df3b.js +0 -1
  172. package/dist/preview/.next/static/chunks/app/page-ef1c23b954fbd0b5.js +0 -1
  173. package/dist/preview/.next/static/chunks/app/preview/[...slug]/page-ea8e1ae2b5a4a0ec.js +0 -1
  174. package/dist/preview/.next/static/chunks/framework-e7cae9cecd5c9ba2.js +0 -1
  175. package/dist/preview/.next/static/chunks/main-app-9f2fb5ea26e2765b.js +0 -1
  176. package/dist/preview/.next/static/chunks/main-df761fde212f9cda.js +0 -1
  177. package/dist/preview/.next/static/chunks/pages/_app-203a61b355820ccf.js +0 -1
  178. package/dist/preview/.next/static/chunks/pages/_error-1764ca54938748c8.js +0 -1
  179. package/dist/preview/.next/static/css/e4822d5ba3082a95.css +0 -3
  180. package/dist/preview/.next/static/css/ec5d7e66bd3b6cb8.css +0 -1
  181. package/src/app/inter.ts +0 -7
  182. package/src/components/icons/icon-circle-check.tsx +0 -21
  183. package/src/components/icons/icon-circle-close.tsx +0 -17
  184. package/src/components/icons/icon-circle-warning.tsx +0 -17
  185. package/src/components/sidebar/image-checker.tsx +0 -162
  186. package/src/components/sidebar/link-checker.tsx +0 -151
  187. package/src/components/sidebar/spam-assassin.tsx +0 -158
  188. /package/dist/preview/.next/static/{Pt6wqIrWnQxbiyqaKNFOx → gFk9UfWL8joM4iD7-wlKF}/_ssgManifest.js +0 -0
  189. /package/src/components/{sidebar → toolbar}/checking-results.tsx +0 -0
package/dist/cli/index.js CHANGED
@@ -1,697 +1,295 @@
1
1
  #!/usr/bin/env node
2
- function _array_like_to_array(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _array_with_holes(arr) {
8
- if (Array.isArray(arr)) return arr;
9
- }
10
- function _array_without_holes(arr) {
11
- if (Array.isArray(arr)) return _array_like_to_array(arr);
12
- }
13
- function _async_iterator(iterable) {
14
- var method, async, sync, retry = 2;
15
- for("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;){
16
- if (async && null != (method = iterable[async])) return method.call(iterable);
17
- if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable));
18
- async = "@@asyncIterator", sync = "@@iterator";
19
- }
20
- throw new TypeError("Object is not async iterable");
21
- }
22
- function AsyncFromSyncIterator(s) {
23
- function AsyncFromSyncIteratorContinuation(r) {
24
- if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
25
- var done = r.done;
26
- return Promise.resolve(r.value).then(function(value) {
27
- return {
28
- value: value,
29
- done: done
30
- };
31
- });
32
- }
33
- return AsyncFromSyncIterator = function(s) {
34
- this.s = s, this.n = s.next;
35
- }, AsyncFromSyncIterator.prototype = {
36
- s: null,
37
- n: null,
38
- next: function() {
39
- return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
40
- },
41
- return: function(value) {
42
- var ret = this.s.return;
43
- return void 0 === ret ? Promise.resolve({
44
- value: value,
45
- done: !0
46
- }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));
47
- },
48
- throw: function(value) {
49
- var thr = this.s.return;
50
- return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
51
- }
52
- }, new AsyncFromSyncIterator(s);
53
- }
54
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
55
- try {
56
- var info = gen[key](arg);
57
- var value = info.value;
58
- } catch (error) {
59
- reject(error);
60
- return;
61
- }
62
- if (info.done) {
63
- resolve(value);
64
- } else {
65
- Promise.resolve(value).then(_next, _throw);
66
- }
67
- }
68
- function _async_to_generator(fn) {
69
- return function() {
70
- var self = this, args = arguments;
71
- return new Promise(function(resolve, reject) {
72
- var gen = fn.apply(self, args);
73
- function _next(value) {
74
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
75
- }
76
- function _throw(err) {
77
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
78
- }
79
- _next(undefined);
80
- });
81
- };
82
- }
83
- function _define_property(obj, key, value) {
84
- if (key in obj) {
85
- Object.defineProperty(obj, key, {
86
- value: value,
87
- enumerable: true,
88
- configurable: true,
89
- writable: true
90
- });
91
- } else {
92
- obj[key] = value;
93
- }
94
- return obj;
95
- }
96
- function _iterable_to_array(iter) {
97
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
98
- }
99
- function _iterable_to_array_limit(arr, i) {
100
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
101
- if (_i == null) return;
102
- var _arr = [];
103
- var _n = true;
104
- var _d = false;
105
- var _s, _e;
106
- try {
107
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
108
- _arr.push(_s.value);
109
- if (i && _arr.length === i) break;
110
- }
111
- } catch (err) {
112
- _d = true;
113
- _e = err;
114
- } finally{
115
- try {
116
- if (!_n && _i["return"] != null) _i["return"]();
117
- } finally{
118
- if (_d) throw _e;
119
- }
120
- }
121
- return _arr;
122
- }
123
- function _non_iterable_rest() {
124
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
125
- }
126
- function _non_iterable_spread() {
127
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
128
- }
129
- function _object_spread(target) {
130
- for(var i = 1; i < arguments.length; i++){
131
- var source = arguments[i] != null ? arguments[i] : {};
132
- var ownKeys = Object.keys(source);
133
- if (typeof Object.getOwnPropertySymbols === "function") {
134
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
135
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
136
- }));
137
- }
138
- ownKeys.forEach(function(key) {
139
- _define_property(target, key, source[key]);
140
- });
141
- }
142
- return target;
143
- }
144
- function ownKeys(object, enumerableOnly) {
145
- var keys = Object.keys(object);
146
- if (Object.getOwnPropertySymbols) {
147
- var symbols = Object.getOwnPropertySymbols(object);
148
- if (enumerableOnly) {
149
- symbols = symbols.filter(function(sym) {
150
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
151
- });
152
- }
153
- keys.push.apply(keys, symbols);
154
- }
155
- return keys;
156
- }
157
- function _object_spread_props(target, source) {
158
- source = source != null ? source : {};
159
- if (Object.getOwnPropertyDescriptors) {
160
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
161
- } else {
162
- ownKeys(Object(source)).forEach(function(key) {
163
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
164
- });
165
- }
166
- return target;
167
- }
168
- function _sliced_to_array(arr, i) {
169
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
170
- }
171
- function _to_consumable_array(arr) {
172
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
173
- }
174
- function _unsupported_iterable_to_array(o, minLen) {
175
- if (!o) return;
176
- if (typeof o === "string") return _array_like_to_array(o, minLen);
177
- var n = Object.prototype.toString.call(o).slice(8, -1);
178
- if (n === "Object" && o.constructor) n = o.constructor.name;
179
- if (n === "Map" || n === "Set") return Array.from(n);
180
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
181
- }
182
- function _ts_generator(thisArg, body) {
183
- var f, y, t, g, _ = {
184
- label: 0,
185
- sent: function() {
186
- if (t[0] & 1) throw t[1];
187
- return t[1];
188
- },
189
- trys: [],
190
- ops: []
191
- };
192
- return g = {
193
- next: verb(0),
194
- "throw": verb(1),
195
- "return": verb(2)
196
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
197
- return this;
198
- }), g;
199
- function verb(n) {
200
- return function(v) {
201
- return step([
202
- n,
203
- v
204
- ]);
205
- };
206
- }
207
- function step(op) {
208
- if (f) throw new TypeError("Generator is already executing.");
209
- while(_)try {
210
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
211
- if (y = 0, t) op = [
212
- op[0] & 2,
213
- t.value
214
- ];
215
- switch(op[0]){
216
- case 0:
217
- case 1:
218
- t = op;
219
- break;
220
- case 4:
221
- _.label++;
222
- return {
223
- value: op[1],
224
- done: false
225
- };
226
- case 5:
227
- _.label++;
228
- y = op[1];
229
- op = [
230
- 0
231
- ];
232
- continue;
233
- case 7:
234
- op = _.ops.pop();
235
- _.trys.pop();
236
- continue;
237
- default:
238
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
239
- _ = 0;
240
- continue;
241
- }
242
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
243
- _.label = op[1];
244
- break;
245
- }
246
- if (op[0] === 6 && _.label < t[1]) {
247
- _.label = t[1];
248
- t = op;
249
- break;
250
- }
251
- if (t && _.label < t[2]) {
252
- _.label = t[2];
253
- _.ops.push(op);
254
- break;
255
- }
256
- if (t[2]) _.ops.pop();
257
- _.trys.pop();
258
- continue;
259
- }
260
- op = body.call(thisArg, _);
261
- } catch (e) {
262
- op = [
263
- 6,
264
- e
265
- ];
266
- y = 0;
267
- } finally{
268
- f = t = 0;
269
- }
270
- if (op[0] & 5) throw op[1];
271
- return {
272
- value: op[0] ? op[1] : void 0,
273
- done: true
274
- };
275
- }
276
- }
277
- function _ts_values(o) {
278
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
279
- if (m) return m.call(o);
280
- if (o && typeof o.length === "number") return {
281
- next: function() {
282
- if (o && i >= o.length) o = void 0;
283
- return {
284
- value: o && o[i++],
285
- done: !o
286
- };
287
- }
288
- };
289
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
290
- }
291
2
  var __create = Object.create;
292
3
  var __defProp = Object.defineProperty;
293
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
294
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
295
6
  var __getProtoOf = Object.getPrototypeOf;
296
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
297
- var __copyProps = function(to, from, except, desc) {
298
- if (from && typeof from === "object" || typeof from === "function") {
299
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
300
- try {
301
- var _loop = function() {
302
- var key = _step.value;
303
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
304
- get: function() {
305
- return from[key];
306
- },
307
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
308
- });
309
- };
310
- for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
311
- } catch (err) {
312
- _didIteratorError = true;
313
- _iteratorError = err;
314
- } finally{
315
- try {
316
- if (!_iteratorNormalCompletion && _iterator.return != null) {
317
- _iterator.return();
318
- }
319
- } finally{
320
- if (_didIteratorError) {
321
- throw _iteratorError;
322
- }
323
- }
324
- }
325
- }
326
- return to;
327
- };
328
- var __toESM = function(mod, isNodeMode, target) {
329
- return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
330
- // file that has been converted to a CommonJS file using a Babel-
331
- // compatible transform (i.e. "__esModule" has not been set), then set
332
- // "default" to the CommonJS "module.exports" for node compatibility.
333
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
334
- value: mod,
335
- enumerable: true
336
- }) : target, mod);
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
337
15
  };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
338
25
  // src/cli/index.ts
339
26
  var import_commander = require("commander");
27
+
340
28
  // package.json
341
29
  var package_default = {
342
- name: "react-email",
343
- version: "4.0.0-alpha.4",
344
- description: "A live preview of your emails right in your browser.",
345
- bin: {
346
- email: "./dist/cli/index.js"
347
- },
348
- scripts: {
349
- build: "tsup-node && node build-preview-server.mjs",
350
- dev: "tsup-node --watch",
351
- test: "vitest run",
352
- "test:watch": "vitest",
353
- clean: "rm -rf dist"
354
- },
355
- license: "MIT",
356
- repository: {
357
- type: "git",
358
- url: "https://github.com/resend/react-email.git",
359
- directory: "packages/react-email"
360
- },
361
- keywords: [
362
- "react",
363
- "email"
364
- ],
365
- engines: {
366
- node: ">=18.0.0"
367
- },
368
- dependencies: {
369
- "@babel/parser": "7.24.5",
370
- "@babel/traverse": "7.25.6",
371
- chalk: "4.1.2",
372
- chokidar: "4.0.3",
373
- commander: "11.1.0",
374
- debounce: "2.0.0",
375
- esbuild: "0.23.0",
376
- glob: "10.3.4",
377
- "log-symbols": "4.1.0",
378
- "mime-types": "2.1.35",
379
- next: "15.1.2",
380
- "normalize-path": "3.0.0",
381
- ora: "5.4.1",
382
- "socket.io": "4.8.1"
383
- },
384
- devDependencies: {
385
- "@lottiefiles/dotlottie-react": "0.12.3",
386
- "@radix-ui/colors": "1.0.1",
387
- "@radix-ui/react-collapsible": "1.1.0",
388
- "@radix-ui/react-dropdown-menu": "2.1.4",
389
- "@radix-ui/react-popover": "1.1.1",
390
- "@radix-ui/react-slot": "1.1.0",
391
- "@radix-ui/react-tabs": "1.1.1",
392
- "@radix-ui/react-toggle-group": "1.1.0",
393
- "@radix-ui/react-tooltip": "1.1.2",
394
- "@react-email/render": "workspace:*",
395
- "@swc/core": "1.4.15",
396
- "@types/babel__core": "7.20.5",
397
- "@types/babel__traverse": "*",
398
- "@types/fs-extra": "11.0.1",
399
- "@types/mime-types": "2.1.4",
400
- "@types/node": "22.10.2",
401
- "@types/normalize-path": "3.0.2",
402
- "@types/react": "^19",
403
- "@types/react-dom": "^19",
404
- "@types/webpack": "5.28.5",
405
- "@vercel/style-guide": "5.1.0",
406
- autoprefixer: "10.4.20",
407
- clsx: "2.1.0",
408
- "framer-motion": "12.0.0-alpha.2",
409
- "node-html-parser": "6.1.13",
410
- postcss: "8.4.40",
411
- "prettier-plugin-tailwindcss": "0.6.6",
412
- "pretty-bytes": "6.1.1",
413
- "prism-react-renderer": "2.1.0",
414
- "module-punycode": "npm:punycode@2.3.1",
415
- react: "^19",
416
- "react-dom": "^19",
417
- sharp: "0.33.3",
418
- "socket.io-client": "4.8.0",
419
- sonner: "1.7.1",
420
- "source-map-js": "1.0.2",
421
- spamc: "0.0.5",
422
- "stacktrace-parser": "0.1.10",
423
- "tailwind-merge": "2.2.0",
424
- tailwindcss: "3.4.0",
425
- tsup: "7.2.0",
426
- tsx: "4.9.0",
427
- typescript: "5.1.6",
428
- "use-debounce": "10.0.4",
429
- vitest: "1.1.3"
430
- }
30
+ name: "react-email",
31
+ version: "4.0.0-alpha.6",
32
+ description: "A live preview of your emails right in your browser.",
33
+ bin: {
34
+ email: "./dist/cli/index.js"
35
+ },
36
+ scripts: {
37
+ build: "tsup-node && node ./scripts/build-preview-server.mjs",
38
+ "caniemail:fetch": "node ./scripts/fill-caniemail-data.mjs",
39
+ clean: "rm -rf dist",
40
+ dev: "tsup-node --watch",
41
+ "dev:preview": "cd ../../apps/demo && tsx ../../packages/react-email/src/cli/index.ts dev",
42
+ test: "vitest run",
43
+ "test:watch": "vitest"
44
+ },
45
+ license: "MIT",
46
+ repository: {
47
+ type: "git",
48
+ url: "https://github.com/resend/react-email.git",
49
+ directory: "packages/react-email"
50
+ },
51
+ keywords: ["react", "email"],
52
+ engines: {
53
+ node: ">=18.0.0"
54
+ },
55
+ dependencies: {
56
+ "@babel/parser": "7.24.5",
57
+ "@babel/traverse": "7.25.6",
58
+ chalk: "4.1.2",
59
+ chokidar: "4.0.3",
60
+ commander: "11.1.0",
61
+ debounce: "2.0.0",
62
+ esbuild: "0.23.0",
63
+ glob: "10.3.4",
64
+ "log-symbols": "4.1.0",
65
+ "mime-types": "2.1.35",
66
+ next: "15.2.2",
67
+ "normalize-path": "3.0.0",
68
+ ora: "5.4.1",
69
+ "socket.io": "4.8.1"
70
+ },
71
+ devDependencies: {
72
+ "@babel/core": "7.26.10",
73
+ "@lottiefiles/dotlottie-react": "0.12.3",
74
+ "@radix-ui/colors": "1.0.1",
75
+ "@radix-ui/react-collapsible": "1.1.0",
76
+ "@radix-ui/react-dropdown-menu": "2.1.4",
77
+ "@radix-ui/react-popover": "1.1.1",
78
+ "@radix-ui/react-slot": "1.1.0",
79
+ "@radix-ui/react-tabs": "1.1.1",
80
+ "@radix-ui/react-toggle-group": "1.1.0",
81
+ "@radix-ui/react-tooltip": "1.1.2",
82
+ "@react-email/render": "workspace:*",
83
+ "@swc/core": "1.4.15",
84
+ "@types/babel__core": "7.20.5",
85
+ "@types/babel__traverse": "*",
86
+ "@types/fs-extra": "11.0.1",
87
+ "@types/mime-types": "2.1.4",
88
+ "@types/node": "22.10.2",
89
+ "@types/normalize-path": "3.0.2",
90
+ "@types/react": "19.0.10",
91
+ "@types/react-dom": "19.0.4",
92
+ "@types/webpack": "5.28.5",
93
+ "@vercel/style-guide": "5.1.0",
94
+ autoprefixer: "10.4.20",
95
+ clsx: "2.1.0",
96
+ "framer-motion": "12.0.0-alpha.2",
97
+ jiti: "2.4.2",
98
+ json5: "2.2.3",
99
+ "module-punycode": "npm:punycode@2.3.1",
100
+ "node-html-parser": "6.1.13",
101
+ postcss: "8.4.40",
102
+ "prettier-plugin-tailwindcss": "0.6.6",
103
+ "pretty-bytes": "6.1.1",
104
+ "prism-react-renderer": "2.1.0",
105
+ react: "19.0.0",
106
+ "react-dom": "19.0.0",
107
+ sharp: "0.33.3",
108
+ "socket.io-client": "4.8.0",
109
+ sonner: "1.7.1",
110
+ "source-map-js": "1.0.2",
111
+ spamc: "0.0.5",
112
+ "stacktrace-parser": "0.1.10",
113
+ "tailwind-merge": "2.2.0",
114
+ tailwindcss: "3.4.0",
115
+ tsup: "7.2.0",
116
+ tsx: "4.9.0",
117
+ typescript: "5.8.2",
118
+ "use-debounce": "10.0.4",
119
+ vitest: "1.1.3",
120
+ zod: "3.24.2"
121
+ }
431
122
  };
123
+
432
124
  // src/cli/commands/build.ts
433
125
  var import_node_child_process = require("child_process");
434
126
  var import_node_fs5 = __toESM(require("fs"));
435
127
  var import_node_path8 = __toESM(require("path"));
436
128
  var import_log_symbols3 = __toESM(require("log-symbols"));
437
129
  var import_ora2 = __toESM(require("ora"));
130
+
438
131
  // src/utils/get-emails-directory-metadata.ts
439
132
  var import_node_fs = __toESM(require("fs"));
440
133
  var import_node_path = __toESM(require("path"));
441
- var isFileAnEmail = function(fullPath) {
442
- var stat = import_node_fs.default.statSync(fullPath);
443
- if (stat.isDirectory()) return false;
444
- var ext = import_node_path.default.parse(fullPath).ext;
445
- if (![
446
- ".js",
447
- ".tsx",
448
- ".jsx"
449
- ].includes(ext)) return false;
450
- if (!import_node_fs.default.existsSync(fullPath)) {
451
- return false;
452
- }
453
- var fileContents = import_node_fs.default.readFileSync(fullPath, "utf8");
454
- return /\bexport\s+default\b/gm.test(fileContents);
134
+ var isFileAnEmail = (fullPath) => {
135
+ const stat = import_node_fs.default.statSync(fullPath);
136
+ if (stat.isDirectory())
137
+ return false;
138
+ const { ext } = import_node_path.default.parse(fullPath);
139
+ if (![".js", ".tsx", ".jsx"].includes(ext))
140
+ return false;
141
+ if (!import_node_fs.default.existsSync(fullPath)) {
142
+ return false;
143
+ }
144
+ const fileContents = import_node_fs.default.readFileSync(fullPath, "utf8");
145
+ return /\bexport\s+default\b/gm.test(fileContents);
455
146
  };
456
- var mergeDirectoriesWithSubDirectories = function(emailsDirectoryMetadata) {
457
- var currentResultingMergedDirectory = emailsDirectoryMetadata;
458
- while(currentResultingMergedDirectory.emailFilenames.length === 0 && currentResultingMergedDirectory.subDirectories.length === 1){
459
- var onlySubDirectory = currentResultingMergedDirectory.subDirectories[0];
460
- currentResultingMergedDirectory = _object_spread_props(_object_spread({}, onlySubDirectory), {
461
- directoryName: import_node_path.default.join(currentResultingMergedDirectory.directoryName, onlySubDirectory.directoryName)
462
- });
463
- }
464
- return currentResultingMergedDirectory;
465
- };
466
- var getEmailsDirectoryMetadata = function() {
467
- var _ref = _async_to_generator(function(absolutePathToEmailsDirectory) {
468
- var keepFileExtensions, isSubDirectory, baseDirectoryPath, dirents, emailFilenames, subDirectories, emailsMetadata;
469
- var _arguments = arguments;
470
- return _ts_generator(this, function(_state) {
471
- switch(_state.label){
472
- case 0:
473
- keepFileExtensions = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : false, isSubDirectory = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : false, baseDirectoryPath = _arguments.length > 3 && _arguments[3] !== void 0 ? _arguments[3] : absolutePathToEmailsDirectory;
474
- if (!import_node_fs.default.existsSync(absolutePathToEmailsDirectory)) return [
475
- 2
476
- ];
477
- return [
478
- 4,
479
- import_node_fs.default.promises.readdir(absolutePathToEmailsDirectory, {
480
- withFileTypes: true
481
- })
482
- ];
483
- case 1:
484
- dirents = _state.sent();
485
- emailFilenames = dirents.filter(function(dirent) {
486
- return isFileAnEmail(import_node_path.default.join(absolutePathToEmailsDirectory, dirent.name));
487
- }).map(function(dirent) {
488
- return keepFileExtensions ? dirent.name : dirent.name.replace(import_node_path.default.extname(dirent.name), "");
489
- });
490
- return [
491
- 4,
492
- Promise.all(dirents.filter(function(dirent) {
493
- return dirent.isDirectory() && !dirent.name.startsWith("_") && dirent.name !== "static";
494
- }).map(function(dirent) {
495
- var direntAbsolutePath = import_node_path.default.join(absolutePathToEmailsDirectory, dirent.name);
496
- return getEmailsDirectoryMetadata(direntAbsolutePath, keepFileExtensions, true, baseDirectoryPath);
497
- }))
498
- ];
499
- case 2:
500
- subDirectories = _state.sent();
501
- emailsMetadata = {
502
- absolutePath: absolutePathToEmailsDirectory,
503
- relativePath: import_node_path.default.relative(baseDirectoryPath, absolutePathToEmailsDirectory),
504
- directoryName: absolutePathToEmailsDirectory.split(import_node_path.default.sep).pop(),
505
- emailFilenames: emailFilenames,
506
- subDirectories: subDirectories
507
- };
508
- return [
509
- 2,
510
- isSubDirectory ? mergeDirectoriesWithSubDirectories(emailsMetadata) : emailsMetadata
511
- ];
512
- }
513
- });
514
- });
515
- return function getEmailsDirectoryMetadata(absolutePathToEmailsDirectory) {
516
- return _ref.apply(this, arguments);
147
+ var mergeDirectoriesWithSubDirectories = (emailsDirectoryMetadata) => {
148
+ let currentResultingMergedDirectory = emailsDirectoryMetadata;
149
+ while (currentResultingMergedDirectory.emailFilenames.length === 0 && currentResultingMergedDirectory.subDirectories.length === 1) {
150
+ const onlySubDirectory = currentResultingMergedDirectory.subDirectories[0];
151
+ currentResultingMergedDirectory = {
152
+ ...onlySubDirectory,
153
+ directoryName: import_node_path.default.join(
154
+ currentResultingMergedDirectory.directoryName,
155
+ onlySubDirectory.directoryName
156
+ )
517
157
  };
518
- }();
158
+ }
159
+ return currentResultingMergedDirectory;
160
+ };
161
+ var getEmailsDirectoryMetadata = async (absolutePathToEmailsDirectory, keepFileExtensions = false, isSubDirectory = false, baseDirectoryPath = absolutePathToEmailsDirectory) => {
162
+ if (!import_node_fs.default.existsSync(absolutePathToEmailsDirectory))
163
+ return;
164
+ const dirents = await import_node_fs.default.promises.readdir(absolutePathToEmailsDirectory, {
165
+ withFileTypes: true
166
+ });
167
+ const emailFilenames = dirents.filter(
168
+ (dirent) => isFileAnEmail(import_node_path.default.join(absolutePathToEmailsDirectory, dirent.name))
169
+ ).map(
170
+ (dirent) => keepFileExtensions ? dirent.name : dirent.name.replace(import_node_path.default.extname(dirent.name), "")
171
+ );
172
+ const subDirectories = await Promise.all(
173
+ dirents.filter(
174
+ (dirent) => dirent.isDirectory() && !dirent.name.startsWith("_") && dirent.name !== "static"
175
+ ).map((dirent) => {
176
+ const direntAbsolutePath = import_node_path.default.join(
177
+ absolutePathToEmailsDirectory,
178
+ dirent.name
179
+ );
180
+ return getEmailsDirectoryMetadata(
181
+ direntAbsolutePath,
182
+ keepFileExtensions,
183
+ true,
184
+ baseDirectoryPath
185
+ );
186
+ })
187
+ );
188
+ const emailsMetadata = {
189
+ absolutePath: absolutePathToEmailsDirectory,
190
+ relativePath: import_node_path.default.relative(
191
+ baseDirectoryPath,
192
+ absolutePathToEmailsDirectory
193
+ ),
194
+ directoryName: absolutePathToEmailsDirectory.split(import_node_path.default.sep).pop(),
195
+ emailFilenames,
196
+ subDirectories
197
+ };
198
+ return isSubDirectory ? mergeDirectoriesWithSubDirectories(emailsMetadata) : emailsMetadata;
199
+ };
200
+
519
201
  // src/utils/register-spinner-autostopping.ts
520
202
  var import_log_symbols = __toESM(require("log-symbols"));
521
203
  var spinners = /* @__PURE__ */ new Set();
522
- process.on("SIGINT", function() {
523
- spinners.forEach(function(spinner) {
524
- if (spinner.isSpinning) {
525
- spinner.stop();
526
- }
527
- });
204
+ process.on("SIGINT", () => {
205
+ spinners.forEach((spinner) => {
206
+ if (spinner.isSpinning) {
207
+ spinner.stop();
208
+ }
209
+ });
528
210
  });
529
- process.on("exit", function(code) {
530
- if (code !== 0) {
531
- spinners.forEach(function(spinner) {
532
- if (spinner.isSpinning) {
533
- spinner.stopAndPersist({
534
- symbol: import_log_symbols.default.error
535
- });
536
- }
211
+ process.on("exit", (code) => {
212
+ if (code !== 0) {
213
+ spinners.forEach((spinner) => {
214
+ if (spinner.isSpinning) {
215
+ spinner.stopAndPersist({
216
+ symbol: import_log_symbols.default.error
537
217
  });
538
- }
218
+ }
219
+ });
220
+ }
539
221
  });
540
- var registerSpinnerAutostopping = function(spinner) {
541
- spinners.add(spinner);
222
+ var registerSpinnerAutostopping = (spinner) => {
223
+ spinners.add(spinner);
542
224
  };
225
+
543
226
  // src/cli/utils/tree.ts
544
227
  var import_node_fs2 = require("fs");
545
228
  var import_node_os = __toESM(require("os"));
546
229
  var import_node_path2 = __toESM(require("path"));
547
230
  var SYMBOLS = {
548
- BRANCH: "├── ",
549
- EMPTY: "",
550
- INDENT: " ",
551
- LAST_BRANCH: "└── ",
552
- VERTICAL: " "
231
+ BRANCH: "\u251C\u2500\u2500 ",
232
+ EMPTY: "",
233
+ INDENT: " ",
234
+ LAST_BRANCH: "\u2514\u2500\u2500 ",
235
+ VERTICAL: "\u2502 "
553
236
  };
554
- var getTreeLines = function() {
555
- var _ref = _async_to_generator(function(dirPath, depth) {
556
- var currentDepth, base, dirFullpath, dirname, lines, dirStat, _loop, childDirents, i;
557
- var _arguments = arguments;
558
- return _ts_generator(this, function(_state) {
559
- switch(_state.label){
560
- case 0:
561
- currentDepth = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : 0;
562
- base = process.cwd();
563
- dirFullpath = import_node_path2.default.resolve(base, dirPath);
564
- dirname = import_node_path2.default.basename(dirFullpath);
565
- lines = [
566
- dirname
567
- ];
568
- return [
569
- 4,
570
- import_node_fs2.promises.stat(dirFullpath)
571
- ];
572
- case 1:
573
- dirStat = _state.sent();
574
- if (!(dirStat.isDirectory() && currentDepth < depth)) return [
575
- 3,
576
- 6
577
- ];
578
- _loop = function(i) {
579
- var dirent, isLast, branchingSymbol, verticalSymbol, pathToDirectory, treeLinesForSubDirectory;
580
- return _ts_generator(this, function(_state) {
581
- switch(_state.label){
582
- case 0:
583
- dirent = childDirents[i];
584
- isLast = i === childDirents.length - 1;
585
- branchingSymbol = isLast ? SYMBOLS.LAST_BRANCH : SYMBOLS.BRANCH;
586
- verticalSymbol = isLast ? SYMBOLS.INDENT : SYMBOLS.VERTICAL;
587
- if (!dirent.isFile()) return [
588
- 3,
589
- 1
590
- ];
591
- lines.push("".concat(branchingSymbol).concat(dirent.name));
592
- return [
593
- 3,
594
- 3
595
- ];
596
- case 1:
597
- pathToDirectory = import_node_path2.default.join(dirFullpath, dirent.name);
598
- return [
599
- 4,
600
- getTreeLines(pathToDirectory, depth, currentDepth + 1)
601
- ];
602
- case 2:
603
- treeLinesForSubDirectory = _state.sent();
604
- lines = lines.concat(treeLinesForSubDirectory.map(function(line, index) {
605
- return index === 0 ? "".concat(branchingSymbol).concat(line) : "".concat(verticalSymbol).concat(line);
606
- }));
607
- _state.label = 3;
608
- case 3:
609
- return [
610
- 2
611
- ];
612
- }
613
- });
614
- };
615
- return [
616
- 4,
617
- import_node_fs2.promises.readdir(dirFullpath, {
618
- withFileTypes: true
619
- })
620
- ];
621
- case 2:
622
- childDirents = _state.sent();
623
- childDirents.sort(function(a, b) {
624
- if (a.isDirectory() && b.isFile()) {
625
- return -1;
626
- }
627
- if (a.isFile() && b.isDirectory()) {
628
- return 1;
629
- }
630
- return b.name > a.name ? -1 : 1;
631
- });
632
- i = 0;
633
- _state.label = 3;
634
- case 3:
635
- if (!(i < childDirents.length)) return [
636
- 3,
637
- 6
638
- ];
639
- return [
640
- 5,
641
- _ts_values(_loop(i))
642
- ];
643
- case 4:
644
- _state.sent();
645
- _state.label = 5;
646
- case 5:
647
- i++;
648
- return [
649
- 3,
650
- 3
651
- ];
652
- case 6:
653
- return [
654
- 2,
655
- lines
656
- ];
657
- }
658
- });
237
+ var getTreeLines = async (dirPath, depth, currentDepth = 0) => {
238
+ const base = process.cwd();
239
+ const dirFullpath = import_node_path2.default.resolve(base, dirPath);
240
+ const dirname = import_node_path2.default.basename(dirFullpath);
241
+ let lines = [dirname];
242
+ const dirStat = await import_node_fs2.promises.stat(dirFullpath);
243
+ if (dirStat.isDirectory() && currentDepth < depth) {
244
+ const childDirents = await import_node_fs2.promises.readdir(dirFullpath, { withFileTypes: true });
245
+ childDirents.sort((a, b) => {
246
+ if (a.isDirectory() && b.isFile()) {
247
+ return -1;
248
+ }
249
+ if (a.isFile() && b.isDirectory()) {
250
+ return 1;
251
+ }
252
+ return b.name > a.name ? -1 : 1;
659
253
  });
660
- return function getTreeLines(dirPath, depth) {
661
- return _ref.apply(this, arguments);
662
- };
663
- }();
664
- var tree = function() {
665
- var _ref = _async_to_generator(function(dirPath, depth) {
666
- var lines;
667
- return _ts_generator(this, function(_state) {
668
- switch(_state.label){
669
- case 0:
670
- return [
671
- 4,
672
- getTreeLines(dirPath, depth)
673
- ];
674
- case 1:
675
- lines = _state.sent();
676
- return [
677
- 2,
678
- lines.join(import_node_os.default.EOL)
679
- ];
680
- }
681
- });
682
- });
683
- return function tree(dirPath, depth) {
684
- return _ref.apply(this, arguments);
685
- };
686
- }();
254
+ for (let i = 0; i < childDirents.length; i++) {
255
+ const dirent = childDirents[i];
256
+ const isLast = i === childDirents.length - 1;
257
+ const branchingSymbol = isLast ? SYMBOLS.LAST_BRANCH : SYMBOLS.BRANCH;
258
+ const verticalSymbol = isLast ? SYMBOLS.INDENT : SYMBOLS.VERTICAL;
259
+ if (dirent.isFile()) {
260
+ lines.push(`${branchingSymbol}${dirent.name}`);
261
+ } else {
262
+ const pathToDirectory = import_node_path2.default.join(dirFullpath, dirent.name);
263
+ const treeLinesForSubDirectory = await getTreeLines(
264
+ pathToDirectory,
265
+ depth,
266
+ currentDepth + 1
267
+ );
268
+ lines = lines.concat(
269
+ treeLinesForSubDirectory.map(
270
+ (line, index) => index === 0 ? `${branchingSymbol}${line}` : `${verticalSymbol}${line}`
271
+ )
272
+ );
273
+ }
274
+ }
275
+ }
276
+ return lines;
277
+ };
278
+ var tree = async (dirPath, depth) => {
279
+ const lines = await getTreeLines(dirPath, depth);
280
+ return lines.join(import_node_os.default.EOL);
281
+ };
282
+
687
283
  // src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
688
284
  var import_node_path7 = __toESM(require("path"));
689
285
  var import_chokidar = require("chokidar");
690
286
  var import_debounce = __toESM(require("debounce"));
691
287
  var import_socket = require("socket.io");
288
+
692
289
  // src/cli/utils/preview/hot-reloading/create-dependency-graph.ts
693
290
  var import_node_fs4 = require("fs");
694
291
  var import_node_path6 = __toESM(require("path"));
292
+
695
293
  // src/cli/utils/preview/start-dev-server.ts
696
294
  var import_node_http = __toESM(require("http"));
697
295
  var import_node_path5 = __toESM(require("path"));
@@ -700,1627 +298,759 @@ var import_chalk = __toESM(require("chalk"));
700
298
  var import_log_symbols2 = __toESM(require("log-symbols"));
701
299
  var import_next = __toESM(require("next"));
702
300
  var import_ora = __toESM(require("ora"));
301
+
703
302
  // src/cli/utils/preview/get-env-variables-for-preview-app.ts
704
303
  var import_node_path3 = __toESM(require("path"));
705
- var getEnvVariablesForPreviewApp = function(relativePathToEmailsDirectory, cwd) {
706
- return {
707
- EMAILS_DIR_RELATIVE_PATH: relativePathToEmailsDirectory,
708
- EMAILS_DIR_ABSOLUTE_PATH: import_node_path3.default.resolve(cwd, relativePathToEmailsDirectory),
709
- USER_PROJECT_LOCATION: cwd
710
- };
304
+ var getEnvVariablesForPreviewApp = (relativePathToEmailsDirectory, cwd) => {
305
+ return {
306
+ EMAILS_DIR_RELATIVE_PATH: relativePathToEmailsDirectory,
307
+ EMAILS_DIR_ABSOLUTE_PATH: import_node_path3.default.resolve(cwd, relativePathToEmailsDirectory),
308
+ USER_PROJECT_LOCATION: cwd
309
+ };
711
310
  };
311
+
712
312
  // src/cli/utils/preview/serve-static-file.ts
713
313
  var import_node_fs3 = require("fs");
714
314
  var import_node_path4 = __toESM(require("path"));
715
315
  var import_mime_types = require("mime-types");
716
- var serveStaticFile = function() {
717
- var _ref = _async_to_generator(function(res, parsedUrl, staticDirRelativePath) {
718
- var staticBaseDir, pathname, ext, fileAbsolutePath, fileHandle, fileData, exception;
719
- return _ts_generator(this, function(_state) {
720
- switch(_state.label){
721
- case 0:
722
- staticBaseDir = import_node_path4.default.join(process.cwd(), staticDirRelativePath);
723
- pathname = parsedUrl.pathname;
724
- ext = import_node_path4.default.parse(pathname).ext;
725
- fileAbsolutePath = import_node_path4.default.join(staticBaseDir, pathname);
726
- return [
727
- 4,
728
- import_node_fs3.promises.open(fileAbsolutePath, "r")
729
- ];
730
- case 1:
731
- fileHandle = _state.sent();
732
- _state.label = 2;
733
- case 2:
734
- _state.trys.push([
735
- 2,
736
- 4,
737
- 5,
738
- 6
739
- ]);
740
- return [
741
- 4,
742
- import_node_fs3.promises.readFile(fileHandle)
743
- ];
744
- case 3:
745
- fileData = _state.sent();
746
- res.setHeader("Content-type", (0, import_mime_types.lookup)(ext) || "text/plain");
747
- res.end(fileData);
748
- return [
749
- 3,
750
- 6
751
- ];
752
- case 4:
753
- exception = _state.sent();
754
- console.error("Could not read file at ".concat(fileAbsolutePath, " to be served, here's the exception:"), exception);
755
- res.statusCode = 500;
756
- res.end("Could not read file to be served! Check your terminal for more information.");
757
- return [
758
- 3,
759
- 6
760
- ];
761
- case 5:
762
- fileHandle.close();
763
- return [
764
- 7
765
- ];
766
- case 6:
767
- return [
768
- 2
769
- ];
770
- }
771
- });
772
- });
773
- return function serveStaticFile(res, parsedUrl, staticDirRelativePath) {
774
- return _ref.apply(this, arguments);
775
- };
776
- }();
316
+ var serveStaticFile = async (res, parsedUrl, staticDirRelativePath) => {
317
+ const staticBaseDir = import_node_path4.default.join(process.cwd(), staticDirRelativePath);
318
+ const pathname = parsedUrl.pathname;
319
+ const ext = import_node_path4.default.parse(pathname).ext;
320
+ const fileAbsolutePath = import_node_path4.default.join(staticBaseDir, pathname);
321
+ const fileHandle = await import_node_fs3.promises.open(fileAbsolutePath, "r");
322
+ try {
323
+ const fileData = await import_node_fs3.promises.readFile(fileHandle);
324
+ res.setHeader("Content-type", (0, import_mime_types.lookup)(ext) || "text/plain");
325
+ res.end(fileData);
326
+ } catch (exception) {
327
+ console.error(
328
+ `Could not read file at ${fileAbsolutePath} to be served, here's the exception:`,
329
+ exception
330
+ );
331
+ res.statusCode = 500;
332
+ res.end(
333
+ "Could not read file to be served! Check your terminal for more information."
334
+ );
335
+ } finally {
336
+ fileHandle.close();
337
+ }
338
+ };
339
+
777
340
  // src/cli/utils/preview/start-dev-server.ts
778
341
  var devServer;
779
- var safeAsyncServerListen = function(server, port) {
780
- return new Promise(function(resolve) {
781
- server.listen(port, function() {
782
- resolve({
783
- portAlreadyInUse: false
784
- });
785
- });
786
- server.on("error", function(e) {
787
- if (e.code === "EADDRINUSE") {
788
- resolve({
789
- portAlreadyInUse: true
790
- });
791
- }
792
- });
342
+ var safeAsyncServerListen = (server, port) => {
343
+ return new Promise((resolve) => {
344
+ server.listen(port, () => {
345
+ resolve({ portAlreadyInUse: false });
346
+ });
347
+ server.on("error", (e) => {
348
+ if (e.code === "EADDRINUSE") {
349
+ resolve({ portAlreadyInUse: true });
350
+ }
793
351
  });
352
+ });
794
353
  };
795
354
  var isDev = !__filename.endsWith(import_node_path5.default.join("cli", "index.js"));
796
355
  var cliPacakgeLocation = isDev ? import_node_path5.default.resolve(__dirname, "../../../..") : import_node_path5.default.resolve(__dirname, "../..");
797
356
  var previewServerLocation = isDev ? import_node_path5.default.resolve(__dirname, "../../../..") : import_node_path5.default.resolve(__dirname, "../preview");
798
- var startDevServer = function() {
799
- var _ref = _async_to_generator(function(emailsDirRelativePath, staticBaseDirRelativePath, port) {
800
- var portAlreadyInUse, nextPortToTry, spinner, timeBeforeNextReady, app, isNextReady, nextReadyPromise, nextHandleRequest, secondsToNextReady;
801
- return _ts_generator(this, function(_state) {
802
- switch(_state.label){
803
- case 0:
804
- devServer = import_node_http.default.createServer(function(req, res) {
805
- if (!req.url) {
806
- res.end(404);
807
- return;
808
- }
809
- var parsedUrl = import_node_url.default.parse(req.url, true);
810
- res.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store");
811
- res.setHeader("Pragma", "no-cache");
812
- res.setHeader("Expires", "-1");
813
- try {
814
- var _parsedUrl_path;
815
- if (((_parsedUrl_path = parsedUrl.path) === null || _parsedUrl_path === void 0 ? void 0 : _parsedUrl_path.includes("static/")) && !parsedUrl.path.includes("_next/static/")) {
816
- void serveStaticFile(res, parsedUrl, staticBaseDirRelativePath);
817
- } else if (!isNextReady) {
818
- void nextReadyPromise.then(function() {
819
- return nextHandleRequest === null || nextHandleRequest === void 0 ? void 0 : nextHandleRequest(req, res, parsedUrl);
820
- });
821
- } else {
822
- void (nextHandleRequest === null || nextHandleRequest === void 0 ? void 0 : nextHandleRequest(req, res, parsedUrl));
823
- }
824
- } catch (e) {
825
- console.error("caught error", e);
826
- res.writeHead(500);
827
- res.end();
828
- }
829
- });
830
- return [
831
- 4,
832
- safeAsyncServerListen(devServer, port)
833
- ];
834
- case 1:
835
- portAlreadyInUse = _state.sent().portAlreadyInUse;
836
- if (!portAlreadyInUse) {
837
- console.log(import_chalk.default.greenBright(" React Email ".concat(package_default.version)));
838
- console.log(" Running preview at: http://localhost:".concat(port, "\n"));
839
- } else {
840
- nextPortToTry = port + 1;
841
- console.warn(" ".concat(import_log_symbols2.default.warning, " Port ").concat(port, " is already in use, trying ").concat(nextPortToTry));
842
- return [
843
- 2,
844
- startDevServer(emailsDirRelativePath, staticBaseDirRelativePath, nextPortToTry)
845
- ];
846
- }
847
- devServer.on("close", /*#__PURE__*/ _async_to_generator(function() {
848
- return _ts_generator(this, function(_state) {
849
- switch(_state.label){
850
- case 0:
851
- return [
852
- 4,
853
- app.close()
854
- ];
855
- case 1:
856
- _state.sent();
857
- return [
858
- 2
859
- ];
860
- }
861
- });
862
- }));
863
- devServer.on("error", function(e) {
864
- console.error(" ".concat(import_log_symbols2.default.error, " preview server error: "), JSON.stringify(e));
865
- process.exit(1);
866
- });
867
- spinner = (0, import_ora.default)({
868
- text: "Getting react-email preview server ready...\n",
869
- prefixText: " "
870
- }).start();
871
- registerSpinnerAutostopping(spinner);
872
- timeBeforeNextReady = performance.now();
873
- process.env = _object_spread({
874
- NODE_ENV: "development"
875
- }, process.env, getEnvVariablesForPreviewApp(// If we don't do normalization here, stuff like https://github.com/resend/react-email/issues/1354 happens.
876
- import_node_path5.default.normalize(emailsDirRelativePath), process.cwd()));
877
- app = (0, import_next.default)({
878
- // passing in env here does not get the environment variables there
879
- dev: isDev,
880
- conf: {
881
- images: {
882
- // This is to avoid the warning with sharp
883
- unoptimized: true
884
- }
885
- },
886
- hostname: "localhost",
887
- port: port,
888
- dir: previewServerLocation
889
- });
890
- isNextReady = false;
891
- nextReadyPromise = app.prepare();
892
- return [
893
- 4,
894
- nextReadyPromise
895
- ];
896
- case 2:
897
- _state.sent();
898
- isNextReady = true;
899
- nextHandleRequest = app.getRequestHandler();
900
- secondsToNextReady = ((performance.now() - timeBeforeNextReady) / 1e3).toFixed(1);
901
- spinner.stopAndPersist({
902
- text: "Ready in ".concat(secondsToNextReady, "s\n"),
903
- symbol: import_log_symbols2.default.success
904
- });
905
- return [
906
- 2,
907
- devServer
908
- ];
909
- }
910
- });
911
- });
912
- return function startDevServer(emailsDirRelativePath, staticBaseDirRelativePath, port) {
913
- return _ref.apply(this, arguments);
914
- };
915
- }();
916
- var makeExitHandler = function(options) {
917
- return function(_codeOrSignal) {
918
- if (typeof devServer !== "undefined") {
919
- console.log("\nshutting down dev server");
920
- devServer.close();
921
- devServer = void 0;
922
- }
923
- if (options === null || options === void 0 ? void 0 : options.shouldKillProcess) {
924
- process.exit(options.killWithErrorCode ? 1 : 0);
925
- }
926
- };
357
+ var startDevServer = async (emailsDirRelativePath, staticBaseDirRelativePath, port) => {
358
+ devServer = import_node_http.default.createServer((req, res) => {
359
+ if (!req.url) {
360
+ res.end(404);
361
+ return;
362
+ }
363
+ const parsedUrl = import_node_url.default.parse(req.url, true);
364
+ res.setHeader(
365
+ "Cache-Control",
366
+ "no-cache, max-age=0, must-revalidate, no-store"
367
+ );
368
+ res.setHeader("Pragma", "no-cache");
369
+ res.setHeader("Expires", "-1");
370
+ try {
371
+ if (parsedUrl.path?.includes("static/") && !parsedUrl.path.includes("_next/static/")) {
372
+ void serveStaticFile(res, parsedUrl, staticBaseDirRelativePath);
373
+ } else if (!isNextReady) {
374
+ void nextReadyPromise.then(
375
+ () => nextHandleRequest?.(req, res, parsedUrl)
376
+ );
377
+ } else {
378
+ void nextHandleRequest?.(req, res, parsedUrl);
379
+ }
380
+ } catch (e) {
381
+ console.error("caught error", e);
382
+ res.writeHead(500);
383
+ res.end();
384
+ }
385
+ });
386
+ const { portAlreadyInUse } = await safeAsyncServerListen(devServer, port);
387
+ if (!portAlreadyInUse) {
388
+ console.log(import_chalk.default.greenBright(` React Email ${package_default.version}`));
389
+ console.log(` Running preview at: http://localhost:${port}
390
+ `);
391
+ } else {
392
+ const nextPortToTry = port + 1;
393
+ console.warn(
394
+ ` ${import_log_symbols2.default.warning} Port ${port} is already in use, trying ${nextPortToTry}`
395
+ );
396
+ return startDevServer(
397
+ emailsDirRelativePath,
398
+ staticBaseDirRelativePath,
399
+ nextPortToTry
400
+ );
401
+ }
402
+ devServer.on("close", async () => {
403
+ await app.close();
404
+ });
405
+ devServer.on("error", (e) => {
406
+ console.error(
407
+ ` ${import_log_symbols2.default.error} preview server error: `,
408
+ JSON.stringify(e)
409
+ );
410
+ process.exit(1);
411
+ });
412
+ const spinner = (0, import_ora.default)({
413
+ text: "Getting react-email preview server ready...\n",
414
+ prefixText: " "
415
+ }).start();
416
+ registerSpinnerAutostopping(spinner);
417
+ const timeBeforeNextReady = performance.now();
418
+ process.env = {
419
+ NODE_ENV: "development",
420
+ ...process.env,
421
+ ...getEnvVariablesForPreviewApp(
422
+ // If we don't do normalization here, stuff like https://github.com/resend/react-email/issues/1354 happens.
423
+ import_node_path5.default.normalize(emailsDirRelativePath),
424
+ process.cwd()
425
+ )
426
+ };
427
+ const app = (0, import_next.default)({
428
+ // passing in env here does not get the environment variables there
429
+ dev: isDev,
430
+ conf: {
431
+ images: {
432
+ // This is to avoid the warning with sharp
433
+ unoptimized: true
434
+ }
435
+ },
436
+ hostname: "localhost",
437
+ port,
438
+ dir: previewServerLocation
439
+ });
440
+ let isNextReady = false;
441
+ const nextReadyPromise = app.prepare();
442
+ await nextReadyPromise;
443
+ isNextReady = true;
444
+ const nextHandleRequest = app.getRequestHandler();
445
+ const secondsToNextReady = ((performance.now() - timeBeforeNextReady) / 1e3).toFixed(1);
446
+ spinner.stopAndPersist({
447
+ text: `Ready in ${secondsToNextReady}s
448
+ `,
449
+ symbol: import_log_symbols2.default.success
450
+ });
451
+ return devServer;
452
+ };
453
+ var makeExitHandler = (options) => (_codeOrSignal) => {
454
+ if (typeof devServer !== "undefined") {
455
+ console.log("\nshutting down dev server");
456
+ devServer.close();
457
+ devServer = void 0;
458
+ }
459
+ if (options?.shouldKillProcess) {
460
+ process.exit(options.killWithErrorCode ? 1 : 0);
461
+ }
927
462
  };
928
463
  process.on("exit", makeExitHandler());
929
- process.on("SIGINT", makeExitHandler({
930
- shouldKillProcess: true,
931
- killWithErrorCode: false
932
- }));
933
- process.on("SIGUSR1", makeExitHandler({
934
- shouldKillProcess: true,
935
- killWithErrorCode: false
936
- }));
937
- process.on("SIGUSR2", makeExitHandler({
938
- shouldKillProcess: true,
939
- killWithErrorCode: false
940
- }));
941
- process.on("uncaughtException", makeExitHandler({
942
- shouldKillProcess: true,
943
- killWithErrorCode: true
944
- }));
464
+ process.on(
465
+ "SIGINT",
466
+ makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
467
+ );
468
+ process.on(
469
+ "SIGUSR1",
470
+ makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
471
+ );
472
+ process.on(
473
+ "SIGUSR2",
474
+ makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
475
+ );
476
+ process.on(
477
+ "uncaughtException",
478
+ makeExitHandler({ shouldKillProcess: true, killWithErrorCode: true })
479
+ );
480
+
945
481
  // src/cli/utils/preview/hot-reloading/get-imported-modules.ts
946
482
  var import_parser = require("@babel/parser");
947
483
  var import_traverse = __toESM(require("@babel/traverse"));
948
- var getImportedModules = function(contents) {
949
- var importedPaths = [];
950
- var parsedContents = (0, import_parser.parse)(contents, {
951
- sourceType: "unambiguous",
952
- strictMode: false,
953
- errorRecovery: true,
954
- plugins: [
955
- "jsx",
956
- "typescript",
957
- "decorators"
958
- ]
959
- });
960
- (0, import_traverse.default)(parsedContents, {
961
- ImportDeclaration: function ImportDeclaration(param) {
962
- var node = param.node;
963
- importedPaths.push(node.source.value);
964
- },
965
- ExportAllDeclaration: function ExportAllDeclaration(param) {
966
- var node = param.node;
967
- importedPaths.push(node.source.value);
968
- },
969
- ExportNamedDeclaration: function ExportNamedDeclaration(param) {
970
- var node = param.node;
971
- if (node.source) {
972
- importedPaths.push(node.source.value);
973
- }
974
- },
975
- CallExpression: function CallExpression(param) {
976
- var node = param.node;
977
- if ("name" in node.callee && node.callee.name === "require") {
978
- if (node.arguments.length === 1) {
979
- var importPathNode = node.arguments[0];
980
- if (importPathNode.type === "StringLiteral") {
981
- importedPaths.push(importPathNode.value);
982
- }
983
- }
984
- }
484
+ var getImportedModules = (contents) => {
485
+ const importedPaths = [];
486
+ const parsedContents = (0, import_parser.parse)(contents, {
487
+ sourceType: "unambiguous",
488
+ strictMode: false,
489
+ errorRecovery: true,
490
+ plugins: ["jsx", "typescript", "decorators"]
491
+ });
492
+ (0, import_traverse.default)(parsedContents, {
493
+ ImportDeclaration({ node }) {
494
+ importedPaths.push(node.source.value);
495
+ },
496
+ ExportAllDeclaration({ node }) {
497
+ importedPaths.push(node.source.value);
498
+ },
499
+ ExportNamedDeclaration({ node }) {
500
+ if (node.source) {
501
+ importedPaths.push(node.source.value);
502
+ }
503
+ },
504
+ CallExpression({ node }) {
505
+ if ("name" in node.callee && node.callee.name === "require") {
506
+ if (node.arguments.length === 1) {
507
+ const importPathNode = node.arguments[0];
508
+ if (importPathNode.type === "StringLiteral") {
509
+ importedPaths.push(importPathNode.value);
510
+ }
985
511
  }
986
- });
987
- return importedPaths;
512
+ }
513
+ }
514
+ });
515
+ return importedPaths;
988
516
  };
517
+
989
518
  // src/cli/utils/preview/hot-reloading/create-dependency-graph.ts
990
- var readAllFilesInsideDirectory = function() {
991
- var _ref = _async_to_generator(function(directory) {
992
- var allFilePaths, topLevelDirents, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, dirent, pathToDirent, _, err;
993
- return _ts_generator(this, function(_state) {
994
- switch(_state.label){
995
- case 0:
996
- allFilePaths = [];
997
- return [
998
- 4,
999
- import_node_fs4.promises.readdir(directory, {
1000
- withFileTypes: true
1001
- })
1002
- ];
1003
- case 1:
1004
- topLevelDirents = _state.sent();
1005
- _iteratorAbruptCompletion = false, _didIteratorError = false;
1006
- _state.label = 2;
1007
- case 2:
1008
- _state.trys.push([
1009
- 2,
1010
- 9,
1011
- 10,
1012
- 15
1013
- ]);
1014
- _iterator = _async_iterator(topLevelDirents);
1015
- _state.label = 3;
1016
- case 3:
1017
- return [
1018
- 4,
1019
- _iterator.next()
1020
- ];
1021
- case 4:
1022
- if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
1023
- 3,
1024
- 8
1025
- ];
1026
- _value = _step.value;
1027
- dirent = _value;
1028
- pathToDirent = import_node_path6.default.join(directory, dirent.name);
1029
- if (!dirent.isDirectory()) return [
1030
- 3,
1031
- 6
1032
- ];
1033
- _ = allFilePaths.concat;
1034
- return [
1035
- 4,
1036
- readAllFilesInsideDirectory(pathToDirent)
1037
- ];
1038
- case 5:
1039
- allFilePaths = _.apply(allFilePaths, [
1040
- _state.sent()
1041
- ]);
1042
- return [
1043
- 3,
1044
- 7
1045
- ];
1046
- case 6:
1047
- allFilePaths.push(pathToDirent);
1048
- _state.label = 7;
1049
- case 7:
1050
- _iteratorAbruptCompletion = false;
1051
- return [
1052
- 3,
1053
- 3
1054
- ];
1055
- case 8:
1056
- return [
1057
- 3,
1058
- 15
1059
- ];
1060
- case 9:
1061
- err = _state.sent();
1062
- _didIteratorError = true;
1063
- _iteratorError = err;
1064
- return [
1065
- 3,
1066
- 15
1067
- ];
1068
- case 10:
1069
- _state.trys.push([
1070
- 10,
1071
- ,
1072
- 13,
1073
- 14
1074
- ]);
1075
- if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
1076
- 3,
1077
- 12
1078
- ];
1079
- return [
1080
- 4,
1081
- _iterator.return()
1082
- ];
1083
- case 11:
1084
- _state.sent();
1085
- _state.label = 12;
1086
- case 12:
1087
- return [
1088
- 3,
1089
- 14
1090
- ];
1091
- case 13:
1092
- if (_didIteratorError) {
1093
- throw _iteratorError;
1094
- }
1095
- return [
1096
- 7
1097
- ];
1098
- case 14:
1099
- return [
1100
- 7
1101
- ];
1102
- case 15:
1103
- return [
1104
- 2,
1105
- allFilePaths
1106
- ];
1107
- }
1108
- });
1109
- });
1110
- return function readAllFilesInsideDirectory(directory) {
1111
- return _ref.apply(this, arguments);
1112
- };
1113
- }();
1114
- var isJavascriptModule = function(filePath) {
1115
- var extensionName = import_node_path6.default.extname(filePath);
1116
- return [
1117
- ".js",
1118
- ".ts",
1119
- ".jsx",
1120
- ".tsx",
1121
- ".mjs",
1122
- ".cjs"
1123
- ].includes(extensionName);
1124
- };
1125
- var checkFileExtensionsUntilItExists = function(pathWithoutExtension) {
1126
- if ((0, import_node_fs4.existsSync)("".concat(pathWithoutExtension, ".ts"))) {
1127
- return "".concat(pathWithoutExtension, ".ts");
1128
- }
1129
- if ((0, import_node_fs4.existsSync)("".concat(pathWithoutExtension, ".tsx"))) {
1130
- return "".concat(pathWithoutExtension, ".tsx");
1131
- }
1132
- if ((0, import_node_fs4.existsSync)("".concat(pathWithoutExtension, ".js"))) {
1133
- return "".concat(pathWithoutExtension, ".js");
1134
- }
1135
- if ((0, import_node_fs4.existsSync)("".concat(pathWithoutExtension, ".jsx"))) {
1136
- return "".concat(pathWithoutExtension, ".jsx");
1137
- }
1138
- if ((0, import_node_fs4.existsSync)("".concat(pathWithoutExtension, ".mjs"))) {
1139
- return "".concat(pathWithoutExtension, ".mjs");
1140
- }
1141
- if ((0, import_node_fs4.existsSync)("".concat(pathWithoutExtension, ".cjs"))) {
1142
- return "".concat(pathWithoutExtension, ".cjs");
519
+ var readAllFilesInsideDirectory = async (directory) => {
520
+ let allFilePaths = [];
521
+ const topLevelDirents = await import_node_fs4.promises.readdir(directory, { withFileTypes: true });
522
+ for await (const dirent of topLevelDirents) {
523
+ const pathToDirent = import_node_path6.default.join(directory, dirent.name);
524
+ if (dirent.isDirectory()) {
525
+ allFilePaths = allFilePaths.concat(
526
+ await readAllFilesInsideDirectory(pathToDirent)
527
+ );
528
+ } else {
529
+ allFilePaths.push(pathToDirent);
1143
530
  }
531
+ }
532
+ return allFilePaths;
533
+ };
534
+ var isJavascriptModule = (filePath) => {
535
+ const extensionName = import_node_path6.default.extname(filePath);
536
+ return [".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs"].includes(extensionName);
537
+ };
538
+ var checkFileExtensionsUntilItExists = (pathWithoutExtension) => {
539
+ if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.ts`)) {
540
+ return `${pathWithoutExtension}.ts`;
541
+ }
542
+ if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.tsx`)) {
543
+ return `${pathWithoutExtension}.tsx`;
544
+ }
545
+ if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.js`)) {
546
+ return `${pathWithoutExtension}.js`;
547
+ }
548
+ if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.jsx`)) {
549
+ return `${pathWithoutExtension}.jsx`;
550
+ }
551
+ if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.mjs`)) {
552
+ return `${pathWithoutExtension}.mjs`;
553
+ }
554
+ if ((0, import_node_fs4.existsSync)(`${pathWithoutExtension}.cjs`)) {
555
+ return `${pathWithoutExtension}.cjs`;
556
+ }
1144
557
  };
1145
- var createDependencyGraph = function() {
1146
- var _ref = _async_to_generator(function(directory) {
1147
- var filePaths, modulePaths, graph, getDependencyPaths, updateModuleDependenciesInGraph, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, filePath, err, removeModuleFromGraph;
1148
- return _ts_generator(this, function(_state) {
1149
- switch(_state.label){
1150
- case 0:
1151
- return [
1152
- 4,
1153
- readAllFilesInsideDirectory(directory)
1154
- ];
1155
- case 1:
1156
- filePaths = _state.sent();
1157
- modulePaths = filePaths.filter(isJavascriptModule);
1158
- graph = Object.fromEntries(modulePaths.map(function(path12) {
1159
- return [
1160
- path12,
1161
- {
1162
- path: path12,
1163
- dependencyPaths: [],
1164
- dependentPaths: [],
1165
- moduleDependencies: []
1166
- }
1167
- ];
1168
- }));
1169
- getDependencyPaths = function() {
1170
- var _ref = _async_to_generator(function(filePath) {
1171
- var contents, importedPaths, importedPathsRelativeToDirectory, moduleDependencies, nonNodeModuleImportPathsRelativeToDirectory;
1172
- return _ts_generator(this, function(_state) {
1173
- switch(_state.label){
1174
- case 0:
1175
- return [
1176
- 4,
1177
- import_node_fs4.promises.readFile(filePath, "utf8")
1178
- ];
1179
- case 1:
1180
- contents = _state.sent();
1181
- importedPaths = getImportedModules(contents);
1182
- importedPathsRelativeToDirectory = importedPaths.map(function(dependencyPath) {
1183
- var isModulePath = !dependencyPath.startsWith(".");
1184
- if (isModulePath || import_node_path6.default.isAbsolute(dependencyPath)) {
1185
- return dependencyPath;
1186
- }
1187
- var pathToDependencyFromDirectory = import_node_path6.default.resolve(/*
558
+ var createDependencyGraph = async (directory) => {
559
+ const filePaths = await readAllFilesInsideDirectory(directory);
560
+ const modulePaths = filePaths.filter(isJavascriptModule);
561
+ const graph = Object.fromEntries(
562
+ modulePaths.map((path12) => [
563
+ path12,
564
+ {
565
+ path: path12,
566
+ dependencyPaths: [],
567
+ dependentPaths: [],
568
+ moduleDependencies: []
569
+ }
570
+ ])
571
+ );
572
+ const getDependencyPaths = async (filePath) => {
573
+ const contents = await import_node_fs4.promises.readFile(filePath, "utf8");
574
+ const importedPaths = getImportedModules(contents);
575
+ const importedPathsRelativeToDirectory = importedPaths.map(
576
+ (dependencyPath) => {
577
+ const isModulePath = !dependencyPath.startsWith(".");
578
+ if (isModulePath || import_node_path6.default.isAbsolute(dependencyPath)) {
579
+ return dependencyPath;
580
+ }
581
+ let pathToDependencyFromDirectory = import_node_path6.default.resolve(
582
+ /*
1188
583
  path.resolve resolves paths differently from what imports on javascript do.
1189
584
 
1190
585
  So if we wouldn't do this, for an email at "/path/to/email.tsx" with a dependecy path of "./other-email"
1191
586
  would end up going into /path/to/email.tsx/other-email instead of /path/to/other-email which is the
1192
587
  one the import is meant to go to
1193
- */ import_node_path6.default.dirname(filePath), dependencyPath);
1194
- var isDirectory = false;
1195
- try {
1196
- isDirectory = (0, import_node_fs4.statSync)(pathToDependencyFromDirectory).isDirectory();
1197
- } catch (_) {}
1198
- if (isDirectory) {
1199
- var pathToSubDirectory = pathToDependencyFromDirectory;
1200
- var pathWithExtension = checkFileExtensionsUntilItExists("".concat(pathToSubDirectory, "/index"));
1201
- if (pathWithExtension) {
1202
- pathToDependencyFromDirectory = pathWithExtension;
1203
- } else if (isDev) {
1204
- console.warn("Could not find index file for directory at ".concat(pathToDependencyFromDirectory, ". This is probably going to cause issues with both hot reloading and your code."));
1205
- }
1206
- }
1207
- if (!isJavascriptModule(pathToDependencyFromDirectory)) {
1208
- var pathWithExtension1 = checkFileExtensionsUntilItExists(pathToDependencyFromDirectory);
1209
- if (pathWithExtension1) {
1210
- pathToDependencyFromDirectory = pathWithExtension1;
1211
- } else if (isDev) {
1212
- console.warn("Could not determine the file extension for the file at ".concat(pathToDependencyFromDirectory));
1213
- }
1214
- }
1215
- return pathToDependencyFromDirectory;
1216
- });
1217
- moduleDependencies = importedPathsRelativeToDirectory.filter(function(dependencyPath) {
1218
- return !dependencyPath.startsWith(".") && !import_node_path6.default.isAbsolute(dependencyPath);
1219
- });
1220
- nonNodeModuleImportPathsRelativeToDirectory = importedPathsRelativeToDirectory.filter(function(dependencyPath) {
1221
- return dependencyPath.startsWith(".") || import_node_path6.default.isAbsolute(dependencyPath);
1222
- });
1223
- return [
1224
- 2,
1225
- {
1226
- dependencyPaths: nonNodeModuleImportPathsRelativeToDirectory,
1227
- moduleDependencies: moduleDependencies
1228
- }
1229
- ];
1230
- }
1231
- });
1232
- });
1233
- return function getDependencyPaths(filePath) {
1234
- return _ref.apply(this, arguments);
1235
- };
1236
- }();
1237
- updateModuleDependenciesInGraph = function() {
1238
- var _ref = _async_to_generator(function(moduleFilePath) {
1239
- var _graph_moduleFilePath, module2, _ref, moduleDependencies, newDependencyPaths, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, dependencyPath, dependencyModule, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, dependencyPath1, dependencyModule1;
1240
- return _ts_generator(this, function(_state) {
1241
- switch(_state.label){
1242
- case 0:
1243
- module2 = (_graph_moduleFilePath = graph[moduleFilePath]) !== null && _graph_moduleFilePath !== void 0 ? _graph_moduleFilePath : {
1244
- path: moduleFilePath,
1245
- dependencyPaths: [],
1246
- dependentPaths: [],
1247
- moduleDependencies: []
1248
- };
1249
- return [
1250
- 4,
1251
- getDependencyPaths(moduleFilePath)
1252
- ];
1253
- case 1:
1254
- _ref = _state.sent(), moduleDependencies = _ref.moduleDependencies, newDependencyPaths = _ref.dependencyPaths;
1255
- module2.moduleDependencies = moduleDependencies;
1256
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1257
- try {
1258
- for(_iterator = module2.dependencyPaths[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1259
- dependencyPath = _step.value;
1260
- if (newDependencyPaths.includes(dependencyPath)) continue;
1261
- dependencyModule = graph[dependencyPath];
1262
- if (dependencyModule !== void 0) {
1263
- dependencyModule.dependentPaths = dependencyModule.dependentPaths.filter(function(dependentPath) {
1264
- return dependentPath !== moduleFilePath;
1265
- });
1266
- }
1267
- }
1268
- } catch (err) {
1269
- _didIteratorError = true;
1270
- _iteratorError = err;
1271
- } finally{
1272
- try {
1273
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1274
- _iterator.return();
1275
- }
1276
- } finally{
1277
- if (_didIteratorError) {
1278
- throw _iteratorError;
1279
- }
1280
- }
1281
- }
1282
- module2.dependencyPaths = newDependencyPaths;
1283
- _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1284
- try {
1285
- for(_iterator1 = newDependencyPaths[Symbol.iterator](); !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1286
- dependencyPath1 = _step1.value;
1287
- dependencyModule1 = graph[dependencyPath1];
1288
- if (dependencyModule1 !== void 0 && !dependencyModule1.dependentPaths.includes(moduleFilePath)) {
1289
- dependencyModule1.dependentPaths.push(moduleFilePath);
1290
- } else {
1291
- graph[dependencyPath1] = {
1292
- path: dependencyPath1,
1293
- moduleDependencies: [],
1294
- dependencyPaths: [],
1295
- dependentPaths: [
1296
- moduleFilePath
1297
- ]
1298
- };
1299
- }
1300
- }
1301
- } catch (err) {
1302
- _didIteratorError1 = true;
1303
- _iteratorError1 = err;
1304
- } finally{
1305
- try {
1306
- if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1307
- _iterator1.return();
1308
- }
1309
- } finally{
1310
- if (_didIteratorError1) {
1311
- throw _iteratorError1;
1312
- }
1313
- }
1314
- }
1315
- graph[moduleFilePath] = module2;
1316
- return [
1317
- 2
1318
- ];
1319
- }
1320
- });
1321
- });
1322
- return function updateModuleDependenciesInGraph(moduleFilePath) {
1323
- return _ref.apply(this, arguments);
1324
- };
1325
- }();
1326
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1327
- _state.label = 2;
1328
- case 2:
1329
- _state.trys.push([
1330
- 2,
1331
- 7,
1332
- 8,
1333
- 9
1334
- ]);
1335
- _iterator = modulePaths[Symbol.iterator]();
1336
- _state.label = 3;
1337
- case 3:
1338
- if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
1339
- 3,
1340
- 6
1341
- ];
1342
- filePath = _step.value;
1343
- return [
1344
- 4,
1345
- updateModuleDependenciesInGraph(filePath)
1346
- ];
1347
- case 4:
1348
- _state.sent();
1349
- _state.label = 5;
1350
- case 5:
1351
- _iteratorNormalCompletion = true;
1352
- return [
1353
- 3,
1354
- 3
1355
- ];
1356
- case 6:
1357
- return [
1358
- 3,
1359
- 9
1360
- ];
1361
- case 7:
1362
- err = _state.sent();
1363
- _didIteratorError = true;
1364
- _iteratorError = err;
1365
- return [
1366
- 3,
1367
- 9
1368
- ];
1369
- case 8:
1370
- try {
1371
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1372
- _iterator.return();
1373
- }
1374
- } finally{
1375
- if (_didIteratorError) {
1376
- throw _iteratorError;
1377
- }
1378
- }
1379
- return [
1380
- 7
1381
- ];
1382
- case 9:
1383
- removeModuleFromGraph = function(filePath) {
1384
- var module2 = graph[filePath];
1385
- if (module2) {
1386
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1387
- try {
1388
- for(var _iterator = module2.dependencyPaths[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1389
- var dependencyPath = _step.value;
1390
- if (graph[dependencyPath]) {
1391
- graph[dependencyPath].dependentPaths = graph[dependencyPath].dependentPaths.filter(function(dependentPath) {
1392
- return dependentPath !== filePath;
1393
- });
1394
- }
1395
- }
1396
- } catch (err) {
1397
- _didIteratorError = true;
1398
- _iteratorError = err;
1399
- } finally{
1400
- try {
1401
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1402
- _iterator.return();
1403
- }
1404
- } finally{
1405
- if (_didIteratorError) {
1406
- throw _iteratorError;
1407
- }
1408
- }
1409
- }
1410
- delete graph[filePath];
1411
- }
1412
- };
1413
- return [
1414
- 2,
1415
- [
1416
- graph,
1417
- function() {
1418
- var _ref = _async_to_generator(function(event, pathToModified) {
1419
- var filesInsideAddedDirectory, modulesInsideAddedDirectory, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, filePath, err, filesInsideDeletedDirectory, modulesInsideDeletedDirectory, _iteratorAbruptCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, _value1, filePath1, err1;
1420
- return _ts_generator(this, function(_state) {
1421
- switch(_state.label){
1422
- case 0:
1423
- switch(event){
1424
- case "change":
1425
- return [
1426
- 3,
1427
- 1
1428
- ];
1429
- case "add":
1430
- return [
1431
- 3,
1432
- 4
1433
- ];
1434
- case "addDir":
1435
- return [
1436
- 3,
1437
- 7
1438
- ];
1439
- case "unlink":
1440
- return [
1441
- 3,
1442
- 22
1443
- ];
1444
- case "unlinkDir":
1445
- return [
1446
- 3,
1447
- 23
1448
- ];
1449
- }
1450
- return [
1451
- 3,
1452
- 37
1453
- ];
1454
- case 1:
1455
- if (!isJavascriptModule(pathToModified)) return [
1456
- 3,
1457
- 3
1458
- ];
1459
- return [
1460
- 4,
1461
- updateModuleDependenciesInGraph(pathToModified)
1462
- ];
1463
- case 2:
1464
- _state.sent();
1465
- _state.label = 3;
1466
- case 3:
1467
- return [
1468
- 3,
1469
- 37
1470
- ];
1471
- case 4:
1472
- if (!isJavascriptModule(pathToModified)) return [
1473
- 3,
1474
- 6
1475
- ];
1476
- return [
1477
- 4,
1478
- updateModuleDependenciesInGraph(pathToModified)
1479
- ];
1480
- case 5:
1481
- _state.sent();
1482
- _state.label = 6;
1483
- case 6:
1484
- return [
1485
- 3,
1486
- 37
1487
- ];
1488
- case 7:
1489
- return [
1490
- 4,
1491
- readAllFilesInsideDirectory(pathToModified)
1492
- ];
1493
- case 8:
1494
- filesInsideAddedDirectory = _state.sent();
1495
- modulesInsideAddedDirectory = filesInsideAddedDirectory.filter(isJavascriptModule);
1496
- _iteratorAbruptCompletion = false, _didIteratorError = false;
1497
- _state.label = 9;
1498
- case 9:
1499
- _state.trys.push([
1500
- 9,
1501
- 15,
1502
- 16,
1503
- 21
1504
- ]);
1505
- _iterator = _async_iterator(modulesInsideAddedDirectory);
1506
- _state.label = 10;
1507
- case 10:
1508
- return [
1509
- 4,
1510
- _iterator.next()
1511
- ];
1512
- case 11:
1513
- if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
1514
- 3,
1515
- 14
1516
- ];
1517
- _value = _step.value;
1518
- filePath = _value;
1519
- return [
1520
- 4,
1521
- updateModuleDependenciesInGraph(filePath)
1522
- ];
1523
- case 12:
1524
- _state.sent();
1525
- _state.label = 13;
1526
- case 13:
1527
- _iteratorAbruptCompletion = false;
1528
- return [
1529
- 3,
1530
- 10
1531
- ];
1532
- case 14:
1533
- return [
1534
- 3,
1535
- 21
1536
- ];
1537
- case 15:
1538
- err = _state.sent();
1539
- _didIteratorError = true;
1540
- _iteratorError = err;
1541
- return [
1542
- 3,
1543
- 21
1544
- ];
1545
- case 16:
1546
- _state.trys.push([
1547
- 16,
1548
- ,
1549
- 19,
1550
- 20
1551
- ]);
1552
- if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
1553
- 3,
1554
- 18
1555
- ];
1556
- return [
1557
- 4,
1558
- _iterator.return()
1559
- ];
1560
- case 17:
1561
- _state.sent();
1562
- _state.label = 18;
1563
- case 18:
1564
- return [
1565
- 3,
1566
- 20
1567
- ];
1568
- case 19:
1569
- if (_didIteratorError) {
1570
- throw _iteratorError;
1571
- }
1572
- return [
1573
- 7
1574
- ];
1575
- case 20:
1576
- return [
1577
- 7
1578
- ];
1579
- case 21:
1580
- return [
1581
- 3,
1582
- 37
1583
- ];
1584
- case 22:
1585
- if (isJavascriptModule(pathToModified)) {
1586
- removeModuleFromGraph(pathToModified);
1587
- }
1588
- return [
1589
- 3,
1590
- 37
1591
- ];
1592
- case 23:
1593
- return [
1594
- 4,
1595
- readAllFilesInsideDirectory(pathToModified)
1596
- ];
1597
- case 24:
1598
- filesInsideDeletedDirectory = _state.sent();
1599
- modulesInsideDeletedDirectory = filesInsideDeletedDirectory.filter(isJavascriptModule);
1600
- _iteratorAbruptCompletion1 = false, _didIteratorError1 = false;
1601
- _state.label = 25;
1602
- case 25:
1603
- _state.trys.push([
1604
- 25,
1605
- 30,
1606
- 31,
1607
- 36
1608
- ]);
1609
- _iterator1 = _async_iterator(modulesInsideDeletedDirectory);
1610
- _state.label = 26;
1611
- case 26:
1612
- return [
1613
- 4,
1614
- _iterator1.next()
1615
- ];
1616
- case 27:
1617
- if (!(_iteratorAbruptCompletion1 = !(_step1 = _state.sent()).done)) return [
1618
- 3,
1619
- 29
1620
- ];
1621
- _value1 = _step1.value;
1622
- filePath1 = _value1;
1623
- removeModuleFromGraph(filePath1);
1624
- _state.label = 28;
1625
- case 28:
1626
- _iteratorAbruptCompletion1 = false;
1627
- return [
1628
- 3,
1629
- 26
1630
- ];
1631
- case 29:
1632
- return [
1633
- 3,
1634
- 36
1635
- ];
1636
- case 30:
1637
- err1 = _state.sent();
1638
- _didIteratorError1 = true;
1639
- _iteratorError1 = err1;
1640
- return [
1641
- 3,
1642
- 36
1643
- ];
1644
- case 31:
1645
- _state.trys.push([
1646
- 31,
1647
- ,
1648
- 34,
1649
- 35
1650
- ]);
1651
- if (!(_iteratorAbruptCompletion1 && _iterator1.return != null)) return [
1652
- 3,
1653
- 33
1654
- ];
1655
- return [
1656
- 4,
1657
- _iterator1.return()
1658
- ];
1659
- case 32:
1660
- _state.sent();
1661
- _state.label = 33;
1662
- case 33:
1663
- return [
1664
- 3,
1665
- 35
1666
- ];
1667
- case 34:
1668
- if (_didIteratorError1) {
1669
- throw _iteratorError1;
1670
- }
1671
- return [
1672
- 7
1673
- ];
1674
- case 35:
1675
- return [
1676
- 7
1677
- ];
1678
- case 36:
1679
- return [
1680
- 3,
1681
- 37
1682
- ];
1683
- case 37:
1684
- return [
1685
- 2
1686
- ];
1687
- }
1688
- });
1689
- });
1690
- return function(event, pathToModified) {
1691
- return _ref.apply(this, arguments);
1692
- };
1693
- }(),
1694
- {
1695
- resolveDependentsOf: function resolveDependentsOf(pathToModule) {
1696
- var moduleEntry = graph[pathToModule];
1697
- var dependentPaths = [];
1698
- if (moduleEntry) {
1699
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1700
- try {
1701
- for(var _iterator = moduleEntry.dependentPaths[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1702
- var dependentPath = _step.value;
1703
- var _dependentPaths;
1704
- var dependentsOfDependent = resolveDependentsOf(dependentPath);
1705
- (_dependentPaths = dependentPaths).push.apply(_dependentPaths, _to_consumable_array(dependentsOfDependent));
1706
- dependentPaths.push(dependentPath);
1707
- }
1708
- } catch (err) {
1709
- _didIteratorError = true;
1710
- _iteratorError = err;
1711
- } finally{
1712
- try {
1713
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1714
- _iterator.return();
1715
- }
1716
- } finally{
1717
- if (_didIteratorError) {
1718
- throw _iteratorError;
1719
- }
1720
- }
1721
- }
1722
- }
1723
- return dependentPaths;
1724
- }
1725
- }
1726
- ]
1727
- ];
1728
- }
1729
- });
1730
- });
1731
- return function createDependencyGraph(directory) {
1732
- return _ref.apply(this, arguments);
588
+ */
589
+ import_node_path6.default.dirname(filePath),
590
+ dependencyPath
591
+ );
592
+ let isDirectory = false;
593
+ try {
594
+ isDirectory = (0, import_node_fs4.statSync)(pathToDependencyFromDirectory).isDirectory();
595
+ } catch (_) {
596
+ }
597
+ if (isDirectory) {
598
+ const pathToSubDirectory = pathToDependencyFromDirectory;
599
+ const pathWithExtension = checkFileExtensionsUntilItExists(
600
+ `${pathToSubDirectory}/index`
601
+ );
602
+ if (pathWithExtension) {
603
+ pathToDependencyFromDirectory = pathWithExtension;
604
+ } else if (isDev) {
605
+ console.warn(
606
+ `Could not find index file for directory at ${pathToDependencyFromDirectory}. This is probably going to cause issues with both hot reloading and your code.`
607
+ );
608
+ }
609
+ }
610
+ if (!isJavascriptModule(pathToDependencyFromDirectory)) {
611
+ const pathWithExtension = checkFileExtensionsUntilItExists(
612
+ pathToDependencyFromDirectory
613
+ );
614
+ if (pathWithExtension) {
615
+ pathToDependencyFromDirectory = pathWithExtension;
616
+ } else if (isDev) {
617
+ console.warn(
618
+ `Could not determine the file extension for the file at ${pathToDependencyFromDirectory}`
619
+ );
620
+ }
621
+ }
622
+ return pathToDependencyFromDirectory;
623
+ }
624
+ );
625
+ const moduleDependencies = importedPathsRelativeToDirectory.filter(
626
+ (dependencyPath) => !dependencyPath.startsWith(".") && !import_node_path6.default.isAbsolute(dependencyPath)
627
+ );
628
+ const nonNodeModuleImportPathsRelativeToDirectory = importedPathsRelativeToDirectory.filter(
629
+ (dependencyPath) => dependencyPath.startsWith(".") || import_node_path6.default.isAbsolute(dependencyPath)
630
+ );
631
+ return {
632
+ dependencyPaths: nonNodeModuleImportPathsRelativeToDirectory,
633
+ moduleDependencies
1733
634
  };
1734
- }();
1735
- // src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
1736
- var setupHotreloading = function() {
1737
- var _ref = _async_to_generator(function(devServer2, emailDirRelativePath) {
1738
- var clients, io, changes, reload, absolutePathToEmailsDirectory, _ref, dependencyGraph, updateDependencyGraph, resolveDependentsOf, watcher, getFilesOutsideEmailsDirectory, filesOutsideEmailsDirectory, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, p, exit;
1739
- return _ts_generator(this, function(_state) {
1740
- switch(_state.label){
1741
- case 0:
1742
- clients = [];
1743
- io = new import_socket.Server(devServer2);
1744
- io.on("connection", function(client) {
1745
- clients.push(client);
1746
- client.on("disconnect", function() {
1747
- clients = clients.filter(function(item) {
1748
- return item !== client;
1749
- });
1750
- });
1751
- });
1752
- changes = [];
1753
- reload = (0, import_debounce.default)(function() {
1754
- clients.forEach(function(client) {
1755
- client.emit("reload", changes);
1756
- });
1757
- changes = [];
1758
- }, 150);
1759
- absolutePathToEmailsDirectory = import_node_path7.default.resolve(process.cwd(), emailDirRelativePath);
1760
- return [
1761
- 4,
1762
- createDependencyGraph(absolutePathToEmailsDirectory)
1763
- ];
1764
- case 1:
1765
- _ref = _sliced_to_array.apply(void 0, [
1766
- _state.sent(),
1767
- 3
1768
- ]), dependencyGraph = _ref[0], updateDependencyGraph = _ref[1], resolveDependentsOf = _ref[2].resolveDependentsOf;
1769
- watcher = (0, import_chokidar.watch)("", {
1770
- ignoreInitial: true,
1771
- cwd: absolutePathToEmailsDirectory
1772
- });
1773
- getFilesOutsideEmailsDirectory = function() {
1774
- return Object.keys(dependencyGraph).filter(function(p) {
1775
- return import_node_path7.default.relative(absolutePathToEmailsDirectory, p).startsWith("..");
1776
- });
1777
- };
1778
- filesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
1779
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1780
- try {
1781
- for(_iterator = filesOutsideEmailsDirectory[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1782
- p = _step.value;
1783
- watcher.add(p);
1784
- }
1785
- } catch (err) {
1786
- _didIteratorError = true;
1787
- _iteratorError = err;
1788
- } finally{
1789
- try {
1790
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1791
- _iterator.return();
1792
- }
1793
- } finally{
1794
- if (_didIteratorError) {
1795
- throw _iteratorError;
1796
- }
1797
- }
1798
- }
1799
- exit = function() {
1800
- var _ref = _async_to_generator(function() {
1801
- return _ts_generator(this, function(_state) {
1802
- switch(_state.label){
1803
- case 0:
1804
- return [
1805
- 4,
1806
- watcher.close()
1807
- ];
1808
- case 1:
1809
- _state.sent();
1810
- return [
1811
- 2
1812
- ];
1813
- }
1814
- });
1815
- });
1816
- return function exit() {
1817
- return _ref.apply(this, arguments);
1818
- };
1819
- }();
1820
- process.on("SIGINT", exit);
1821
- process.on("uncaughtException", exit);
1822
- watcher.on("all", function() {
1823
- var _ref = _async_to_generator(function(event, relativePathToChangeTarget) {
1824
- var file, pathToChangeTarget, newFilesOutsideEmailsDirectory, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, p, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, p1, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, dependentPath;
1825
- return _ts_generator(this, function(_state) {
1826
- switch(_state.label){
1827
- case 0:
1828
- file = relativePathToChangeTarget.split(import_node_path7.default.sep);
1829
- if (file.length === 0) {
1830
- return [
1831
- 2
1832
- ];
1833
- }
1834
- pathToChangeTarget = import_node_path7.default.resolve(absolutePathToEmailsDirectory, relativePathToChangeTarget);
1835
- return [
1836
- 4,
1837
- updateDependencyGraph(event, pathToChangeTarget)
1838
- ];
1839
- case 1:
1840
- _state.sent();
1841
- newFilesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
1842
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1843
- try {
1844
- for(_iterator = filesOutsideEmailsDirectory[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1845
- p = _step.value;
1846
- if (!newFilesOutsideEmailsDirectory.includes(p)) {
1847
- watcher.unwatch(p);
1848
- }
1849
- }
1850
- } catch (err) {
1851
- _didIteratorError = true;
1852
- _iteratorError = err;
1853
- } finally{
1854
- try {
1855
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1856
- _iterator.return();
1857
- }
1858
- } finally{
1859
- if (_didIteratorError) {
1860
- throw _iteratorError;
1861
- }
1862
- }
1863
- }
1864
- _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1865
- try {
1866
- for(_iterator1 = newFilesOutsideEmailsDirectory[Symbol.iterator](); !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1867
- p1 = _step1.value;
1868
- if (!filesOutsideEmailsDirectory.includes(p1)) {
1869
- watcher.add(p1);
1870
- }
1871
- }
1872
- } catch (err) {
1873
- _didIteratorError1 = true;
1874
- _iteratorError1 = err;
1875
- } finally{
1876
- try {
1877
- if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1878
- _iterator1.return();
1879
- }
1880
- } finally{
1881
- if (_didIteratorError1) {
1882
- throw _iteratorError1;
1883
- }
1884
- }
1885
- }
1886
- filesOutsideEmailsDirectory = newFilesOutsideEmailsDirectory;
1887
- changes.push({
1888
- event: event,
1889
- filename: relativePathToChangeTarget
1890
- });
1891
- _iteratorNormalCompletion2 = true, _didIteratorError2 = false, _iteratorError2 = undefined;
1892
- try {
1893
- for(_iterator2 = resolveDependentsOf(pathToChangeTarget)[Symbol.iterator](); !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true){
1894
- dependentPath = _step2.value;
1895
- changes.push({
1896
- event: "change",
1897
- filename: import_node_path7.default.relative(absolutePathToEmailsDirectory, dependentPath)
1898
- });
1899
- }
1900
- } catch (err) {
1901
- _didIteratorError2 = true;
1902
- _iteratorError2 = err;
1903
- } finally{
1904
- try {
1905
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
1906
- _iterator2.return();
1907
- }
1908
- } finally{
1909
- if (_didIteratorError2) {
1910
- throw _iteratorError2;
1911
- }
1912
- }
1913
- }
1914
- reload();
1915
- return [
1916
- 2
1917
- ];
1918
- }
1919
- });
1920
- });
1921
- return function(event, relativePathToChangeTarget) {
1922
- return _ref.apply(this, arguments);
1923
- };
1924
- }());
1925
- return [
1926
- 2,
1927
- watcher
1928
- ];
1929
- }
1930
- });
1931
- });
1932
- return function setupHotreloading(devServer2, emailDirRelativePath) {
1933
- return _ref.apply(this, arguments);
635
+ };
636
+ const updateModuleDependenciesInGraph = async (moduleFilePath) => {
637
+ const module2 = graph[moduleFilePath] ?? {
638
+ path: moduleFilePath,
639
+ dependencyPaths: [],
640
+ dependentPaths: [],
641
+ moduleDependencies: []
1934
642
  };
1935
- }();
1936
- // src/cli/commands/build.ts
1937
- var buildPreviewApp = function(absoluteDirectory) {
1938
- return new Promise(function(resolve, reject) {
1939
- var nextBuild = (0, import_node_child_process.spawn)("npm", [
1940
- "run",
1941
- "build"
1942
- ], {
1943
- cwd: absoluteDirectory,
1944
- shell: true
1945
- });
1946
- nextBuild.stdout.pipe(process.stdout);
1947
- nextBuild.stderr.pipe(process.stderr);
1948
- nextBuild.on("close", function(code) {
1949
- if (code === 0) {
1950
- resolve();
1951
- } else {
1952
- reject(new Error("Unable to build the Next app and it exited with code: ".concat(code)));
1953
- }
1954
- });
1955
- });
643
+ const { moduleDependencies, dependencyPaths: newDependencyPaths } = await getDependencyPaths(moduleFilePath);
644
+ module2.moduleDependencies = moduleDependencies;
645
+ for (const dependencyPath of module2.dependencyPaths) {
646
+ if (newDependencyPaths.includes(dependencyPath))
647
+ continue;
648
+ const dependencyModule = graph[dependencyPath];
649
+ if (dependencyModule !== void 0) {
650
+ dependencyModule.dependentPaths = dependencyModule.dependentPaths.filter(
651
+ (dependentPath) => dependentPath !== moduleFilePath
652
+ );
653
+ }
654
+ }
655
+ module2.dependencyPaths = newDependencyPaths;
656
+ for (const dependencyPath of newDependencyPaths) {
657
+ const dependencyModule = graph[dependencyPath];
658
+ if (dependencyModule !== void 0 && !dependencyModule.dependentPaths.includes(moduleFilePath)) {
659
+ dependencyModule.dependentPaths.push(moduleFilePath);
660
+ } else {
661
+ graph[dependencyPath] = {
662
+ path: dependencyPath,
663
+ moduleDependencies: [],
664
+ dependencyPaths: [],
665
+ dependentPaths: [moduleFilePath]
666
+ };
667
+ }
668
+ }
669
+ graph[moduleFilePath] = module2;
670
+ };
671
+ for (const filePath of modulePaths) {
672
+ await updateModuleDependenciesInGraph(filePath);
673
+ }
674
+ const removeModuleFromGraph = (filePath) => {
675
+ const module2 = graph[filePath];
676
+ if (module2) {
677
+ for (const dependencyPath of module2.dependencyPaths) {
678
+ if (graph[dependencyPath]) {
679
+ graph[dependencyPath].dependentPaths = graph[dependencyPath].dependentPaths.filter(
680
+ (dependentPath) => dependentPath !== filePath
681
+ );
682
+ }
683
+ }
684
+ delete graph[filePath];
685
+ }
686
+ };
687
+ return [
688
+ graph,
689
+ async (event, pathToModified) => {
690
+ switch (event) {
691
+ case "change":
692
+ if (isJavascriptModule(pathToModified)) {
693
+ await updateModuleDependenciesInGraph(pathToModified);
694
+ }
695
+ break;
696
+ case "add":
697
+ if (isJavascriptModule(pathToModified)) {
698
+ await updateModuleDependenciesInGraph(pathToModified);
699
+ }
700
+ break;
701
+ case "addDir": {
702
+ const filesInsideAddedDirectory = await readAllFilesInsideDirectory(pathToModified);
703
+ const modulesInsideAddedDirectory = filesInsideAddedDirectory.filter(isJavascriptModule);
704
+ for await (const filePath of modulesInsideAddedDirectory) {
705
+ await updateModuleDependenciesInGraph(filePath);
706
+ }
707
+ break;
708
+ }
709
+ case "unlink":
710
+ if (isJavascriptModule(pathToModified)) {
711
+ removeModuleFromGraph(pathToModified);
712
+ }
713
+ break;
714
+ case "unlinkDir": {
715
+ const filesInsideDeletedDirectory = await readAllFilesInsideDirectory(pathToModified);
716
+ const modulesInsideDeletedDirectory = filesInsideDeletedDirectory.filter(isJavascriptModule);
717
+ for await (const filePath of modulesInsideDeletedDirectory) {
718
+ removeModuleFromGraph(filePath);
719
+ }
720
+ break;
721
+ }
722
+ }
723
+ },
724
+ {
725
+ resolveDependentsOf: function resolveDependentsOf(pathToModule) {
726
+ const moduleEntry = graph[pathToModule];
727
+ const dependentPaths = [];
728
+ if (moduleEntry) {
729
+ for (const dependentPath of moduleEntry.dependentPaths) {
730
+ const dependentsOfDependent = resolveDependentsOf(dependentPath);
731
+ dependentPaths.push(...dependentsOfDependent);
732
+ dependentPaths.push(dependentPath);
733
+ }
734
+ }
735
+ return dependentPaths;
736
+ }
737
+ }
738
+ ];
1956
739
  };
1957
- var setNextEnvironmentVariablesForBuild = function() {
1958
- var _ref = _async_to_generator(function(emailsDirRelativePath, builtPreviewAppPath) {
1959
- var nextConfigContents;
1960
- return _ts_generator(this, function(_state) {
1961
- switch(_state.label){
1962
- case 0:
1963
- nextConfigContents = "\nconst path = require('path');\nconst emailsDirRelativePath = path.normalize('".concat(emailsDirRelativePath, "');\nconst userProjectLocation = path.resolve(process.cwd(), '../');\n/** @type {import('next').NextConfig} */\nmodule.exports = {\n env: {\n NEXT_PUBLIC_IS_BUILDING: 'true',\n EMAILS_DIR_RELATIVE_PATH: emailsDirRelativePath,\n EMAILS_DIR_ABSOLUTE_PATH: path.resolve(userProjectLocation, emailsDirRelativePath),\n USER_PROJECT_LOCATION: userProjectLocation\n },\n // this is needed so that the code for building emails works properly\n webpack: (\n /** @type {import('webpack').Configuration & { externals: string[] }} */\n config,\n { isServer }\n ) => {\n if (isServer) {\n config.externals.push('esbuild');\n }\n\n return config;\n },\n typescript: {\n ignoreBuildErrors: true\n },\n eslint: {\n ignoreDuringBuilds: true\n },\n experimental: {\n webpackBuildWorker: true\n },\n}");
1964
- return [
1965
- 4,
1966
- import_node_fs5.default.promises.writeFile(import_node_path8.default.resolve(builtPreviewAppPath, "./next.config.js"), nextConfigContents, "utf8")
1967
- ];
1968
- case 1:
1969
- _state.sent();
1970
- return [
1971
- 2
1972
- ];
1973
- }
1974
- });
740
+
741
+ // src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
742
+ var setupHotreloading = async (devServer2, emailDirRelativePath) => {
743
+ let clients = [];
744
+ const io = new import_socket.Server(devServer2);
745
+ io.on("connection", (client) => {
746
+ clients.push(client);
747
+ client.on("disconnect", () => {
748
+ clients = clients.filter((item) => item !== client);
1975
749
  });
1976
- return function setNextEnvironmentVariablesForBuild(emailsDirRelativePath, builtPreviewAppPath) {
1977
- return _ref.apply(this, arguments);
1978
- };
1979
- }();
1980
- var getEmailSlugsFromEmailDirectory = function(emailDirectory, emailsDirectoryAbsolutePath) {
1981
- var directoryPathRelativeToEmailsDirectory = emailDirectory.absolutePath.replace(emailsDirectoryAbsolutePath, "").trim();
1982
- var slugs = [];
1983
- emailDirectory.emailFilenames.forEach(function(filename) {
1984
- return slugs.push(import_node_path8.default.join(directoryPathRelativeToEmailsDirectory, filename).split(import_node_path8.default.sep).filter(function(segment) {
1985
- return segment.length > 0;
1986
- }));
750
+ });
751
+ let changes = [];
752
+ const reload = (0, import_debounce.default)(() => {
753
+ clients.forEach((client) => {
754
+ client.emit("reload", changes);
1987
755
  });
1988
- emailDirectory.subDirectories.forEach(function(directory) {
1989
- var _slugs;
1990
- (_slugs = slugs).push.apply(_slugs, _to_consumable_array(getEmailSlugsFromEmailDirectory(directory, emailsDirectoryAbsolutePath)));
756
+ changes = [];
757
+ }, 150);
758
+ const absolutePathToEmailsDirectory = import_node_path7.default.resolve(
759
+ process.cwd(),
760
+ emailDirRelativePath
761
+ );
762
+ const [dependencyGraph, updateDependencyGraph, { resolveDependentsOf }] = await createDependencyGraph(absolutePathToEmailsDirectory);
763
+ const watcher = (0, import_chokidar.watch)("", {
764
+ ignoreInitial: true,
765
+ cwd: absolutePathToEmailsDirectory
766
+ });
767
+ const getFilesOutsideEmailsDirectory = () => Object.keys(dependencyGraph).filter(
768
+ (p) => import_node_path7.default.relative(absolutePathToEmailsDirectory, p).startsWith("..")
769
+ );
770
+ let filesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
771
+ for (const p of filesOutsideEmailsDirectory) {
772
+ watcher.add(p);
773
+ }
774
+ const exit = async () => {
775
+ await watcher.close();
776
+ };
777
+ process.on("SIGINT", exit);
778
+ process.on("uncaughtException", exit);
779
+ watcher.on("all", async (event, relativePathToChangeTarget) => {
780
+ const file = relativePathToChangeTarget.split(import_node_path7.default.sep);
781
+ if (file.length === 0) {
782
+ return;
783
+ }
784
+ const pathToChangeTarget = import_node_path7.default.resolve(
785
+ absolutePathToEmailsDirectory,
786
+ relativePathToChangeTarget
787
+ );
788
+ await updateDependencyGraph(event, pathToChangeTarget);
789
+ const newFilesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
790
+ for (const p of filesOutsideEmailsDirectory) {
791
+ if (!newFilesOutsideEmailsDirectory.includes(p)) {
792
+ watcher.unwatch(p);
793
+ }
794
+ }
795
+ for (const p of newFilesOutsideEmailsDirectory) {
796
+ if (!filesOutsideEmailsDirectory.includes(p)) {
797
+ watcher.add(p);
798
+ }
799
+ }
800
+ filesOutsideEmailsDirectory = newFilesOutsideEmailsDirectory;
801
+ changes.push({
802
+ event,
803
+ filename: relativePathToChangeTarget
1991
804
  });
1992
- return slugs;
805
+ for (const dependentPath of resolveDependentsOf(pathToChangeTarget)) {
806
+ changes.push({
807
+ event: "change",
808
+ filename: import_node_path7.default.relative(absolutePathToEmailsDirectory, dependentPath)
809
+ });
810
+ }
811
+ reload();
812
+ });
813
+ return watcher;
1993
814
  };
1994
- var forceSSGForEmailPreviews = function() {
1995
- var _ref = _async_to_generator(function(emailsDirPath, builtPreviewAppPath) {
1996
- var emailDirectoryMetadata, parameters, removeForceDynamic;
1997
- return _ts_generator(this, function(_state) {
1998
- switch(_state.label){
1999
- case 0:
2000
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2001
- return [
2002
- 4,
2003
- getEmailsDirectoryMetadata(emailsDirPath)
2004
- ];
2005
- case 1:
2006
- emailDirectoryMetadata = _state.sent();
2007
- parameters = getEmailSlugsFromEmailDirectory(emailDirectoryMetadata, emailsDirPath).map(function(slug) {
2008
- return {
2009
- slug: slug
2010
- };
2011
- });
2012
- removeForceDynamic = function() {
2013
- var _ref = _async_to_generator(function(filePath) {
2014
- var contents;
2015
- return _ts_generator(this, function(_state) {
2016
- switch(_state.label){
2017
- case 0:
2018
- return [
2019
- 4,
2020
- import_node_fs5.default.promises.readFile(filePath, "utf8")
2021
- ];
2022
- case 1:
2023
- contents = _state.sent();
2024
- return [
2025
- 4,
2026
- import_node_fs5.default.promises.writeFile(filePath, contents.replace("export const dynamic = 'force-dynamic';", ""), "utf8")
2027
- ];
2028
- case 2:
2029
- _state.sent();
2030
- return [
2031
- 2
2032
- ];
2033
- }
2034
- });
2035
- });
2036
- return function removeForceDynamic(filePath) {
2037
- return _ref.apply(this, arguments);
2038
- };
2039
- }();
2040
- return [
2041
- 4,
2042
- removeForceDynamic(import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/layout.tsx"))
2043
- ];
2044
- case 2:
2045
- _state.sent();
2046
- return [
2047
- 4,
2048
- removeForceDynamic(import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx"))
2049
- ];
2050
- case 3:
2051
- _state.sent();
2052
- return [
2053
- 4,
2054
- import_node_fs5.default.promises.appendFile(import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx"), "\n\nexport function generateStaticParams() { \n return Promise.resolve(\n ".concat(JSON.stringify(parameters), "\n );\n}"), "utf8")
2055
- ];
2056
- case 4:
2057
- _state.sent();
2058
- return [
2059
- 2
2060
- ];
2061
- }
2062
- });
815
+
816
+ // src/cli/commands/build.ts
817
+ var buildPreviewApp = (absoluteDirectory) => {
818
+ return new Promise((resolve, reject) => {
819
+ const nextBuild = (0, import_node_child_process.spawn)("npm", ["run", "build"], {
820
+ cwd: absoluteDirectory,
821
+ shell: true
2063
822
  });
2064
- return function forceSSGForEmailPreviews(emailsDirPath, builtPreviewAppPath) {
2065
- return _ref.apply(this, arguments);
2066
- };
2067
- }();
2068
- var updatePackageJson = function() {
2069
- var _ref = _async_to_generator(function(builtPreviewAppPath) {
2070
- var packageJsonPath, packageJson, _;
2071
- return _ts_generator(this, function(_state) {
2072
- switch(_state.label){
2073
- case 0:
2074
- packageJsonPath = import_node_path8.default.resolve(builtPreviewAppPath, "./package.json");
2075
- _ = JSON.parse;
2076
- return [
2077
- 4,
2078
- import_node_fs5.default.promises.readFile(packageJsonPath, "utf8")
2079
- ];
2080
- case 1:
2081
- packageJson = _.apply(JSON, [
2082
- _state.sent()
2083
- ]);
2084
- packageJson.scripts.build = "next build";
2085
- packageJson.scripts.start = "next start";
2086
- packageJson.name = "preview-server";
2087
- delete packageJson.devDependencies["@react-email/render"];
2088
- delete packageJson.devDependencies["@react-email/components"];
2089
- return [
2090
- 4,
2091
- import_node_fs5.default.promises.writeFile(packageJsonPath, JSON.stringify(packageJson), "utf8")
2092
- ];
2093
- case 2:
2094
- _state.sent();
2095
- return [
2096
- 2
2097
- ];
2098
- }
2099
- });
823
+ nextBuild.stdout.pipe(process.stdout);
824
+ nextBuild.stderr.pipe(process.stderr);
825
+ nextBuild.on("close", (code) => {
826
+ if (code === 0) {
827
+ resolve();
828
+ } else {
829
+ reject(
830
+ new Error(
831
+ `Unable to build the Next app and it exited with code: ${code}`
832
+ )
833
+ );
834
+ }
2100
835
  });
2101
- return function updatePackageJson(builtPreviewAppPath) {
2102
- return _ref.apply(this, arguments);
2103
- };
2104
- }();
2105
- var npmInstall = function() {
2106
- var _ref = _async_to_generator(function(builtPreviewAppPath, packageManager) {
2107
- return _ts_generator(this, function(_state) {
2108
- return [
2109
- 2,
2110
- new Promise(function(resolve, reject) {
2111
- var childProc = (0, import_node_child_process.spawn)(packageManager, [
2112
- "install",
2113
- "--silent",
2114
- "--include=dev"
2115
- ], {
2116
- cwd: builtPreviewAppPath,
2117
- shell: true
2118
- });
2119
- childProc.stdout.pipe(process.stdout);
2120
- childProc.stderr.pipe(process.stderr);
2121
- childProc.on("close", function(code) {
2122
- if (code === 0) {
2123
- resolve();
2124
- } else {
2125
- reject(new Error("Unable to install the dependencies and it exited with code: ".concat(code)));
2126
- }
2127
- });
2128
- })
2129
- ];
2130
- });
836
+ });
837
+ };
838
+ var setNextEnvironmentVariablesForBuild = async (emailsDirRelativePath, builtPreviewAppPath) => {
839
+ const nextConfigContents = `
840
+ const path = require('path');
841
+ const emailsDirRelativePath = path.normalize('${emailsDirRelativePath}');
842
+ const userProjectLocation = path.resolve(process.cwd(), '../');
843
+ /** @type {import('next').NextConfig} */
844
+ module.exports = {
845
+ env: {
846
+ NEXT_PUBLIC_IS_BUILDING: 'true',
847
+ EMAILS_DIR_RELATIVE_PATH: emailsDirRelativePath,
848
+ EMAILS_DIR_ABSOLUTE_PATH: path.resolve(userProjectLocation, emailsDirRelativePath),
849
+ USER_PROJECT_LOCATION: userProjectLocation
850
+ },
851
+ // this is needed so that the code for building emails works properly
852
+ webpack: (
853
+ /** @type {import('webpack').Configuration & { externals: string[] }} */
854
+ config,
855
+ { isServer }
856
+ ) => {
857
+ if (isServer) {
858
+ config.externals.push('esbuild');
859
+ }
860
+
861
+ return config;
862
+ },
863
+ typescript: {
864
+ ignoreBuildErrors: true
865
+ },
866
+ eslint: {
867
+ ignoreDuringBuilds: true
868
+ },
869
+ experimental: {
870
+ webpackBuildWorker: true
871
+ },
872
+ }`;
873
+ await import_node_fs5.default.promises.writeFile(
874
+ import_node_path8.default.resolve(builtPreviewAppPath, "./next.config.js"),
875
+ nextConfigContents,
876
+ "utf8"
877
+ );
878
+ };
879
+ var getEmailSlugsFromEmailDirectory = (emailDirectory, emailsDirectoryAbsolutePath) => {
880
+ const directoryPathRelativeToEmailsDirectory = emailDirectory.absolutePath.replace(emailsDirectoryAbsolutePath, "").trim();
881
+ const slugs = [];
882
+ emailDirectory.emailFilenames.forEach(
883
+ (filename) => slugs.push(
884
+ import_node_path8.default.join(directoryPathRelativeToEmailsDirectory, filename).split(import_node_path8.default.sep).filter((segment) => segment.length > 0)
885
+ )
886
+ );
887
+ emailDirectory.subDirectories.forEach((directory) => {
888
+ slugs.push(
889
+ ...getEmailSlugsFromEmailDirectory(
890
+ directory,
891
+ emailsDirectoryAbsolutePath
892
+ )
893
+ );
894
+ });
895
+ return slugs;
896
+ };
897
+ var forceSSGForEmailPreviews = async (emailsDirPath, builtPreviewAppPath) => {
898
+ const emailDirectoryMetadata = (
899
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
900
+ await getEmailsDirectoryMetadata(emailsDirPath)
901
+ );
902
+ const parameters = getEmailSlugsFromEmailDirectory(
903
+ emailDirectoryMetadata,
904
+ emailsDirPath
905
+ ).map((slug) => ({ slug }));
906
+ const removeForceDynamic = async (filePath) => {
907
+ const contents = await import_node_fs5.default.promises.readFile(filePath, "utf8");
908
+ await import_node_fs5.default.promises.writeFile(
909
+ filePath,
910
+ contents.replace("export const dynamic = 'force-dynamic';", ""),
911
+ "utf8"
912
+ );
913
+ };
914
+ await removeForceDynamic(
915
+ import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/layout.tsx")
916
+ );
917
+ await removeForceDynamic(
918
+ import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx")
919
+ );
920
+ await import_node_fs5.default.promises.appendFile(
921
+ import_node_path8.default.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx"),
922
+ `
923
+
924
+ export function generateStaticParams() {
925
+ return Promise.resolve(
926
+ ${JSON.stringify(parameters)}
927
+ );
928
+ }`,
929
+ "utf8"
930
+ );
931
+ };
932
+ var updatePackageJson = async (builtPreviewAppPath) => {
933
+ const packageJsonPath = import_node_path8.default.resolve(builtPreviewAppPath, "./package.json");
934
+ const packageJson = JSON.parse(
935
+ await import_node_fs5.default.promises.readFile(packageJsonPath, "utf8")
936
+ );
937
+ packageJson.scripts.build = "next build";
938
+ packageJson.scripts.start = "next start";
939
+ packageJson.name = "preview-server";
940
+ delete packageJson.devDependencies["@react-email/render"];
941
+ delete packageJson.devDependencies["@react-email/components"];
942
+ await import_node_fs5.default.promises.writeFile(
943
+ packageJsonPath,
944
+ JSON.stringify(packageJson),
945
+ "utf8"
946
+ );
947
+ };
948
+ var npmInstall = async (builtPreviewAppPath, packageManager) => {
949
+ return new Promise((resolve, reject) => {
950
+ const childProc = (0, import_node_child_process.spawn)(
951
+ packageManager,
952
+ ["install", "--silent", "--include=dev"],
953
+ {
954
+ cwd: builtPreviewAppPath,
955
+ shell: true
956
+ }
957
+ );
958
+ childProc.stdout.pipe(process.stdout);
959
+ childProc.stderr.pipe(process.stderr);
960
+ childProc.on("close", (code) => {
961
+ if (code === 0) {
962
+ resolve();
963
+ } else {
964
+ reject(
965
+ new Error(
966
+ `Unable to install the dependencies and it exited with code: ${code}`
967
+ )
968
+ );
969
+ }
2131
970
  });
2132
- return function npmInstall(builtPreviewAppPath, packageManager) {
2133
- return _ref.apply(this, arguments);
2134
- };
2135
- }();
2136
- var build = function() {
2137
- var _ref = _async_to_generator(function(param) {
2138
- var emailsDirRelativePath, packageManager, spinner, emailsDirPath, staticPath, builtPreviewAppPath, builtStaticDirectory, error;
2139
- return _ts_generator(this, function(_state) {
2140
- switch(_state.label){
2141
- case 0:
2142
- emailsDirRelativePath = param.dir, packageManager = param.packageManager;
2143
- _state.label = 1;
2144
- case 1:
2145
- _state.trys.push([
2146
- 1,
2147
- 12,
2148
- ,
2149
- 13
2150
- ]);
2151
- spinner = (0, import_ora2.default)({
2152
- text: "Starting build process...",
2153
- prefixText: " "
2154
- }).start();
2155
- registerSpinnerAutostopping(spinner);
2156
- spinner.text = "Checking if ".concat(emailsDirRelativePath, " folder exists");
2157
- if (!import_node_fs5.default.existsSync(emailsDirRelativePath)) {
2158
- process.exit(1);
2159
- }
2160
- emailsDirPath = import_node_path8.default.join(process.cwd(), emailsDirRelativePath);
2161
- staticPath = import_node_path8.default.join(emailsDirPath, "static");
2162
- builtPreviewAppPath = import_node_path8.default.join(process.cwd(), ".react-email");
2163
- if (!import_node_fs5.default.existsSync(builtPreviewAppPath)) return [
2164
- 3,
2165
- 3
2166
- ];
2167
- spinner.text = "Deleting pre-existing `.react-email` folder";
2168
- return [
2169
- 4,
2170
- import_node_fs5.default.promises.rm(builtPreviewAppPath, {
2171
- recursive: true
2172
- })
2173
- ];
2174
- case 2:
2175
- _state.sent();
2176
- _state.label = 3;
2177
- case 3:
2178
- spinner.text = "Copying preview app from CLI to `.react-email`";
2179
- return [
2180
- 4,
2181
- import_node_fs5.default.promises.cp(cliPacakgeLocation, builtPreviewAppPath, {
2182
- recursive: true,
2183
- filter: function(source) {
2184
- return !/(\/|\\)cli(\/|\\)?/.test(source) && !/(\/|\\)\.next(\/|\\)?/.test(source) && !/(\/|\\)\.turbo(\/|\\)?/.test(source) && !/(\/|\\)node_modules(\/|\\)?$/.test(source);
2185
- }
2186
- })
2187
- ];
2188
- case 4:
2189
- _state.sent();
2190
- if (!import_node_fs5.default.existsSync(staticPath)) return [
2191
- 3,
2192
- 6
2193
- ];
2194
- spinner.text = "Copying `static` folder into `.react-email/public/static`";
2195
- builtStaticDirectory = import_node_path8.default.resolve(builtPreviewAppPath, "./public/static");
2196
- return [
2197
- 4,
2198
- import_node_fs5.default.promises.cp(staticPath, builtStaticDirectory, {
2199
- recursive: true
2200
- })
2201
- ];
2202
- case 5:
2203
- _state.sent();
2204
- _state.label = 6;
2205
- case 6:
2206
- spinner.text = "Setting Next environment variables for preview app to work properly";
2207
- return [
2208
- 4,
2209
- setNextEnvironmentVariablesForBuild(emailsDirRelativePath, builtPreviewAppPath)
2210
- ];
2211
- case 7:
2212
- _state.sent();
2213
- spinner.text = "Setting server side generation for the email preview pages";
2214
- return [
2215
- 4,
2216
- forceSSGForEmailPreviews(emailsDirPath, builtPreviewAppPath)
2217
- ];
2218
- case 8:
2219
- _state.sent();
2220
- spinner.text = "Updating package.json's build and start scripts";
2221
- return [
2222
- 4,
2223
- updatePackageJson(builtPreviewAppPath)
2224
- ];
2225
- case 9:
2226
- _state.sent();
2227
- spinner.text = "Installing dependencies on `.react-email`";
2228
- return [
2229
- 4,
2230
- npmInstall(builtPreviewAppPath, packageManager)
2231
- ];
2232
- case 10:
2233
- _state.sent();
2234
- spinner.stopAndPersist({
2235
- text: "Successfully prepared `.react-email` for `next build`",
2236
- symbol: import_log_symbols3.default.success
2237
- });
2238
- return [
2239
- 4,
2240
- buildPreviewApp(builtPreviewAppPath)
2241
- ];
2242
- case 11:
2243
- _state.sent();
2244
- return [
2245
- 3,
2246
- 13
2247
- ];
2248
- case 12:
2249
- error = _state.sent();
2250
- console.log(error);
2251
- process.exit(1);
2252
- return [
2253
- 3,
2254
- 13
2255
- ];
2256
- case 13:
2257
- return [
2258
- 2
2259
- ];
2260
- }
2261
- });
971
+ });
972
+ };
973
+ var build = async ({
974
+ dir: emailsDirRelativePath,
975
+ packageManager
976
+ }) => {
977
+ try {
978
+ const spinner = (0, import_ora2.default)({
979
+ text: "Starting build process...",
980
+ prefixText: " "
981
+ }).start();
982
+ registerSpinnerAutostopping(spinner);
983
+ spinner.text = `Checking if ${emailsDirRelativePath} folder exists`;
984
+ if (!import_node_fs5.default.existsSync(emailsDirRelativePath)) {
985
+ process.exit(1);
986
+ }
987
+ const emailsDirPath = import_node_path8.default.join(process.cwd(), emailsDirRelativePath);
988
+ const staticPath = import_node_path8.default.join(emailsDirPath, "static");
989
+ const builtPreviewAppPath = import_node_path8.default.join(process.cwd(), ".react-email");
990
+ if (import_node_fs5.default.existsSync(builtPreviewAppPath)) {
991
+ spinner.text = "Deleting pre-existing `.react-email` folder";
992
+ await import_node_fs5.default.promises.rm(builtPreviewAppPath, { recursive: true });
993
+ }
994
+ spinner.text = "Copying preview app from CLI to `.react-email`";
995
+ await import_node_fs5.default.promises.cp(cliPacakgeLocation, builtPreviewAppPath, {
996
+ recursive: true,
997
+ filter: (source) => {
998
+ return !/(\/|\\)cli(\/|\\)?/.test(source) && !/(\/|\\)\.next(\/|\\)?/.test(source) && !/(\/|\\)\.turbo(\/|\\)?/.test(source) && !/(\/|\\)node_modules(\/|\\)?$/.test(source);
999
+ }
2262
1000
  });
2263
- return function build(_) {
2264
- return _ref.apply(this, arguments);
2265
- };
2266
- }();
1001
+ if (import_node_fs5.default.existsSync(staticPath)) {
1002
+ spinner.text = "Copying `static` folder into `.react-email/public/static`";
1003
+ const builtStaticDirectory = import_node_path8.default.resolve(
1004
+ builtPreviewAppPath,
1005
+ "./public/static"
1006
+ );
1007
+ await import_node_fs5.default.promises.cp(staticPath, builtStaticDirectory, {
1008
+ recursive: true
1009
+ });
1010
+ }
1011
+ spinner.text = "Setting Next environment variables for preview app to work properly";
1012
+ await setNextEnvironmentVariablesForBuild(
1013
+ emailsDirRelativePath,
1014
+ builtPreviewAppPath
1015
+ );
1016
+ spinner.text = "Setting server side generation for the email preview pages";
1017
+ await forceSSGForEmailPreviews(emailsDirPath, builtPreviewAppPath);
1018
+ spinner.text = "Updating package.json's build and start scripts";
1019
+ await updatePackageJson(builtPreviewAppPath);
1020
+ spinner.text = "Installing dependencies on `.react-email`";
1021
+ await npmInstall(builtPreviewAppPath, packageManager);
1022
+ spinner.stopAndPersist({
1023
+ text: "Successfully prepared `.react-email` for `next build`",
1024
+ symbol: import_log_symbols3.default.success
1025
+ });
1026
+ await buildPreviewApp(builtPreviewAppPath);
1027
+ } catch (error) {
1028
+ console.log(error);
1029
+ process.exit(1);
1030
+ }
1031
+ };
1032
+
2267
1033
  // src/cli/commands/dev.ts
2268
1034
  var import_node_fs6 = __toESM(require("fs"));
2269
- var dev = function() {
2270
- var _ref = _async_to_generator(function(param) {
2271
- var emailsDirRelativePath, port, devServer2, error;
2272
- return _ts_generator(this, function(_state) {
2273
- switch(_state.label){
2274
- case 0:
2275
- emailsDirRelativePath = param.dir, port = param.port;
2276
- _state.label = 1;
2277
- case 1:
2278
- _state.trys.push([
2279
- 1,
2280
- 4,
2281
- ,
2282
- 5
2283
- ]);
2284
- if (!import_node_fs6.default.existsSync(emailsDirRelativePath)) {
2285
- console.error("Missing ".concat(emailsDirRelativePath, " folder"));
2286
- process.exit(1);
2287
- }
2288
- return [
2289
- 4,
2290
- startDevServer(emailsDirRelativePath, emailsDirRelativePath, // defaults to ./emails/static for the static files that are served to the preview
2291
- Number.parseInt(port))
2292
- ];
2293
- case 2:
2294
- devServer2 = _state.sent();
2295
- return [
2296
- 4,
2297
- setupHotreloading(devServer2, emailsDirRelativePath)
2298
- ];
2299
- case 3:
2300
- _state.sent();
2301
- return [
2302
- 3,
2303
- 5
2304
- ];
2305
- case 4:
2306
- error = _state.sent();
2307
- console.log(error);
2308
- process.exit(1);
2309
- return [
2310
- 3,
2311
- 5
2312
- ];
2313
- case 5:
2314
- return [
2315
- 2
2316
- ];
2317
- }
2318
- });
2319
- });
2320
- return function dev(_) {
2321
- return _ref.apply(this, arguments);
2322
- };
2323
- }();
1035
+ var dev = async ({ dir: emailsDirRelativePath, port }) => {
1036
+ try {
1037
+ if (!import_node_fs6.default.existsSync(emailsDirRelativePath)) {
1038
+ console.error(`Missing ${emailsDirRelativePath} folder`);
1039
+ process.exit(1);
1040
+ }
1041
+ const devServer2 = await startDevServer(
1042
+ emailsDirRelativePath,
1043
+ emailsDirRelativePath,
1044
+ // defaults to ./emails/static for the static files that are served to the preview
1045
+ Number.parseInt(port)
1046
+ );
1047
+ await setupHotreloading(devServer2, emailsDirRelativePath);
1048
+ } catch (error) {
1049
+ console.log(error);
1050
+ process.exit(1);
1051
+ }
1052
+ };
1053
+
2324
1054
  // src/cli/commands/export.ts
2325
1055
  var import_node_fs8 = __toESM(require("fs"));
2326
1056
  var import_node_path10 = __toESM(require("path"));
@@ -2329,457 +1059,244 @@ var import_glob = require("glob");
2329
1059
  var import_log_symbols4 = __toESM(require("log-symbols"));
2330
1060
  var import_normalize_path = __toESM(require("normalize-path"));
2331
1061
  var import_ora3 = __toESM(require("ora"));
1062
+
2332
1063
  // src/utils/esbuild/renderring-utilities-exporter.ts
2333
1064
  var import_node_fs7 = require("fs");
2334
1065
  var import_node_path9 = __toESM(require("path"));
1066
+
2335
1067
  // src/utils/esbuild/escape-string-for-regex.ts
2336
1068
  function escapeStringForRegex(string) {
2337
- return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
1069
+ return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
2338
1070
  }
1071
+
2339
1072
  // src/utils/esbuild/renderring-utilities-exporter.ts
2340
- var renderingUtilitiesExporter = function(emailTemplates) {
2341
- return {
2342
- name: "rendering-utilities-exporter",
2343
- setup: function(b) {
2344
- b.onLoad({
2345
- filter: new RegExp(emailTemplates.map(function(emailPath) {
2346
- return escapeStringForRegex(emailPath);
2347
- }).join("|"))
2348
- }, function() {
2349
- var _ref = _async_to_generator(function(param) {
2350
- var pathToFile, _tmp, _, _1;
2351
- return _ts_generator(this, function(_state) {
2352
- switch(_state.label){
2353
- case 0:
2354
- pathToFile = param.path;
2355
- _tmp = {};
2356
- _1 = (_ = "").concat;
2357
- return [
2358
- 4,
2359
- import_node_fs7.promises.readFile(pathToFile, "utf8")
2360
- ];
2361
- case 1:
2362
- return [
2363
- 2,
2364
- (_tmp.contents = _1.apply(_, [
2365
- _state.sent(),
2366
- ";\n export { render } from 'react-email-module-that-will-export-render'\n export { createElement as reactEmailCreateReactElement } from 'react';\n "
2367
- ]), _tmp.loader = import_node_path9.default.extname(pathToFile).slice(1), _tmp)
2368
- ];
2369
- }
2370
- });
2371
- });
2372
- return function(_) {
2373
- return _ref.apply(this, arguments);
2374
- };
2375
- }());
2376
- b.onResolve({
2377
- filter: /^react-email-module-that-will-export-render$/
2378
- }, function() {
2379
- var _ref = _async_to_generator(function(args) {
2380
- var options, result;
2381
- return _ts_generator(this, function(_state) {
2382
- switch(_state.label){
2383
- case 0:
2384
- options = {
2385
- kind: "import-statement",
2386
- importer: args.importer,
2387
- resolveDir: args.resolveDir,
2388
- namespace: args.namespace
2389
- };
2390
- return [
2391
- 4,
2392
- b.resolve("@react-email/render", options)
2393
- ];
2394
- case 1:
2395
- result = _state.sent();
2396
- if (result.errors.length === 0) {
2397
- return [
2398
- 2,
2399
- result
2400
- ];
2401
- }
2402
- return [
2403
- 4,
2404
- b.resolve("@react-email/components", options)
2405
- ];
2406
- case 2:
2407
- result = _state.sent();
2408
- if (result.errors.length > 0 && result.errors[0]) {
2409
- 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?";
2410
- }
2411
- return [
2412
- 2,
2413
- result
2414
- ];
2415
- }
2416
- });
2417
- });
2418
- return function(args) {
2419
- return _ref.apply(this, arguments);
2420
- };
2421
- }());
1073
+ var renderingUtilitiesExporter = (emailTemplates) => ({
1074
+ name: "rendering-utilities-exporter",
1075
+ setup: (b) => {
1076
+ b.onLoad(
1077
+ {
1078
+ filter: new RegExp(
1079
+ emailTemplates.map((emailPath) => escapeStringForRegex(emailPath)).join("|")
1080
+ )
1081
+ },
1082
+ async ({ path: pathToFile }) => {
1083
+ return {
1084
+ contents: `${await import_node_fs7.promises.readFile(pathToFile, "utf8")};
1085
+ export { render } from 'react-email-module-that-will-export-render'
1086
+ export { createElement as reactEmailCreateReactElement } from 'react';
1087
+ `,
1088
+ loader: import_node_path9.default.extname(pathToFile).slice(1)
1089
+ };
1090
+ }
1091
+ );
1092
+ b.onResolve(
1093
+ { filter: /^react-email-module-that-will-export-render$/ },
1094
+ async (args) => {
1095
+ const options = {
1096
+ kind: "import-statement",
1097
+ importer: args.importer,
1098
+ resolveDir: args.resolveDir,
1099
+ namespace: args.namespace
1100
+ };
1101
+ let result = await b.resolve("@react-email/render", options);
1102
+ if (result.errors.length === 0) {
1103
+ return result;
2422
1104
  }
2423
- };
2424
- };
1105
+ result = await b.resolve("@react-email/components", options);
1106
+ if (result.errors.length > 0 && result.errors[0]) {
1107
+ 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?";
1108
+ }
1109
+ return result;
1110
+ }
1111
+ );
1112
+ }
1113
+ });
1114
+
2425
1115
  // src/cli/commands/export.ts
2426
- var getEmailTemplatesFromDirectory = function(emailDirectory) {
2427
- var templatePaths = [];
2428
- emailDirectory.emailFilenames.forEach(function(filename) {
2429
- return templatePaths.push(import_node_path10.default.join(emailDirectory.absolutePath, filename));
2430
- });
2431
- emailDirectory.subDirectories.forEach(function(directory) {
2432
- var _templatePaths;
2433
- (_templatePaths = templatePaths).push.apply(_templatePaths, _to_consumable_array(getEmailTemplatesFromDirectory(directory)));
2434
- });
2435
- return templatePaths;
1116
+ var getEmailTemplatesFromDirectory = (emailDirectory) => {
1117
+ const templatePaths = [];
1118
+ emailDirectory.emailFilenames.forEach(
1119
+ (filename) => templatePaths.push(import_node_path10.default.join(emailDirectory.absolutePath, filename))
1120
+ );
1121
+ emailDirectory.subDirectories.forEach((directory) => {
1122
+ templatePaths.push(...getEmailTemplatesFromDirectory(directory));
1123
+ });
1124
+ return templatePaths;
2436
1125
  };
2437
- var exportTemplates = function() {
2438
- var _ref = _async_to_generator(function(pathToWhereEmailMarkupShouldBeDumped, emailsDirectoryPath, options) {
2439
- var spinner, emailsDirectoryMetadata, allTemplates, exception, buildFailure, allBuiltTemplates, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, template, emailModule, rendered, htmlPath, exception1, err, staticDirectoryPath, pathToDumpStaticFilesInto, exception2, fileTree;
2440
- return _ts_generator(this, function(_state) {
2441
- switch(_state.label){
2442
- case 0:
2443
- if (import_node_fs8.default.existsSync(pathToWhereEmailMarkupShouldBeDumped)) {
2444
- import_node_fs8.default.rmSync(pathToWhereEmailMarkupShouldBeDumped, {
2445
- recursive: true
2446
- });
2447
- }
2448
- if (!options.silent) {
2449
- spinner = (0, import_ora3.default)("Preparing files...\n").start();
2450
- registerSpinnerAutostopping(spinner);
2451
- }
2452
- return [
2453
- 4,
2454
- getEmailsDirectoryMetadata(import_node_path10.default.resolve(process.cwd(), emailsDirectoryPath), true)
2455
- ];
2456
- case 1:
2457
- emailsDirectoryMetadata = _state.sent();
2458
- if (typeof emailsDirectoryMetadata === "undefined") {
2459
- if (spinner) {
2460
- spinner.stopAndPersist({
2461
- symbol: import_log_symbols4.default.error,
2462
- text: "Could not find the directory at ".concat(emailsDirectoryPath)
2463
- });
2464
- }
2465
- return [
2466
- 2
2467
- ];
2468
- }
2469
- allTemplates = getEmailTemplatesFromDirectory(emailsDirectoryMetadata);
2470
- _state.label = 2;
2471
- case 2:
2472
- _state.trys.push([
2473
- 2,
2474
- 4,
2475
- ,
2476
- 5
2477
- ]);
2478
- return [
2479
- 4,
2480
- (0, import_esbuild.build)({
2481
- bundle: true,
2482
- entryPoints: allTemplates,
2483
- plugins: [
2484
- renderingUtilitiesExporter(allTemplates)
2485
- ],
2486
- platform: "node",
2487
- format: "cjs",
2488
- loader: {
2489
- ".js": "jsx"
2490
- },
2491
- outExtension: {
2492
- ".js": ".cjs"
2493
- },
2494
- jsx: "transform",
2495
- write: true,
2496
- outdir: pathToWhereEmailMarkupShouldBeDumped
2497
- })
2498
- ];
2499
- case 3:
2500
- _state.sent();
2501
- return [
2502
- 3,
2503
- 5
2504
- ];
2505
- case 4:
2506
- exception = _state.sent();
2507
- buildFailure = exception;
2508
- if (spinner) {
2509
- spinner.stopAndPersist({
2510
- symbol: import_log_symbols4.default.error,
2511
- text: "Failed to build emails"
2512
- });
2513
- }
2514
- process.exit(1);
2515
- return [
2516
- 3,
2517
- 5
2518
- ];
2519
- case 5:
2520
- if (spinner) {
2521
- spinner.succeed();
2522
- }
2523
- allBuiltTemplates = import_glob.glob.sync((0, import_normalize_path.default)("".concat(pathToWhereEmailMarkupShouldBeDumped, "/**/*.cjs")), {
2524
- absolute: true
2525
- });
2526
- _iteratorAbruptCompletion = false, _didIteratorError = false;
2527
- _state.label = 6;
2528
- case 6:
2529
- _state.trys.push([
2530
- 6,
2531
- 14,
2532
- 15,
2533
- 20
2534
- ]);
2535
- _iterator = _async_iterator(allBuiltTemplates);
2536
- _state.label = 7;
2537
- case 7:
2538
- return [
2539
- 4,
2540
- _iterator.next()
2541
- ];
2542
- case 8:
2543
- if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
2544
- 3,
2545
- 13
2546
- ];
2547
- _value = _step.value;
2548
- template = _value;
2549
- _state.label = 9;
2550
- case 9:
2551
- _state.trys.push([
2552
- 9,
2553
- 11,
2554
- ,
2555
- 12
2556
- ]);
2557
- if (spinner) {
2558
- spinner.text = "rendering ".concat(template.split("/").pop());
2559
- spinner.render();
2560
- }
2561
- delete require.cache[template];
2562
- emailModule = require(template);
2563
- return [
2564
- 4,
2565
- emailModule.render(emailModule.reactEmailCreateReactElement(emailModule.default, {}), options)
2566
- ];
2567
- case 10:
2568
- rendered = _state.sent();
2569
- htmlPath = template.replace(".cjs", options.plainText ? ".txt" : ".html");
2570
- (0, import_node_fs8.writeFileSync)(htmlPath, rendered);
2571
- (0, import_node_fs8.unlinkSync)(template);
2572
- return [
2573
- 3,
2574
- 12
2575
- ];
2576
- case 11:
2577
- exception1 = _state.sent();
2578
- if (spinner) {
2579
- spinner.stopAndPersist({
2580
- symbol: import_log_symbols4.default.error,
2581
- text: "failed when rendering ".concat(template.split("/").pop())
2582
- });
2583
- }
2584
- console.error(exception1);
2585
- process.exit(1);
2586
- return [
2587
- 3,
2588
- 12
2589
- ];
2590
- case 12:
2591
- _iteratorAbruptCompletion = false;
2592
- return [
2593
- 3,
2594
- 7
2595
- ];
2596
- case 13:
2597
- return [
2598
- 3,
2599
- 20
2600
- ];
2601
- case 14:
2602
- err = _state.sent();
2603
- _didIteratorError = true;
2604
- _iteratorError = err;
2605
- return [
2606
- 3,
2607
- 20
2608
- ];
2609
- case 15:
2610
- _state.trys.push([
2611
- 15,
2612
- ,
2613
- 18,
2614
- 19
2615
- ]);
2616
- if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
2617
- 3,
2618
- 17
2619
- ];
2620
- return [
2621
- 4,
2622
- _iterator.return()
2623
- ];
2624
- case 16:
2625
- _state.sent();
2626
- _state.label = 17;
2627
- case 17:
2628
- return [
2629
- 3,
2630
- 19
2631
- ];
2632
- case 18:
2633
- if (_didIteratorError) {
2634
- throw _iteratorError;
2635
- }
2636
- return [
2637
- 7
2638
- ];
2639
- case 19:
2640
- return [
2641
- 7
2642
- ];
2643
- case 20:
2644
- if (spinner) {
2645
- spinner.succeed("Rendered all files");
2646
- spinner.text = "Copying static files";
2647
- spinner.render();
2648
- }
2649
- staticDirectoryPath = import_node_path10.default.join(emailsDirectoryPath, "static");
2650
- if (!import_node_fs8.default.existsSync(staticDirectoryPath)) return [
2651
- 3,
2652
- 25
2653
- ];
2654
- pathToDumpStaticFilesInto = import_node_path10.default.join(pathToWhereEmailMarkupShouldBeDumped, "static");
2655
- if (!import_node_fs8.default.existsSync(pathToDumpStaticFilesInto)) return [
2656
- 3,
2657
- 22
2658
- ];
2659
- return [
2660
- 4,
2661
- import_node_fs8.default.promises.rm(pathToDumpStaticFilesInto, {
2662
- recursive: true
2663
- })
2664
- ];
2665
- case 21:
2666
- _state.sent();
2667
- _state.label = 22;
2668
- case 22:
2669
- _state.trys.push([
2670
- 22,
2671
- 24,
2672
- ,
2673
- 25
2674
- ]);
2675
- return [
2676
- 4,
2677
- import_node_fs8.default.promises.cp(staticDirectoryPath, pathToDumpStaticFilesInto, {
2678
- recursive: true
2679
- })
2680
- ];
2681
- case 23:
2682
- _state.sent();
2683
- return [
2684
- 3,
2685
- 25
2686
- ];
2687
- case 24:
2688
- exception2 = _state.sent();
2689
- console.error(exception2);
2690
- if (spinner) {
2691
- spinner.stopAndPersist({
2692
- symbol: import_log_symbols4.default.error,
2693
- text: "Failed to copy static files"
2694
- });
2695
- }
2696
- console.error("Something went wrong while copying the file to ".concat(pathToWhereEmailMarkupShouldBeDumped, "/static, ").concat(exception2));
2697
- process.exit(1);
2698
- return [
2699
- 3,
2700
- 25
2701
- ];
2702
- case 25:
2703
- if (!(spinner && !options.silent)) return [
2704
- 3,
2705
- 27
2706
- ];
2707
- spinner.succeed();
2708
- return [
2709
- 4,
2710
- tree(pathToWhereEmailMarkupShouldBeDumped, 4)
2711
- ];
2712
- case 26:
2713
- fileTree = _state.sent();
2714
- console.log(fileTree);
2715
- spinner.stopAndPersist({
2716
- symbol: import_log_symbols4.default.success,
2717
- text: "Successfully exported emails"
2718
- });
2719
- _state.label = 27;
2720
- case 27:
2721
- return [
2722
- 2
2723
- ];
2724
- }
1126
+ var exportTemplates = async (pathToWhereEmailMarkupShouldBeDumped, emailsDirectoryPath, options) => {
1127
+ if (import_node_fs8.default.existsSync(pathToWhereEmailMarkupShouldBeDumped)) {
1128
+ import_node_fs8.default.rmSync(pathToWhereEmailMarkupShouldBeDumped, { recursive: true });
1129
+ }
1130
+ let spinner;
1131
+ if (!options.silent) {
1132
+ spinner = (0, import_ora3.default)("Preparing files...\n").start();
1133
+ registerSpinnerAutostopping(spinner);
1134
+ }
1135
+ const emailsDirectoryMetadata = await getEmailsDirectoryMetadata(
1136
+ import_node_path10.default.resolve(process.cwd(), emailsDirectoryPath),
1137
+ true
1138
+ );
1139
+ if (typeof emailsDirectoryMetadata === "undefined") {
1140
+ if (spinner) {
1141
+ spinner.stopAndPersist({
1142
+ symbol: import_log_symbols4.default.error,
1143
+ text: `Could not find the directory at ${emailsDirectoryPath}`
1144
+ });
1145
+ }
1146
+ return;
1147
+ }
1148
+ const allTemplates = getEmailTemplatesFromDirectory(emailsDirectoryMetadata);
1149
+ try {
1150
+ await (0, import_esbuild.build)({
1151
+ bundle: true,
1152
+ entryPoints: allTemplates,
1153
+ plugins: [renderingUtilitiesExporter(allTemplates)],
1154
+ platform: "node",
1155
+ format: "cjs",
1156
+ loader: { ".js": "jsx" },
1157
+ outExtension: { ".js": ".cjs" },
1158
+ jsx: "transform",
1159
+ write: true,
1160
+ outdir: pathToWhereEmailMarkupShouldBeDumped
1161
+ });
1162
+ } catch (exception) {
1163
+ const buildFailure = exception;
1164
+ if (spinner) {
1165
+ spinner.stopAndPersist({
1166
+ symbol: import_log_symbols4.default.error,
1167
+ text: "Failed to build emails"
1168
+ });
1169
+ }
1170
+ process.exit(1);
1171
+ }
1172
+ if (spinner) {
1173
+ spinner.succeed();
1174
+ }
1175
+ const allBuiltTemplates = import_glob.glob.sync(
1176
+ (0, import_normalize_path.default)(`${pathToWhereEmailMarkupShouldBeDumped}/**/*.cjs`),
1177
+ {
1178
+ absolute: true
1179
+ }
1180
+ );
1181
+ for await (const template of allBuiltTemplates) {
1182
+ try {
1183
+ if (spinner) {
1184
+ spinner.text = `rendering ${template.split("/").pop()}`;
1185
+ spinner.render();
1186
+ }
1187
+ delete require.cache[template];
1188
+ const emailModule = require(template);
1189
+ const rendered = await emailModule.render(
1190
+ emailModule.reactEmailCreateReactElement(emailModule.default, {}),
1191
+ options
1192
+ );
1193
+ const htmlPath = template.replace(
1194
+ ".cjs",
1195
+ options.plainText ? ".txt" : ".html"
1196
+ );
1197
+ (0, import_node_fs8.writeFileSync)(htmlPath, rendered);
1198
+ (0, import_node_fs8.unlinkSync)(template);
1199
+ } catch (exception) {
1200
+ if (spinner) {
1201
+ spinner.stopAndPersist({
1202
+ symbol: import_log_symbols4.default.error,
1203
+ text: `failed when rendering ${template.split("/").pop()}`
1204
+ });
1205
+ }
1206
+ console.error(exception);
1207
+ process.exit(1);
1208
+ }
1209
+ }
1210
+ if (spinner) {
1211
+ spinner.succeed("Rendered all files");
1212
+ spinner.text = "Copying static files";
1213
+ spinner.render();
1214
+ }
1215
+ const staticDirectoryPath = import_node_path10.default.join(emailsDirectoryPath, "static");
1216
+ if (import_node_fs8.default.existsSync(staticDirectoryPath)) {
1217
+ const pathToDumpStaticFilesInto = import_node_path10.default.join(
1218
+ pathToWhereEmailMarkupShouldBeDumped,
1219
+ "static"
1220
+ );
1221
+ if (import_node_fs8.default.existsSync(pathToDumpStaticFilesInto))
1222
+ await import_node_fs8.default.promises.rm(pathToDumpStaticFilesInto, { recursive: true });
1223
+ try {
1224
+ await import_node_fs8.default.promises.cp(staticDirectoryPath, pathToDumpStaticFilesInto, {
1225
+ recursive: true
1226
+ });
1227
+ } catch (exception) {
1228
+ console.error(exception);
1229
+ if (spinner) {
1230
+ spinner.stopAndPersist({
1231
+ symbol: import_log_symbols4.default.error,
1232
+ text: "Failed to copy static files"
2725
1233
  });
1234
+ }
1235
+ console.error(
1236
+ `Something went wrong while copying the file to ${pathToWhereEmailMarkupShouldBeDumped}/static, ${exception}`
1237
+ );
1238
+ process.exit(1);
1239
+ }
1240
+ }
1241
+ if (spinner && !options.silent) {
1242
+ spinner.succeed();
1243
+ const fileTree = await tree(pathToWhereEmailMarkupShouldBeDumped, 4);
1244
+ console.log(fileTree);
1245
+ spinner.stopAndPersist({
1246
+ symbol: import_log_symbols4.default.success,
1247
+ text: "Successfully exported emails"
2726
1248
  });
2727
- return function exportTemplates(pathToWhereEmailMarkupShouldBeDumped, emailsDirectoryPath, options) {
2728
- return _ref.apply(this, arguments);
2729
- };
2730
- }();
1249
+ }
1250
+ };
1251
+
2731
1252
  // src/cli/commands/start.ts
2732
1253
  var import_node_child_process2 = require("child_process");
2733
1254
  var import_node_fs9 = __toESM(require("fs"));
2734
1255
  var import_node_path11 = __toESM(require("path"));
2735
- var start = function() {
2736
- var _ref = _async_to_generator(function() {
2737
- var usersProjectLocation, builtPreviewPath, nextStart;
2738
- return _ts_generator(this, function(_state) {
2739
- try {
2740
- usersProjectLocation = process.cwd();
2741
- builtPreviewPath = import_node_path11.default.resolve(usersProjectLocation, "./.react-email");
2742
- if (!import_node_fs9.default.existsSync(builtPreviewPath)) {
2743
- console.error("Could not find .react-email, maybe you haven't ran email build?");
2744
- process.exit(1);
2745
- }
2746
- nextStart = (0, import_node_child_process2.spawn)("npm", [
2747
- "start"
2748
- ], {
2749
- cwd: builtPreviewPath,
2750
- stdio: "inherit"
2751
- });
2752
- process.on("SIGINT", function() {
2753
- nextStart.kill("SIGINT");
2754
- });
2755
- nextStart.on("exit", function(code) {
2756
- process.exit(code !== null && code !== void 0 ? code : 0);
2757
- });
2758
- } catch (error) {
2759
- console.log(error);
2760
- process.exit(1);
2761
- }
2762
- return [
2763
- 2
2764
- ];
2765
- });
1256
+ var start = async () => {
1257
+ try {
1258
+ const usersProjectLocation = process.cwd();
1259
+ const builtPreviewPath = import_node_path11.default.resolve(
1260
+ usersProjectLocation,
1261
+ "./.react-email"
1262
+ );
1263
+ if (!import_node_fs9.default.existsSync(builtPreviewPath)) {
1264
+ console.error(
1265
+ "Could not find .react-email, maybe you haven't ran email build?"
1266
+ );
1267
+ process.exit(1);
1268
+ }
1269
+ const nextStart = (0, import_node_child_process2.spawn)("npm", ["start"], {
1270
+ cwd: builtPreviewPath,
1271
+ stdio: "inherit"
2766
1272
  });
2767
- return function start() {
2768
- return _ref.apply(this, arguments);
2769
- };
2770
- }();
1273
+ process.on("SIGINT", () => {
1274
+ nextStart.kill("SIGINT");
1275
+ });
1276
+ nextStart.on("exit", (code) => {
1277
+ process.exit(code ?? 0);
1278
+ });
1279
+ } catch (error) {
1280
+ console.log(error);
1281
+ process.exit(1);
1282
+ }
1283
+ };
1284
+
2771
1285
  // src/cli/index.ts
2772
1286
  var PACKAGE_NAME = "react-email";
2773
1287
  import_commander.program.name(PACKAGE_NAME).description("A live preview of your emails right in your browser").version(package_default.version);
2774
1288
  import_commander.program.command("dev").description("Starts the preview email development app").option("-d, --dir <path>", "Directory with your email templates", "./emails").option("-p --port <port>", "Port to run dev server on", "3000").action(dev);
2775
- import_commander.program.command("build").description("Copies the preview app for onto .react-email and builds it").option("-d, --dir <path>", "Directory with your email templates", "./emails").option("-p --packageManager <name>", "Package name to use on installation on `.react-email`", "npm").action(build);
1289
+ import_commander.program.command("build").description("Copies the preview app for onto .react-email and builds it").option("-d, --dir <path>", "Directory with your email templates", "./emails").option(
1290
+ "-p --packageManager <name>",
1291
+ "Package name to use on installation on `.react-email`",
1292
+ "npm"
1293
+ ).action(build);
2776
1294
  import_commander.program.command("start").description('Runs the built preview app that is inside of ".react-email"').action(start);
2777
- import_commander.program.command("export").description("Build the templates to the `out` directory").option("--outDir <path>", "Output directory", "out").option("-p, --pretty", "Pretty print the output", false).option("-t, --plainText", "Set output format as plain text", false).option("-d, --dir <path>", "Directory with your email templates", "./emails").option("-s, --silent", "To, or not to show a spinner with process information", false).action(function(param) {
2778
- var outDir = param.outDir, pretty = param.pretty, plainText = param.plainText, silent = param.silent, srcDir = param.dir;
2779
- return exportTemplates(outDir, srcDir, {
2780
- pretty: pretty,
2781
- silent: silent,
2782
- plainText: plainText
2783
- });
2784
- });
1295
+ import_commander.program.command("export").description("Build the templates to the `out` directory").option("--outDir <path>", "Output directory", "out").option("-p, --pretty", "Pretty print the output", false).option("-t, --plainText", "Set output format as plain text", false).option("-d, --dir <path>", "Directory with your email templates", "./emails").option(
1296
+ "-s, --silent",
1297
+ "To, or not to show a spinner with process information",
1298
+ false
1299
+ ).action(
1300
+ ({ outDir, pretty, plainText, silent, dir: srcDir }) => exportTemplates(outDir, srcDir, { pretty, silent, plainText })
1301
+ );
2785
1302
  import_commander.program.parse();