@warlock.js/core 5.20.0 → 5.21.0

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 (295) hide show
  1. package/CHANGELOG.md +1124 -1086
  2. package/esm/benchmark/benchmark.mjs +34 -25
  3. package/esm/benchmark/benchmark.mjs.map +1 -1
  4. package/esm/benchmark/profiler.d.mts.map +1 -1
  5. package/esm/benchmark/profiler.mjs +8 -3
  6. package/esm/benchmark/profiler.mjs.map +1 -1
  7. package/esm/bootstrap.d.mts.map +1 -1
  8. package/esm/bootstrap.mjs +3 -0
  9. package/esm/bootstrap.mjs.map +1 -1
  10. package/esm/cache/database-cache-driver.d.mts +2 -2
  11. package/esm/cache/database-cache-driver.d.mts.map +1 -1
  12. package/esm/cache/database-cache-driver.mjs +3 -2
  13. package/esm/cache/database-cache-driver.mjs.map +1 -1
  14. package/esm/cli/cli-commands.manager.mjs +16 -14
  15. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  16. package/esm/cli/commands/add.command.mjs +1 -1
  17. package/esm/cli/commands/add.command.mjs.map +1 -1
  18. package/esm/cli/commands/doctor/checks/optional-peers.check.mjs +3 -2
  19. package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
  20. package/esm/cli/commands/generate/generate.command.mjs +20 -0
  21. package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
  22. package/esm/cli/commands/generate/generators/column-dsl-parser.mjs +4 -2
  23. package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
  24. package/esm/cli/commands/generate/generators/controller.generator.mjs +1 -1
  25. package/esm/cli/commands/generate/generators/controller.generator.mjs.map +1 -1
  26. package/esm/cli/commands/generate/generators/migration.generator.mjs +22 -6
  27. package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
  28. package/esm/cli/commands/generate/generators/model.generator.mjs +22 -7
  29. package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
  30. package/esm/cli/commands/generate/generators/module.generator.mjs +8 -6
  31. package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
  32. package/esm/cli/commands/generate/generators/repository.generator.mjs +1 -1
  33. package/esm/cli/commands/generate/generators/repository.generator.mjs.map +1 -1
  34. package/esm/cli/commands/generate/generators/resource.generator.mjs +1 -1
  35. package/esm/cli/commands/generate/generators/resource.generator.mjs.map +1 -1
  36. package/esm/cli/commands/generate/generators/service.generator.mjs +1 -1
  37. package/esm/cli/commands/generate/generators/service.generator.mjs.map +1 -1
  38. package/esm/cli/commands/generate/templates/stubs.mjs +7 -7
  39. package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
  40. package/esm/cli/commands/generate/utils/writer.mjs +25 -1
  41. package/esm/cli/commands/generate/utils/writer.mjs.map +1 -1
  42. package/esm/cli/commands/routes/routes-command.action.mjs +5 -1
  43. package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -1
  44. package/esm/cli/commands/routes/with-console-on-stderr.mjs +24 -0
  45. package/esm/cli/commands/routes/with-console-on-stderr.mjs.map +1 -0
  46. package/esm/cli/commands/routes.command.mjs +3 -4
  47. package/esm/cli/commands/routes.command.mjs.map +1 -1
  48. package/esm/cli/commands/start-production.command.mjs +5 -5
  49. package/esm/cli/commands/start-production.command.mjs.map +1 -1
  50. package/esm/cli/commands/storage-put.action.mjs +2 -1
  51. package/esm/cli/commands/storage-put.action.mjs.map +1 -1
  52. package/esm/cli/commands/update.command.mjs +1 -0
  53. package/esm/cli/commands/update.command.mjs.map +1 -1
  54. package/esm/cli/parse-cli-args.mjs +13 -1
  55. package/esm/cli/parse-cli-args.mjs.map +1 -1
  56. package/esm/commands/cli-command.d.mts.map +1 -1
  57. package/esm/commands/cli-command.mjs +4 -2
  58. package/esm/commands/cli-command.mjs.map +1 -1
  59. package/esm/commands/index.mjs +3 -0
  60. package/esm/config/config-key-from-path.mjs +20 -0
  61. package/esm/config/config-key-from-path.mjs.map +1 -0
  62. package/esm/config/config-loader.d.mts.map +1 -1
  63. package/esm/config/config-loader.mjs +2 -3
  64. package/esm/config/config-loader.mjs.map +1 -1
  65. package/esm/connectors/connectors-manager.d.mts +4 -0
  66. package/esm/connectors/connectors-manager.d.mts.map +1 -1
  67. package/esm/connectors/connectors-manager.mjs +30 -2
  68. package/esm/connectors/connectors-manager.mjs.map +1 -1
  69. package/esm/connectors/socket-connector.d.mts +29 -0
  70. package/esm/connectors/socket-connector.d.mts.map +1 -1
  71. package/esm/connectors/socket-connector.mjs +73 -9
  72. package/esm/connectors/socket-connector.mjs.map +1 -1
  73. package/esm/connectors/types.d.mts +1 -1
  74. package/esm/connectors/types.mjs.map +1 -1
  75. package/esm/database/models/database-log/database-log.d.mts +47 -24
  76. package/esm/database/models/database-log/database-log.d.mts.map +1 -1
  77. package/esm/database/models/database-log/database-log.mjs +36 -4
  78. package/esm/database/models/database-log/database-log.mjs.map +1 -1
  79. package/esm/database/seed-command-action.mjs +10 -2
  80. package/esm/database/seed-command-action.mjs.map +1 -1
  81. package/esm/dev-server/development-server.mjs +11 -4
  82. package/esm/dev-server/development-server.mjs.map +1 -1
  83. package/esm/dev-server/file-event-handler.mjs +26 -6
  84. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  85. package/esm/dev-server/file-manager.d.mts.map +1 -1
  86. package/esm/dev-server/file-manager.mjs +2 -2
  87. package/esm/dev-server/file-manager.mjs.map +1 -1
  88. package/esm/dev-server/files-orchestrator.mjs +3 -1
  89. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  90. package/esm/dev-server/files-watcher.mjs +64 -5
  91. package/esm/dev-server/files-watcher.mjs.map +1 -1
  92. package/esm/dev-server/health-checker/files-healthcare.manager.mjs +31 -9
  93. package/esm/dev-server/health-checker/files-healthcare.manager.mjs.map +1 -1
  94. package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs +11 -7
  95. package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs.map +1 -1
  96. package/esm/dev-server/loader/load-hook.mjs +1 -1
  97. package/esm/dev-server/loader/register-loader.mjs +1 -1
  98. package/esm/dev-server/manifest-manager.d.mts.map +1 -1
  99. package/esm/dev-server/manifest-manager.mjs +12 -6
  100. package/esm/dev-server/manifest-manager.mjs.map +1 -1
  101. package/esm/dev-server/parse-imports.mjs +9 -0
  102. package/esm/dev-server/parse-imports.mjs.map +1 -1
  103. package/esm/dev-server/register-dev-shortcuts.mjs +2 -1
  104. package/esm/dev-server/register-dev-shortcuts.mjs.map +1 -1
  105. package/esm/dev-server/shortcuts.mjs +2 -2
  106. package/esm/dev-server/shortcuts.mjs.map +1 -1
  107. package/esm/dev-server/special-file-patterns.mjs +18 -0
  108. package/esm/dev-server/special-file-patterns.mjs.map +1 -0
  109. package/esm/dev-server/special-files-collector.d.mts.map +1 -1
  110. package/esm/dev-server/special-files-collector.mjs +2 -5
  111. package/esm/dev-server/special-files-collector.mjs.map +1 -1
  112. package/esm/dev-server/start-development-server.mjs +1 -2
  113. package/esm/dev-server/start-development-server.mjs.map +1 -1
  114. package/esm/dev-server/supervisor.mjs +23 -3
  115. package/esm/dev-server/supervisor.mjs.map +1 -1
  116. package/esm/dev-server/tsconfig-manager.mjs +22 -12
  117. package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
  118. package/esm/dev-server/type-generator.mjs +10 -9
  119. package/esm/dev-server/type-generator.mjs.map +1 -1
  120. package/esm/encryption/encrypt.d.mts.map +1 -1
  121. package/esm/encryption/encrypt.mjs +16 -5
  122. package/esm/encryption/encrypt.mjs.map +1 -1
  123. package/esm/encryption/hash.d.mts.map +1 -1
  124. package/esm/encryption/hash.mjs +2 -0
  125. package/esm/encryption/hash.mjs.map +1 -1
  126. package/esm/encryption/password.d.mts.map +1 -1
  127. package/esm/encryption/password.mjs +3 -1
  128. package/esm/encryption/password.mjs.map +1 -1
  129. package/esm/generations/features/index.mjs +1 -1
  130. package/esm/generations/features/mysql.feature.mjs +9 -2
  131. package/esm/generations/features/mysql.feature.mjs.map +1 -1
  132. package/esm/generations/features/test.feature.mjs +2 -1
  133. package/esm/generations/features/test.feature.mjs.map +1 -1
  134. package/esm/generations/features/web.feature.mjs +4 -2
  135. package/esm/generations/features/web.feature.mjs.map +1 -1
  136. package/esm/http/csrf-origin-policy.d.mts.map +1 -1
  137. package/esm/http/csrf-origin-policy.mjs +5 -2
  138. package/esm/http/csrf-origin-policy.mjs.map +1 -1
  139. package/esm/http/flush-pending-cookies.mjs +52 -0
  140. package/esm/http/flush-pending-cookies.mjs.map +1 -0
  141. package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
  142. package/esm/http/middleware/cache-response-middleware.mjs +4 -2
  143. package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
  144. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  145. package/esm/http/middleware/inject-request-context.mjs +14 -3
  146. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  147. package/esm/http/middleware/utils/cidr-match.d.mts +1 -1
  148. package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
  149. package/esm/http/middleware/utils/cidr-match.mjs +11 -2
  150. package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
  151. package/esm/http/middleware/utils/idempotency-key.mjs +1 -1
  152. package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
  153. package/esm/http/plugins.d.mts.map +1 -1
  154. package/esm/http/plugins.mjs +10 -1
  155. package/esm/http/plugins.mjs.map +1 -1
  156. package/esm/http/request.d.mts +12 -1
  157. package/esm/http/request.d.mts.map +1 -1
  158. package/esm/http/request.mjs +35 -7
  159. package/esm/http/request.mjs.map +1 -1
  160. package/esm/http/response.d.mts +16 -0
  161. package/esm/http/response.d.mts.map +1 -1
  162. package/esm/http/response.mjs +75 -37
  163. package/esm/http/response.mjs.map +1 -1
  164. package/esm/http/types.d.mts +24 -0
  165. package/esm/http/types.d.mts.map +1 -1
  166. package/esm/http/uploads/uploaded-file.controller.mjs +1 -1
  167. package/esm/http/uploads-config.mjs +2 -1
  168. package/esm/http/uploads-config.mjs.map +1 -1
  169. package/esm/http/uploads-types.d.mts +3 -3
  170. package/esm/image/image.d.mts +1 -1
  171. package/esm/image/image.d.mts.map +1 -1
  172. package/esm/image/image.mjs +25 -15
  173. package/esm/image/image.mjs.map +1 -1
  174. package/esm/index.d.mts +4 -3
  175. package/esm/index.mjs +5 -3
  176. package/esm/logger/logger.mjs +6 -1
  177. package/esm/logger/logger.mjs.map +1 -1
  178. package/esm/mail/config.d.mts.map +1 -1
  179. package/esm/mail/config.mjs +31 -21
  180. package/esm/mail/config.mjs.map +1 -1
  181. package/esm/mail/react-mail.mjs +6 -3
  182. package/esm/mail/react-mail.mjs.map +1 -1
  183. package/esm/mail/send-mail.d.mts.map +1 -1
  184. package/esm/mail/send-mail.mjs +40 -19
  185. package/esm/mail/send-mail.mjs.map +1 -1
  186. package/esm/production/build-contributions.mjs +3 -0
  187. package/esm/production/build-contributions.mjs.map +1 -1
  188. package/esm/production/esbuild-plugins.mjs +3 -2
  189. package/esm/production/esbuild-plugins.mjs.map +1 -1
  190. package/esm/production/production-builder.mjs +32 -36
  191. package/esm/production/production-builder.mjs.map +1 -1
  192. package/esm/production/production-supervisor.mjs +12 -5
  193. package/esm/production/production-supervisor.mjs.map +1 -1
  194. package/esm/repositories/adapters/cascade/cascade-adapter.d.mts +3 -1
  195. package/esm/repositories/adapters/cascade/cascade-adapter.d.mts.map +1 -1
  196. package/esm/repositories/adapters/cascade/cascade-adapter.mjs +17 -5
  197. package/esm/repositories/adapters/cascade/cascade-adapter.mjs.map +1 -1
  198. package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +3 -3
  199. package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
  200. package/esm/repositories/adapters/cascade/filter-applicator.mjs +88 -61
  201. package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
  202. package/esm/repositories/adapters/cascade/index.d.mts +1 -1
  203. package/esm/repositories/adapters/cascade/index.mjs +1 -1
  204. package/esm/repositories/contracts/query-builder.contract.d.mts +3 -3
  205. package/esm/repositories/contracts/types.d.mts +5 -0
  206. package/esm/repositories/contracts/types.d.mts.map +1 -1
  207. package/esm/repositories/index.d.mts +1 -1
  208. package/esm/repositories/index.mjs +1 -1
  209. package/esm/repositories/repository.manager.d.mts +65 -3
  210. package/esm/repositories/repository.manager.d.mts.map +1 -1
  211. package/esm/repositories/repository.manager.mjs +146 -57
  212. package/esm/repositories/repository.manager.mjs.map +1 -1
  213. package/esm/resource/resource-field-builder.d.mts.map +1 -1
  214. package/esm/resource/resource-field-builder.mjs +1 -0
  215. package/esm/resource/resource-field-builder.mjs.map +1 -1
  216. package/esm/resource/resource.d.mts +10 -3
  217. package/esm/resource/resource.d.mts.map +1 -1
  218. package/esm/resource/resource.mjs +19 -5
  219. package/esm/resource/resource.mjs.map +1 -1
  220. package/esm/restful/restful.d.mts +12 -5
  221. package/esm/restful/restful.d.mts.map +1 -1
  222. package/esm/restful/restful.mjs +47 -16
  223. package/esm/restful/restful.mjs.map +1 -1
  224. package/esm/router/build-route-rate-limit.mjs +22 -0
  225. package/esm/router/build-route-rate-limit.mjs.map +1 -0
  226. package/esm/router/dev-dispatch.mjs +60 -0
  227. package/esm/router/dev-dispatch.mjs.map +1 -0
  228. package/esm/router/route-builder.mjs +4 -1
  229. package/esm/router/route-builder.mjs.map +1 -1
  230. package/esm/router/route-registry.d.mts.map +1 -1
  231. package/esm/router/route-registry.mjs +2 -2
  232. package/esm/router/route-registry.mjs.map +1 -1
  233. package/esm/router/router.d.mts +1 -1
  234. package/esm/router/router.d.mts.map +1 -1
  235. package/esm/router/router.mjs +57 -39
  236. package/esm/router/router.mjs.map +1 -1
  237. package/esm/socket/types.d.mts +9 -2
  238. package/esm/socket/types.d.mts.map +1 -1
  239. package/esm/storage/drivers/cloud-driver.d.mts +17 -0
  240. package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
  241. package/esm/storage/drivers/cloud-driver.mjs +53 -17
  242. package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
  243. package/esm/storage/drivers/local-driver.d.mts +7 -5
  244. package/esm/storage/drivers/local-driver.d.mts.map +1 -1
  245. package/esm/storage/drivers/local-driver.mjs +31 -26
  246. package/esm/storage/drivers/local-driver.mjs.map +1 -1
  247. package/esm/storage/index.d.mts +2 -1
  248. package/esm/storage/index.mjs +2 -1
  249. package/esm/storage/scoped-storage.d.mts +13 -1
  250. package/esm/storage/scoped-storage.d.mts.map +1 -1
  251. package/esm/storage/scoped-storage.mjs +18 -8
  252. package/esm/storage/scoped-storage.mjs.map +1 -1
  253. package/esm/storage/storage.d.mts +0 -5
  254. package/esm/storage/storage.d.mts.map +1 -1
  255. package/esm/storage/storage.mjs +7 -16
  256. package/esm/storage/storage.mjs.map +1 -1
  257. package/esm/storage/types.d.mts +22 -4
  258. package/esm/storage/types.d.mts.map +1 -1
  259. package/esm/storage/utils/classify-ip-address.d.mts +13 -0
  260. package/esm/storage/utils/classify-ip-address.d.mts.map +1 -0
  261. package/esm/storage/utils/classify-ip-address.mjs +98 -0
  262. package/esm/storage/utils/classify-ip-address.mjs.map +1 -0
  263. package/esm/storage/utils/safe-fetch.d.mts +3 -12
  264. package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
  265. package/esm/storage/utils/safe-fetch.mjs +3 -48
  266. package/esm/storage/utils/safe-fetch.mjs.map +1 -1
  267. package/esm/updater/update-warlock-packages.mjs +11 -1
  268. package/esm/updater/update-warlock-packages.mjs.map +1 -1
  269. package/esm/use-cases/use-case-broadcast.mjs +7 -1
  270. package/esm/use-cases/use-case-broadcast.mjs.map +1 -1
  271. package/esm/use-cases/use-cases-registry.mjs +21 -2
  272. package/esm/use-cases/use-cases-registry.mjs.map +1 -1
  273. package/esm/utils/database-log.mjs +0 -3
  274. package/esm/utils/database-log.mjs.map +1 -1
  275. package/esm/utils/queue.d.mts +6 -4
  276. package/esm/utils/queue.d.mts.map +1 -1
  277. package/esm/utils/queue.mjs +20 -9
  278. package/esm/utils/queue.mjs.map +1 -1
  279. package/esm/validation/database/exists-except-current-id.mjs +6 -2
  280. package/esm/validation/database/exists-except-current-id.mjs.map +1 -1
  281. package/esm/validation/database/unique-except-current-id.mjs +6 -2
  282. package/esm/validation/database/unique-except-current-id.mjs.map +1 -1
  283. package/esm/validation/init.mjs +6 -2
  284. package/esm/validation/init.mjs.map +1 -1
  285. package/esm/validation/validateAll.mjs +3 -2
  286. package/esm/validation/validateAll.mjs.map +1 -1
  287. package/esm/warlock-config/types.d.mts +14 -1
  288. package/esm/warlock-config/types.d.mts.map +1 -1
  289. package/esm/warlock-config/warlock-config.manager.d.mts.map +1 -1
  290. package/esm/warlock-config/warlock-config.manager.mjs +3 -1
  291. package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
  292. package/esm/warlock-config/warn-deprecated-config.mjs +25 -0
  293. package/esm/warlock-config/warn-deprecated-config.mjs.map +1 -0
  294. package/package.json +11 -11
  295. package/esm/_virtual/_rolldown/runtime.mjs +0 -7
@@ -1,16 +1,33 @@
1
+ import { config } from "../config/config-getter.mjs";
2
+ import "../config/index.mjs";
3
+ import { environment } from "../utils/environment.mjs";
4
+
1
5
  //#region ../core/src/mail/config.ts
2
6
  /**
3
7
  * Default mail configurations
4
8
  */
5
9
  const defaultConfigurations = {
6
- secure: true,
7
10
  tls: true,
8
11
  driver: "smtp"
9
12
  };
10
13
  /**
11
- * Current mail mode
14
+ * Merge defaults into an SMTP config.
15
+ * `secure` is derived from the port when not set explicitly:
16
+ * 465 uses implicit TLS, every other port (e.g. 587) uses STARTTLS.
17
+ */
18
+ function withSmtpDefaults(config) {
19
+ const merged = {
20
+ ...defaultConfigurations,
21
+ ...config
22
+ };
23
+ if (merged.secure === void 0) merged.secure = Number(merged.port) === 465;
24
+ return merged;
25
+ }
26
+ /**
27
+ * Mode set explicitly through `setMailMode`; when undefined the mode is
28
+ * derived from the environment.
12
29
  */
13
- let currentMode = "production";
30
+ let explicitMode;
14
31
  /**
15
32
  * Registered mailers configuration
16
33
  */
@@ -34,31 +51,33 @@ let mailersConfig = {};
34
51
  * ```
35
52
  */
36
53
  function setMailMode(mode) {
37
- currentMode = mode;
54
+ explicitMode = mode;
38
55
  }
39
56
  /**
40
57
  * Get the current mail mode
41
58
  */
42
59
  function getMailMode() {
43
- return currentMode;
60
+ if (explicitMode) return explicitMode;
61
+ if (environment() !== "production" && config.key("mail.sendInDevelopment") !== true) return "development";
62
+ return "production";
44
63
  }
45
64
  /**
46
65
  * Check if in production mode
47
66
  */
48
67
  function isProductionMode() {
49
- return currentMode === "production";
68
+ return getMailMode() === "production";
50
69
  }
51
70
  /**
52
71
  * Check if in development mode
53
72
  */
54
73
  function isDevelopmentMode() {
55
- return currentMode === "development";
74
+ return getMailMode() === "development";
56
75
  }
57
76
  /**
58
77
  * Check if in test mode
59
78
  */
60
79
  function isTestMode() {
61
- return currentMode === "test";
80
+ return getMailMode() === "test";
62
81
  }
63
82
  /**
64
83
  * Set mail configurations
@@ -93,10 +112,7 @@ function getDefaultMailConfig() {
93
112
  const config = mailersConfig.default;
94
113
  if (!config) return {};
95
114
  if ("driver" in config && config.driver === "ses") return config;
96
- return {
97
- ...defaultConfigurations,
98
- ...config
99
- };
115
+ return withSmtpDefaults(config);
100
116
  }
101
117
  /**
102
118
  * Get a named mailer configuration
@@ -106,10 +122,7 @@ function getMailerConfig(name) {
106
122
  const config = mailersConfig.mailers?.[name];
107
123
  if (!config) return;
108
124
  if ("driver" in config && config.driver === "ses") return config;
109
- return {
110
- ...defaultConfigurations,
111
- ...config
112
- };
125
+ return withSmtpDefaults(config);
113
126
  }
114
127
  /**
115
128
  * Resolve configuration from options
@@ -118,10 +131,7 @@ function getMailerConfig(name) {
118
131
  function resolveMailConfig(options) {
119
132
  if (options.config) {
120
133
  if ("driver" in options.config && options.config.driver === "ses") return options.config;
121
- return {
122
- ...defaultConfigurations,
123
- ...options.config
124
- };
134
+ return withSmtpDefaults(options.config);
125
135
  }
126
136
  if (options.mailer) {
127
137
  const config = getMailerConfig(options.mailer);
@@ -134,7 +144,7 @@ function resolveMailConfig(options) {
134
144
  * Reset all configurations (useful for testing)
135
145
  */
136
146
  function resetMailConfig() {
137
- currentMode = "production";
147
+ explicitMode = void 0;
138
148
  mailersConfig = {};
139
149
  }
140
150
 
@@ -1 +1 @@
1
- {"version":3,"file":"config.mjs","names":[],"sources":["../../../../../../../core/src/mail/config.ts"],"sourcesContent":["import type { MailConfigurations, MailersConfig, MailMode, SMTPConfigurations } from \"./types\";\n\n/**\n * Default mail configurations\n */\nconst defaultConfigurations: Partial<SMTPConfigurations> = {\n secure: true,\n tls: true,\n driver: \"smtp\",\n};\n\n/**\n * Current mail mode\n */\nlet currentMode: MailMode = \"production\";\n\n/**\n * Registered mailers configuration\n */\nlet mailersConfig: MailersConfig = {};\n\n/**\n * Set the mail mode\n *\n * @param mode \"production\" | \"development\" | \"test\"\n *\n * - **production**: Actually sends emails via SMTP\n * - **development**: Logs emails to console without sending\n * - **test**: Captures emails to test mailbox for assertions\n *\n * @example\n * ```typescript\n * // In test setup\n * setMailMode(\"test\");\n *\n * // In development\n * setMailMode(\"development\");\n * ```\n */\nexport function setMailMode(mode: MailMode): void {\n currentMode = mode;\n}\n\n/**\n * Get the current mail mode\n */\nexport function getMailMode(): MailMode {\n return currentMode;\n}\n\n/**\n * Check if in production mode\n */\nexport function isProductionMode(): boolean {\n return currentMode === \"production\";\n}\n\n/**\n * Check if in development mode\n */\nexport function isDevelopmentMode(): boolean {\n return currentMode === \"development\";\n}\n\n/**\n * Check if in test mode\n */\nexport function isTestMode(): boolean {\n return currentMode === \"test\";\n}\n\n/**\n * Set mail configurations\n *\n * Supports both simple config and named mailers.\n *\n * @example\n * ```typescript\n * // Simple config (sets as default)\n * setMailConfigurations({\n * host: \"smtp.gmail.com\",\n * port: 587,\n * username: \"...\",\n * password: \"...\",\n * });\n *\n * // Named mailers\n * setMailConfigurations({\n * default: { host: \"smtp.sendgrid.net\", ... },\n * mailers: {\n * marketing: { host: \"smtp.mailchimp.com\", ... },\n * transactional: { host: \"smtp.postmark.com\", ... },\n * },\n * });\n * ```\n */\nexport function setMailConfigurations(config: MailConfigurations | MailersConfig): void {\n // Check if it's a MailersConfig (has 'default' or 'mailers' key)\n if (\"default\" in config || \"mailers\" in config) {\n mailersConfig = config as MailersConfig;\n } else {\n // Simple config - set as default\n mailersConfig = {\n default: config as MailConfigurations,\n };\n }\n}\n\nexport function getDefaultMailConfig(): MailConfigurations {\n const config = mailersConfig.default;\n if (!config) return {} as MailConfigurations;\n if (\"driver\" in config && config.driver === \"ses\") return config;\n\n return {\n ...defaultConfigurations,\n ...config,\n } as SMTPConfigurations;\n}\n\n/**\n * Get a named mailer configuration\n */\nexport function getMailerConfig(name: string): MailConfigurations | undefined {\n if (name === \"default\") {\n return getDefaultMailConfig();\n }\n\n const config = mailersConfig.mailers?.[name];\n if (!config) {\n return undefined;\n }\n\n if (\"driver\" in config && config.driver === \"ses\") return config;\n\n return {\n ...defaultConfigurations,\n ...config,\n } as SMTPConfigurations;\n}\n\n/**\n * Resolve configuration from options\n * Priority: config > mailer > default\n */\nexport function resolveMailConfig(options: {\n config?: MailConfigurations;\n mailer?: string;\n}): MailConfigurations {\n if (options.config) {\n // SES config passes through as-is, no defaultConfigurations merge\n if (\"driver\" in options.config && options.config.driver === \"ses\") {\n return options.config;\n }\n\n return {\n ...defaultConfigurations,\n ...options.config,\n } as SMTPConfigurations;\n }\n\n if (options.mailer) {\n const config = getMailerConfig(options.mailer);\n if (!config) {\n throw new Error(`Mailer \"${options.mailer}\" not found in configuration`);\n }\n return config;\n }\n\n return getDefaultMailConfig();\n}\n\n/**\n * Reset all configurations (useful for testing)\n */\nexport function resetMailConfig(): void {\n currentMode = \"production\";\n mailersConfig = {};\n}\n"],"mappings":";;;;AAKA,MAAM,wBAAqD;CACzD,QAAQ;CACR,KAAK;CACL,QAAQ;AACV;;;;AAKA,IAAI,cAAwB;;;;AAK5B,IAAI,gBAA+B,CAAC;;;;;;;;;;;;;;;;;;;AAoBpC,SAAgB,YAAY,MAAsB;CAChD,cAAc;A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cesContent":["import { config } from \"../config\";\nimport { environment } from \"../utils/environment\";\nimport type { MailConfigurations, MailersConfig, MailMode, SMTPConfigurations } from \"./types\";\n\n/**\n * Default mail configurations\n */\nconst defaultConfigurations: Partial<SMTPConfigurations> = {\n tls: true,\n driver: \"smtp\",\n};\n\n/**\n * Merge defaults into an SMTP config.\n * `secure` is derived from the port when not set explicitly:\n * 465 uses implicit TLS, every other port (e.g. 587) uses STARTTLS.\n */\nfunction withSmtpDefaults(config: MailConfigurations): SMTPConfigurations {\n const merged = { ...defaultConfigurations, ...config } as SMTPConfigurations;\n\n if (merged.secure === undefined) {\n merged.secure = Number(merged.port) === 465;\n }\n\n return merged;\n}\n\n/**\n * Mode set explicitly through `setMailMode`; when undefined the mode is\n * derived from the environment.\n */\nlet explicitMode: MailMode | undefined;\n\n/**\n * Registered mailers configuration\n */\nlet mailersConfig: MailersConfig = {};\n\n/**\n * Set the mail mode\n *\n * @param mode \"production\" | \"development\" | \"test\"\n *\n * - **production**: Actually sends emails via SMTP\n * - **development**: Logs emails to console without sending\n * - **test**: Captures emails to test mailbox for assertions\n *\n * @example\n * ```typescript\n * // In test setup\n * setMailMode(\"test\");\n *\n * // In development\n * setMailMode(\"development\");\n * ```\n */\nexport function setMailMode(mode: MailMode): void {\n explicitMode = mode;\n}\n\n/**\n * Get the current mail mode\n */\nexport function getMailMode(): MailMode {\n if (explicitMode) return explicitMode;\n\n // Development and test never send real mail unless `mail.sendInDevelopment` is true\n if (environment() !== \"production\" && config.key(\"mail.sendInDevelopment\") !== true) {\n return \"development\";\n }\n\n return \"production\";\n}\n\n/**\n * Check if in production mode\n */\nexport function isProductionMode(): boolean {\n return getMailMode() === \"production\";\n}\n\n/**\n * Check if in development mode\n */\nexport function isDevelopmentMode(): boolean {\n return getMailMode() === \"development\";\n}\n\n/**\n * Check if in test mode\n */\nexport function isTestMode(): boolean {\n return getMailMode() === \"test\";\n}\n\n/**\n * Set mail configurations\n *\n * Supports both simple config and named mailers.\n *\n * @example\n * ```typescript\n * // Simple config (sets as default)\n * setMailConfigurations({\n * host: \"smtp.gmail.com\",\n * port: 587,\n * username: \"...\",\n * password: \"...\",\n * });\n *\n * // Named mailers\n * setMailConfigurations({\n * default: { host: \"smtp.sendgrid.net\", ... },\n * mailers: {\n * marketing: { host: \"smtp.mailchimp.com\", ... },\n * transactional: { host: \"smtp.postmark.com\", ... },\n * },\n * });\n * ```\n */\nexport function setMailConfigurations(config: MailConfigurations | MailersConfig): void {\n // Check if it's a MailersConfig (has 'default' or 'mailers' key)\n if (\"default\" in config || \"mailers\" in config) {\n mailersConfig = config as MailersConfig;\n } else {\n // Simple config - set as default\n mailersConfig = {\n default: config as MailConfigurations,\n };\n }\n}\n\nexport function getDefaultMailConfig(): MailConfigurations {\n const config = mailersConfig.default;\n if (!config) return {} as MailConfigurations;\n if (\"driver\" in config && config.driver === \"ses\") return config;\n\n return withSmtpDefaults(config);\n}\n\n/**\n * Get a named mailer configuration\n */\nexport function getMailerConfig(name: string): MailConfigurations | undefined {\n if (name === \"default\") {\n return getDefaultMailConfig();\n }\n\n const config = mailersConfig.mailers?.[name];\n if (!config) {\n return undefined;\n }\n\n if (\"driver\" in config && config.driver === \"ses\") return config;\n\n return withSmtpDefaults(config);\n}\n\n/**\n * Resolve configuration from options\n * Priority: config > mailer > default\n */\nexport function resolveMailConfig(options: {\n config?: MailConfigurations;\n mailer?: string;\n}): MailConfigurations {\n if (options.config) {\n // SES config passes through as-is, no defaultConfigurations merge\n if (\"driver\" in options.config && options.config.driver === \"ses\") {\n return options.config;\n }\n\n return withSmtpDefaults(options.config);\n }\n\n if (options.mailer) {\n const config = getMailerConfig(options.mailer);\n if (!config) {\n throw new Error(`Mailer \"${options.mailer}\" not found in configuration`);\n }\n return config;\n }\n\n return getDefaultMailConfig();\n}\n\n/**\n * Reset all configurations (useful for testing)\n */\nexport function resetMailConfig(): void {\n explicitMode = undefined;\n mailersConfig = {};\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,wBAAqD;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AQ,OAAO,WAAW,OAC1D,OAAO,QAAQ;EAGjB,OAAO,iBAAiB,QAAQ,MAAM;CACxC;CAEA,IAAI,QAAQ,QAAQ;EAClB,MAAM,SAAS,gBAAgB,QAAQ,MAAM;EAC7C,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,WAAW,QAAQ,OAAO,6BAA6B;EAEzE,OAAO;CACT;CAEA,OAAO,qBAAqB;AAC9B;;;;AAKA,SAAgB,kBAAwB;CACtC,eAAe;CACf,gBAAgB,CAAC;AACnB"}
@@ -26,12 +26,15 @@ function createHtmlPage(html) {
26
26
  async function renderReactMail(element) {
27
27
  const React = await import("react");
28
28
  const reactElement = typeof element === "function" ? React.createElement(element) : element;
29
+ let render;
29
30
  try {
30
- const { render } = await import("@react-email/render");
31
- return await render(reactElement);
32
- } catch {
31
+ ({render} = await import("@react-email/render"));
32
+ } catch (error) {
33
+ const code = error?.code;
34
+ if (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND") throw error;
33
35
  return createHtmlPage(renderReact(reactElement));
34
36
  }
37
+ return await render(reactElement);
35
38
  }
36
39
 
37
40
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"react-mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/react-mail.ts"],"sourcesContent":["import type React from \"react\";\nimport { renderReact } from \"../react\";\n\n/**\n * Create a complete HTML page from rendered content\n */\nfunction createHtmlPage(html: string): string {\n const styles: string[] = [];\n const links: string[] = [];\n\n const body = html.replace(/<style.*?<\\/style>|<link.*?>/gims, (match: string) => {\n if (match.startsWith(\"<style\")) {\n styles.push(match);\n } else {\n links.push(match);\n }\n return \"\";\n });\n\n const head = `<head>${links.join(\"\")}${styles.join(\"\")}</head>`;\n\n return `<!doctype html><html>${head}<body>${body}</body></html>`;\n}\n\n/**\n * Render a React element to HTML for email\n *\n * - Uses @react-email/render when installed (full react-email pipeline)\n * - Falls back to react-dom/server renderToStaticMarkup otherwise\n *\n * **Note:** This function requires React packages to be installed.\n * Install them with: `warlock add react` or `npm install react react-dom`\n */\nexport async function renderReactMail(\n element: React.ReactElement | React.ComponentType,\n): Promise<string> {\n const React = await import(\"react\");\n const reactElement = typeof element === \"function\" ? React.createElement(element) : element;\n\n try {\n const { render } = await import(\"@react-email/render\");\n return await render(reactElement as React.ReactElement);\n } catch {\n // @react-email/render not installed — graceful fallback\n const content = renderReact(reactElement);\n return createHtmlPage(content);\n }\n}\n"],"mappings":";;;;;;AAMA,SAAS,eAAe,MAAsB;CAC5C,MAAM,SAAmB,CAAC;CAC1B,MAAM,QAAkB,CAAC;CAEzB,MAAM,OAAO,KAAK,QAAQ,qCAAqC,UAAkB;EAC/E,IAAI,MAAM,WAAW,QAAQ,GAC3B,OAAO,KAAK,KAAK;OAEjB,MAAM,KAAK,KAAK;EAElB,OAAO;CACT,CAAC;CAID,OAAO,wBAAwB,SAFT,MAAM,KAAK,EAAE,IAAI,OAAO,KAAK,EAAE,EAAE,SAEnB,QAAQ,KAAK;AACnD;;;;;;;;;;AAWA,eAAsB,gBACpB,SACiB;CACjB,MAAM,QAAQ,MAAM,OAAO;CAC3B,MAAM,eAAe,OAAO,YAAY,aAAa,MAAM,cAAc,OAAO,IAAI;CAEpF,IAAI;EACF,MAAM,EAAE,WAAW,MAAM,OAAO;EAChC,OAAO,MAAM,OAAO,YAAkC;CACxD,QAAQ;EAGN,OAAO,eADS,YAAY,YACA,CAAC;CAC/B;AACF"}
1
+ {"version":3,"file":"react-mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/react-mail.ts"],"sourcesContent":["import type React from \"react\";\nimport { renderReact } from \"../react\";\n\n/**\n * Create a complete HTML page from rendered content\n */\nfunction createHtmlPage(html: string): string {\n const styles: string[] = [];\n const links: string[] = [];\n\n const body = html.replace(/<style.*?<\\/style>|<link.*?>/gims, (match: string) => {\n if (match.startsWith(\"<style\")) {\n styles.push(match);\n } else {\n links.push(match);\n }\n return \"\";\n });\n\n const head = `<head>${links.join(\"\")}${styles.join(\"\")}</head>`;\n\n return `<!doctype html><html>${head}<body>${body}</body></html>`;\n}\n\n/**\n * Render a React element to HTML for email\n *\n * - Uses @react-email/render when installed (full react-email pipeline)\n * - Falls back to react-dom/server renderToStaticMarkup otherwise\n *\n * **Note:** This function requires React packages to be installed.\n * Install them with: `warlock add react` or `npm install react react-dom`\n */\nexport async function renderReactMail(\n element: React.ReactElement | React.ComponentType,\n): Promise<string> {\n const React = await import(\"react\");\n const reactElement = typeof element === \"function\" ? React.createElement(element) : element;\n\n let render: typeof import(\"@react-email/render\").render;\n\n try {\n ({ render } = await import(\"@react-email/render\"));\n } catch (error) {\n const code = (error as { code?: string } | null)?.code;\n\n if (code !== \"ERR_MODULE_NOT_FOUND\" && code !== \"MODULE_NOT_FOUND\") {\n throw error;\n }\n\n // @react-email/render not installed — graceful fallback\n const content = renderReact(reactElement);\n return createHtmlPage(content);\n }\n\n // A throwing component must surface its real error, not fall back silently\n return await render(reactElement as React.ReactElement);\n}\n"],"mappings":";;;;;;AAMA,SAAS,eAAe,MAAsB;CAC5C,MAAM,SAAmB,CAAC;CAC1B,MAAM,QAAkB,CAAC;CAEzB,MAAM,OAAO,KAAK,QAAQ,qCAAqC,UAAkB;EAC/E,IAAI,MAAM,WAAW,QAAQ,GAC3B,OAAO,KAAK,KAAK;OAEjB,MAAM,KAAK,KAAK;EAElB,OAAO;CACT,CAAC;CAID,OAAO,wBAAwB,SAFT,MAAM,KAAK,EAAE,IAAI,OAAO,KAAK,EAAE,EAAE,SAEnB,QAAQ,KAAK;AACnD;;;;;;;;;;AAWA,eAAsB,gBACpB,SACiB;CACjB,MAAM,QAAQ,MAAM,OAAO;CAC3B,MAAM,eAAe,OAAO,YAAY,aAAa,MAAM,cAAc,OAAO,IAAI;CAEpF,IAAI;CAEJ,IAAI;EACF,CAAC,CAAE,UAAW,MAAM,OAAO;CAC7B,SAAS,OAAO;EACd,MAAM,OAAQ,OAAoC;EAElD,IAAI,SAAS,0BAA0B,SAAS,oBAC9C,MAAM;EAKR,OAAO,eADS,YAAY,YACA,CAAC;CAC/B;CAGA,OAAO,MAAM,OAAO,YAAkC;AACxD"}
@@ -1 +1 @@
1
- {"version":3,"file":"send-mail.d.mts","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"mappings":";;;;;AAwPA;;;;;;;;;;;;;AAAwE;;;;;;;;;;;;;;;iBAAlD,QAAA,CAAS,OAAA,EAAS,WAAA,GAAc,OAAA,CAAQ,UAAA"}
1
+ {"version":3,"file":"send-mail.d.mts","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"mappings":";;;;;AA2QA;;;;;;;;;;;;;AAAwE;;;;;;;;;;;;;;;iBAAlD,QAAA,CAAS,OAAA,EAAS,WAAA,GAAc,OAAA,CAAQ,UAAA"}
@@ -9,13 +9,6 @@ import { readFile } from "node:fs/promises";
9
9
 
10
10
  //#region ../core/src/mail/send-mail.ts
11
11
  /**
12
- * Normalize email address to string
13
- */
14
- function addressToString(address) {
15
- if (typeof address === "string") return address;
16
- return `"${address.name}" <${address.address}>`;
17
- }
18
- /**
19
12
  * Normalize recipients to array
20
13
  */
21
14
  function normalizeRecipients(recipients) {
@@ -83,7 +76,7 @@ async function resolveAttachment(attachment) {
83
76
  async function buildNodemailerOptions(normalized) {
84
77
  const options = {
85
78
  to: normalized.to,
86
- from: addressToString(normalized.from),
79
+ from: normalized.from,
87
80
  subject: normalized.subject,
88
81
  priority: mapPriority(normalized.priority)
89
82
  };
@@ -103,6 +96,38 @@ async function buildNodemailerOptions(normalized) {
103
96
  return options;
104
97
  }
105
98
  /**
99
+ * Map a send failure to a MailError code, preferring nodemailer's `code` / `responseCode`
100
+ */
101
+ function detectErrorCode(error) {
102
+ if (error instanceof MailError) return error.code;
103
+ const { code, responseCode } = error ?? {};
104
+ if (code === "EAUTH" || responseCode === 535 || responseCode === 534) return "AUTH_ERROR";
105
+ if ([
106
+ "ECONNECTION",
107
+ "ECONNREFUSED",
108
+ "ENOTFOUND",
109
+ "ESOCKET"
110
+ ].includes(code)) return "CONNECTION_ERROR";
111
+ if ([
112
+ "ETIMEDOUT",
113
+ "ETIMEOUT",
114
+ "ECONNECTIONTIMEOUT"
115
+ ].includes(code)) return "TIMEOUT";
116
+ if (code === "EENVELOPE") return "INVALID_ADDRESS";
117
+ if (responseCode && [
118
+ 421,
119
+ 450,
120
+ 451,
121
+ 452
122
+ ].includes(responseCode)) return "RATE_LIMIT";
123
+ const message = error instanceof Error ? error.message : "";
124
+ if (message.includes("ECONNREFUSED") || message.includes("ENOTFOUND")) return "CONNECTION_ERROR";
125
+ if (message.includes("authentication") || message.includes("auth")) return "AUTH_ERROR";
126
+ if (message.includes("timeout") || message.includes("ETIMEDOUT")) return "TIMEOUT";
127
+ if (message.includes("rate") || message.includes("limit")) return "RATE_LIMIT";
128
+ return "UNKNOWN";
129
+ }
130
+ /**
106
131
  * Run per-mail event handler
107
132
  */
108
133
  async function runMailEvent(handler, ...args) {
@@ -226,29 +251,25 @@ async function sendMail(options) {
226
251
  const output = await mailer.sendMail(nodemailerOptions);
227
252
  const accepted = output.accepted || (output.messageId ? normalized.to : []);
228
253
  const rejected = output.rejected || [];
254
+ if (accepted.length === 0) throw new MailError(`All recipients were rejected: ${rejected.join(", ")}`, "REJECTED");
229
255
  const result = {
230
- success: accepted.length > 0,
256
+ success: true,
231
257
  messageId: output.messageId,
232
258
  accepted,
233
259
  rejected,
234
260
  response: output.response,
235
261
  envelope: output.envelope
236
262
  };
237
- if (result.success) {
238
- log.success(`mail.${driver}`, "sent", `Mail sent successfully (ID: ${result.messageId})`);
239
- await runMailEvent(options.onSuccess, options, result);
240
- await triggerEvents(mailId, "success", options, result);
241
- } else log.warn(`mail.${driver}`, "partial", `Mail partially rejected: ${rejected.join(", ")}`);
263
+ if (rejected.length > 0) log.warn(`mail.${driver}`, "partial", `Mail partially rejected: ${rejected.join(", ")}`);
264
+ log.success(`mail.${driver}`, "sent", `Mail sent successfully (ID: ${result.messageId})`);
265
+ await runMailEvent(options.onSuccess, options, result);
266
+ await triggerEvents(mailId, "success", options, result);
242
267
  await runMailEvent(options.onSent, options, result, null);
243
268
  await triggerEvents(mailId, "sent", options, result, null);
244
269
  return result;
245
270
  } catch (error) {
246
271
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
247
- let code = "UNKNOWN";
248
- if (errorMessage.includes("ECONNREFUSED") || errorMessage.includes("ENOTFOUND")) code = "CONNECTION_ERROR";
249
- else if (errorMessage.includes("authentication") || errorMessage.includes("auth")) code = "AUTH_ERROR";
250
- else if (errorMessage.includes("timeout") || errorMessage.includes("ETIMEDOUT")) code = "TIMEOUT";
251
- else if (errorMessage.includes("rate") || errorMessage.includes("limit")) code = "RATE_LIMIT";
272
+ const code = detectErrorCode(error);
252
273
  const mailError = new MailError(`Failed to send mail: ${errorMessage}`, code, error instanceof Error ? error : void 0);
253
274
  log.error(`mail.${driver}`, "error", mailError.message);
254
275
  await runMailEvent(options.onError, options, mailError);
@@ -1 +1 @@
1
- {"version":3,"file":"send-mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Options as NodemailerOptions } from \"nodemailer/lib/mailer\";\nimport { isDevelopmentMode, isTestMode, resolveMailConfig } from \"./config\";\nimport { MAIL_EVENTS, generateMailId, mailEvents } from \"./events\";\nimport { getMailer } from \"./mailer-pool\";\nimport { renderReactMail } from \"./react-mail\";\nimport { captureMail } from \"./test-mailbox\";\nimport {\n MailError,\n type CapturedMail,\n type MailAddress,\n type MailAttachment,\n type MailOptions,\n type MailPriority,\n type MailResult,\n type NormalizedMail,\n} from \"./types\";\n\n/**\n * Normalize email address to string\n */\nfunction addressToString(address: MailAddress): string {\n if (typeof address === \"string\") {\n return address;\n }\n\n return `\"${address.name}\" <${address.address}>`;\n}\n\n/**\n * Normalize recipients to array\n */\nfunction normalizeRecipients(recipients: string | string[] | undefined): string[] {\n if (!recipients) {\n return [];\n }\n\n return Array.isArray(recipients) ? recipients : [recipients];\n}\n\n/**\n * Map priority to nodemailer format\n */\nfunction mapPriority(priority: MailPriority): \"high\" | \"normal\" | \"low\" {\n return priority;\n}\n\n/**\n * Normalize mail options to internal format\n */\nfunction normalizeMail(options: MailOptions): NormalizedMail {\n const config = resolveMailConfig(options);\n\n return {\n to: normalizeRecipients(options.to),\n cc: normalizeRecipients(options.cc),\n bcc: normalizeRecipients(options.bcc),\n replyTo: options.replyTo,\n from: options.from || config.from || { name: \"No Reply\", address: \"noreply@localhost\" },\n subject: options.subject,\n html: options.html,\n text: options.text,\n attachments: options.attachments || [],\n priority: options.priority || \"normal\",\n headers: options.headers || {},\n tags: options.tags || [],\n correlationId: options.correlationId,\n config,\n };\n}\n\n/**\n * Resolve attachment - read file if path is provided\n */\nasync function resolveAttachment(attachment: MailAttachment): Promise<{\n filename: string;\n content: Buffer | string;\n contentType?: string;\n encoding?: string;\n cid?: string;\n}> {\n // If path is provided, read the file\n if (attachment.path) {\n try {\n const content = await readFile(attachment.path);\n return {\n filename: attachment.filename,\n content,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n } catch (error) {\n throw new MailError(\n `Failed to read attachment file \"${attachment.path}\": ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"CONFIG_ERROR\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n // Already has content\n return {\n filename: attachment.filename,\n content: attachment.content!,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n}\n\n/**\n * Build nodemailer options from normalized mail\n */\nasync function buildNodemailerOptions(normalized: NormalizedMail): Promise<NodemailerOptions> {\n const options: NodemailerOptions = {\n to: normalized.to,\n from: addressToString(normalized.from),\n subject: normalized.subject,\n priority: mapPriority(normalized.priority),\n };\n\n if (normalized.cc.length > 0) {\n options.cc = normalized.cc;\n }\n\n if (normalized.bcc.length > 0) {\n options.bcc = normalized.bcc;\n }\n\n if (normalized.replyTo) {\n options.replyTo = normalized.replyTo;\n }\n\n if (normalized.html) {\n options.html = normalized.html;\n }\n\n if (normalized.text) {\n options.text = normalized.text;\n }\n\n if (normalized.attachments.length > 0) {\n // Resolve all attachments (read files if needed)\n const resolvedAttachments = await Promise.all(\n normalized.attachments.map((att) => resolveAttachment(att as MailAttachment)),\n );\n\n options.attachments = resolvedAttachments.map((att) => ({\n filename: att.filename,\n content: att.content,\n contentType: att.contentType,\n encoding: att.encoding,\n cid: att.cid,\n }));\n }\n\n if (Object.keys(normalized.headers).length > 0) {\n options.headers = normalized.headers;\n }\n\n return options;\n}\n\n/**\n * Run per-mail event handler\n */\nasync function runMailEvent<T extends (...args: any[]) => any>(\n handler: T | undefined,\n ...args: Parameters<T>\n): Promise<ReturnType<T> | undefined> {\n if (!handler) {\n return undefined;\n }\n\n try {\n return await handler(...args);\n } catch (error) {\n log.error(\"mail\", \"event\", `Per-mail event handler error: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Trigger both global and mail-specific events\n */\nasync function triggerEvents(\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n ...args: any[]\n): Promise<any[]> {\n try {\n // Trigger global event (e.g., mail.success)\n const globalEventName =\n event === \"beforeSending\"\n ? \"BEFORE_SENDING\"\n : event === \"sent\"\n ? \"SENT\"\n : event === \"success\"\n ? \"SUCCESS\"\n : \"ERROR\";\n\n const globalResults = await mailEvents.trigger(\n globalEventName as keyof typeof MAIL_EVENTS,\n ...args,\n );\n\n // Trigger mail-specific event (e.g., mail.$id.success)\n const specificResults = await mailEvents.triggerForMail(mailId, event, ...args);\n\n return [...(globalResults || []), ...(specificResults || [])];\n } catch (error) {\n log.error(\"mail\", \"event\", `Event handler error: ${error}`);\n return [];\n }\n}\n\n/**\n * Send an email\n *\n * @param options Mail options including recipients, content, and configuration\n * @returns Result containing success status, message ID, and accepted/rejected recipients\n *\n * @example\n * ```typescript\n * // Basic usage\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n *\n * // With React component\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * component: <WelcomeEmail name=\"John\" />,\n * });\n *\n * // Track specific mail with events\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => {\n * console.log(\"This specific mail was sent!\");\n * });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\nexport async function sendMail(options: MailOptions): Promise<MailResult> {\n // Generate or use provided mail ID\n const mailId = options.id || generateMailId();\n\n // Render React component if provided\n if (options.component) {\n try {\n options.html = await renderReactMail(options.component);\n } catch (error) {\n const mailError = new MailError(\n `Failed to render React component: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"RENDER_ERROR\",\n error instanceof Error ? error : undefined,\n );\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n\n throw mailError;\n }\n }\n\n // Normalize mail\n const normalized = normalizeMail(options);\n const driver = normalized.config.driver || \"smtp\";\n\n // Run beforeSending event (per-mail, global, and mail-specific)\n const beforeResult = await runMailEvent(options.beforeSending, options);\n const globalBeforeResults = await triggerEvents(mailId, \"beforeSending\", options);\n\n // If any returns false, cancel sending\n if (beforeResult === false || globalBeforeResults.some((r) => r === false)) {\n log.info(`mail.${driver}`, \"cancelled\", \"Mail sending cancelled by beforeSending event\");\n\n const result: MailResult = {\n success: false,\n accepted: [],\n rejected: normalized.to,\n response: \"Cancelled by beforeSending event\",\n };\n\n return result;\n }\n\n // Test mode - capture without sending\n if (isTestMode()) {\n log.info(`mail.${driver}`, \"test\", `[TEST MODE] Captured mail to: ${normalized.to.join(\", \")}`);\n\n const result: MailResult = {\n success: true,\n messageId: `test-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Test mode - mail captured\",\n };\n\n const captured: CapturedMail = {\n options,\n normalized,\n timestamp: new Date(),\n result,\n };\n\n captureMail(captured);\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Development mode - log without sending\n if (isDevelopmentMode()) {\n log.info(`mail.${driver}`, \"dev\", `[DEV MODE] Would send mail to: ${normalized.to.join(\", \")}`);\n log.info(`mail.${driver}`, \"dev\", `Subject: ${normalized.subject}`);\n\n if (normalized.html) {\n log.info(`mail.${driver}`, \"dev\", `HTML length: ${normalized.html.length} chars`);\n }\n\n const result: MailResult = {\n success: true,\n messageId: `dev-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Development mode - mail logged\",\n };\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Production mode - actually send\n try {\n const config = resolveMailConfig(options);\n const mailer = await getMailer(config);\n const nodemailerOptions = await buildNodemailerOptions(normalized);\n\n log.info(`mail.${driver}`, \"send\", `Sending mail to: ${normalized.to.join(\", \")}`);\n\n const output = await mailer.sendMail(nodemailerOptions);\n\n const accepted = output.accepted || (output.messageId ? normalized.to : []);\n const rejected = output.rejected || [];\n\n const result: MailResult = {\n success: accepted.length > 0,\n messageId: output.messageId,\n accepted: accepted as string[],\n rejected: rejected as string[],\n response: output.response,\n envelope: output.envelope,\n };\n\n if (result.success) {\n log.success(`mail.${driver}`, \"sent\", `Mail sent successfully (ID: ${result.messageId})`);\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n } else {\n log.warn(`mail.${driver}`, \"partial\", `Mail partially rejected: ${rejected.join(\", \")}`);\n }\n\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n let code: MailError[\"code\"] = \"UNKNOWN\";\n\n // Detect error type\n if (errorMessage.includes(\"ECONNREFUSED\") || errorMessage.includes(\"ENOTFOUND\")) {\n code = \"CONNECTION_ERROR\";\n } else if (errorMessage.includes(\"authentication\") || errorMessage.includes(\"auth\")) {\n code = \"AUTH_ERROR\";\n } else if (errorMessage.includes(\"timeout\") || errorMessage.includes(\"ETIMEDOUT\")) {\n code = \"TIMEOUT\";\n } else if (errorMessage.includes(\"rate\") || errorMessage.includes(\"limit\")) {\n code = \"RATE_LIMIT\";\n }\n\n const mailError = new MailError(\n `Failed to send mail: ${errorMessage}`,\n code,\n error instanceof Error ? error : undefined,\n );\n\n log.error(`mail.${driver}`, \"error\", mailError.message);\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n await runMailEvent(options.onSent, options, null, mailError);\n await triggerEvents(mailId, \"sent\", options, null, mailError);\n\n throw mailError;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAS,gBAAgB,SAA8B;CACrD,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,OAAO,IAAI,QAAQ,KAAK,KAAK,QAAQ,QAAQ;AAC/C;;;;AAKA,SAAS,oBAAoB,YAAqD;CAChF,IAAI,CAAC,YACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAC7D;;;;AAKA,SAAS,YAAY,UAAmD;CACtE,OAAO;AACT;;;;AAKA,SAAS,cAAc,SAAsC;CAC3D,MAAM,SAAS,kBAAkB,OAAO;CAExC,OAAO;EACL,IAAI,oBAAoB,QAAQ,EAAE;EAClC,IAAI,oBAAoB,QAAQ,EAAE;EAClC,KAAK,oBAAoB,QAAQ,GAAG;EACpC,SAAS,QAAQ;EACjB,MAAM,QAAQ,QAAQ,OAAO,QAAQ;GAAE,MAAM;GAAY,SAAS;EAAoB;EACtF,SAAS,QAAQ;EACjB,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,aAAa,QAAQ,eAAe,CAAC;EACrC,UAAU,QAAQ,YAAY;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QAAQ,MACnC;EAEA,IAAI,MAAM,QAAQ,UAAU,SAAS,UAAU,OAAO;EAEtD,MAAM,aAAa,QAAQ,SAAS,SAAS,SAAS;EACtD,MAAM,cAAc,QAAQ,SAAS,SAAS,SAAS;EACvD,MAAM,aAAa,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAC3D,MAAM,cAAc,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAE5D,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"send-mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Options as NodemailerOptions } from \"nodemailer/lib/mailer\";\nimport { isDevelopmentMode, isTestMode, resolveMailConfig } from \"./config\";\nimport { MAIL_EVENTS, generateMailId, mailEvents } from \"./events\";\nimport { getMailer } from \"./mailer-pool\";\nimport { renderReactMail } from \"./react-mail\";\nimport { captureMail } from \"./test-mailbox\";\nimport {\n MailError,\n type CapturedMail,\n type MailAttachment,\n type MailOptions,\n type MailPriority,\n type MailResult,\n type NormalizedMail,\n} from \"./types\";\n\n/**\n * Normalize recipients to array\n */\nfunction normalizeRecipients(recipients: string | string[] | undefined): string[] {\n if (!recipients) {\n return [];\n }\n\n return Array.isArray(recipients) ? recipients : [recipients];\n}\n\n/**\n * Map priority to nodemailer format\n */\nfunction mapPriority(priority: MailPriority): \"high\" | \"normal\" | \"low\" {\n return priority;\n}\n\n/**\n * Normalize mail options to internal format\n */\nfunction normalizeMail(options: MailOptions): NormalizedMail {\n const config = resolveMailConfig(options);\n\n return {\n to: normalizeRecipients(options.to),\n cc: normalizeRecipients(options.cc),\n bcc: normalizeRecipients(options.bcc),\n replyTo: options.replyTo,\n from: options.from || config.from || { name: \"No Reply\", address: \"noreply@localhost\" },\n subject: options.subject,\n html: options.html,\n text: options.text,\n attachments: options.attachments || [],\n priority: options.priority || \"normal\",\n headers: options.headers || {},\n tags: options.tags || [],\n correlationId: options.correlationId,\n config,\n };\n}\n\n/**\n * Resolve attachment - read file if path is provided\n */\nasync function resolveAttachment(attachment: MailAttachment): Promise<{\n filename: string;\n content: Buffer | string;\n contentType?: string;\n encoding?: string;\n cid?: string;\n}> {\n // If path is provided, read the file\n if (attachment.path) {\n try {\n const content = await readFile(attachment.path);\n return {\n filename: attachment.filename,\n content,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n } catch (error) {\n throw new MailError(\n `Failed to read attachment file \"${attachment.path}\": ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"CONFIG_ERROR\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n // Already has content\n return {\n filename: attachment.filename,\n content: attachment.content!,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n}\n\n/**\n * Build nodemailer options from normalized mail\n */\nasync function buildNodemailerOptions(normalized: NormalizedMail): Promise<NodemailerOptions> {\n const options: NodemailerOptions = {\n to: normalized.to,\n // nodemailer encodes/escapes {name, address} objects itself\n from: normalized.from,\n subject: normalized.subject,\n priority: mapPriority(normalized.priority),\n };\n\n if (normalized.cc.length > 0) {\n options.cc = normalized.cc;\n }\n\n if (normalized.bcc.length > 0) {\n options.bcc = normalized.bcc;\n }\n\n if (normalized.replyTo) {\n options.replyTo = normalized.replyTo;\n }\n\n if (normalized.html) {\n options.html = normalized.html;\n }\n\n if (normalized.text) {\n options.text = normalized.text;\n }\n\n if (normalized.attachments.length > 0) {\n // Resolve all attachments (read files if needed)\n const resolvedAttachments = await Promise.all(\n normalized.attachments.map((att) => resolveAttachment(att as MailAttachment)),\n );\n\n options.attachments = resolvedAttachments.map((att) => ({\n filename: att.filename,\n content: att.content,\n contentType: att.contentType,\n encoding: att.encoding,\n cid: att.cid,\n }));\n }\n\n if (Object.keys(normalized.headers).length > 0) {\n options.headers = normalized.headers;\n }\n\n return options;\n}\n\n/**\n * Map a send failure to a MailError code, preferring nodemailer's `code` / `responseCode`\n */\nfunction detectErrorCode(error: unknown): MailError[\"code\"] {\n if (error instanceof MailError) {\n return error.code;\n }\n\n const { code, responseCode } = (error ?? {}) as { code?: string; responseCode?: number };\n\n if (code === \"EAUTH\" || responseCode === 535 || responseCode === 534) return \"AUTH_ERROR\";\n\n if ([\"ECONNECTION\", \"ECONNREFUSED\", \"ENOTFOUND\", \"ESOCKET\"].includes(code as string)) {\n return \"CONNECTION_ERROR\";\n }\n\n if ([\"ETIMEDOUT\", \"ETIMEOUT\", \"ECONNECTIONTIMEOUT\"].includes(code as string)) return \"TIMEOUT\";\n if (code === \"EENVELOPE\") return \"INVALID_ADDRESS\";\n if (responseCode && [421, 450, 451, 452].includes(responseCode)) return \"RATE_LIMIT\";\n\n const message = error instanceof Error ? error.message : \"\";\n\n if (message.includes(\"ECONNREFUSED\") || message.includes(\"ENOTFOUND\")) return \"CONNECTION_ERROR\";\n if (message.includes(\"authentication\") || message.includes(\"auth\")) return \"AUTH_ERROR\";\n if (message.includes(\"timeout\") || message.includes(\"ETIMEDOUT\")) return \"TIMEOUT\";\n if (message.includes(\"rate\") || message.includes(\"limit\")) return \"RATE_LIMIT\";\n\n return \"UNKNOWN\";\n}\n\n/**\n * Run per-mail event handler\n */\nasync function runMailEvent<T extends (...args: any[]) => any>(\n handler: T | undefined,\n ...args: Parameters<T>\n): Promise<ReturnType<T> | undefined> {\n if (!handler) {\n return undefined;\n }\n\n try {\n return await handler(...args);\n } catch (error) {\n log.error(\"mail\", \"event\", `Per-mail event handler error: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Trigger both global and mail-specific events\n */\nasync function triggerEvents(\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n ...args: any[]\n): Promise<any[]> {\n try {\n // Trigger global event (e.g., mail.success)\n const globalEventName =\n event === \"beforeSending\"\n ? \"BEFORE_SENDING\"\n : event === \"sent\"\n ? \"SENT\"\n : event === \"success\"\n ? \"SUCCESS\"\n : \"ERROR\";\n\n const globalResults = await mailEvents.trigger(\n globalEventName as keyof typeof MAIL_EVENTS,\n ...args,\n );\n\n // Trigger mail-specific event (e.g., mail.$id.success)\n const specificResults = await mailEvents.triggerForMail(mailId, event, ...args);\n\n return [...(globalResults || []), ...(specificResults || [])];\n } catch (error) {\n log.error(\"mail\", \"event\", `Event handler error: ${error}`);\n return [];\n }\n}\n\n/**\n * Send an email\n *\n * @param options Mail options including recipients, content, and configuration\n * @returns Result containing success status, message ID, and accepted/rejected recipients\n *\n * @example\n * ```typescript\n * // Basic usage\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n *\n * // With React component\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * component: <WelcomeEmail name=\"John\" />,\n * });\n *\n * // Track specific mail with events\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => {\n * console.log(\"This specific mail was sent!\");\n * });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\nexport async function sendMail(options: MailOptions): Promise<MailResult> {\n // Generate or use provided mail ID\n const mailId = options.id || generateMailId();\n\n // Render React component if provided\n if (options.component) {\n try {\n options.html = await renderReactMail(options.component);\n } catch (error) {\n const mailError = new MailError(\n `Failed to render React component: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"RENDER_ERROR\",\n error instanceof Error ? error : undefined,\n );\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n\n throw mailError;\n }\n }\n\n // Normalize mail\n const normalized = normalizeMail(options);\n const driver = normalized.config.driver || \"smtp\";\n\n // Run beforeSending event (per-mail, global, and mail-specific)\n const beforeResult = await runMailEvent(options.beforeSending, options);\n const globalBeforeResults = await triggerEvents(mailId, \"beforeSending\", options);\n\n // If any returns false, cancel sending\n if (beforeResult === false || globalBeforeResults.some((r) => r === false)) {\n log.info(`mail.${driver}`, \"cancelled\", \"Mail sending cancelled by beforeSending event\");\n\n const result: MailResult = {\n success: false,\n accepted: [],\n rejected: normalized.to,\n response: \"Cancelled by beforeSending event\",\n };\n\n return result;\n }\n\n // Test mode - capture without sending\n if (isTestMode()) {\n log.info(`mail.${driver}`, \"test\", `[TEST MODE] Captured mail to: ${normalized.to.join(\", \")}`);\n\n const result: MailResult = {\n success: true,\n messageId: `test-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Test mode - mail captured\",\n };\n\n const captured: CapturedMail = {\n options,\n normalized,\n timestamp: new Date(),\n result,\n };\n\n captureMail(captured);\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Development mode - log without sending\n if (isDevelopmentMode()) {\n log.info(`mail.${driver}`, \"dev\", `[DEV MODE] Would send mail to: ${normalized.to.join(\", \")}`);\n log.info(`mail.${driver}`, \"dev\", `Subject: ${normalized.subject}`);\n\n if (normalized.html) {\n log.info(`mail.${driver}`, \"dev\", `HTML length: ${normalized.html.length} chars`);\n }\n\n const result: MailResult = {\n success: true,\n messageId: `dev-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Development mode - mail logged\",\n };\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Production mode - actually send\n try {\n const config = resolveMailConfig(options);\n const mailer = await getMailer(config);\n const nodemailerOptions = await buildNodemailerOptions(normalized);\n\n log.info(`mail.${driver}`, \"send\", `Sending mail to: ${normalized.to.join(\", \")}`);\n\n const output = await mailer.sendMail(nodemailerOptions);\n\n const accepted = output.accepted || (output.messageId ? normalized.to : []);\n const rejected = output.rejected || [];\n\n if (accepted.length === 0) {\n throw new MailError(\n `All recipients were rejected: ${(rejected as string[]).join(\", \")}`,\n \"REJECTED\",\n );\n }\n\n const result: MailResult = {\n success: true,\n messageId: output.messageId,\n accepted: accepted as string[],\n rejected: rejected as string[],\n response: output.response,\n envelope: output.envelope,\n };\n\n if (rejected.length > 0) {\n log.warn(`mail.${driver}`, \"partial\", `Mail partially rejected: ${rejected.join(\", \")}`);\n }\n\n log.success(`mail.${driver}`, \"sent\", `Mail sent successfully (ID: ${result.messageId})`);\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n const code = detectErrorCode(error);\n\n const mailError = new MailError(\n `Failed to send mail: ${errorMessage}`,\n code,\n error instanceof Error ? error : undefined,\n );\n\n log.error(`mail.${driver}`, \"error\", mailError.message);\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n await runMailEvent(options.onSent, options, null, mailError);\n await triggerEvents(mailId, \"sent\", options, null, mailError);\n\n throw mailError;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA,SAAS,oBAAoB,YAAqD;CAChF,IAAI,CAAC,YACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAC7D;;;;AAKA,SAAS,YAAY,UAAmD;CACtE,OAAO;AACT;;;;AAKA,SAAS,cAAc,SAAsC;CAC3D,MAAM,SAAS,kBAAkB,OAAO;CAExC,OAAO;EACL,IAAI,oBAAoB,QAAQ,EAAE;EAClC,IAAI,oBAAoB,QAAQ,EAAE;EAClC,KAAK,oBAAoB,QAAQ,GAAG;EACpC,SAAS,QAAQ;EACjB,MAAM,QAAQ,QAAQ,OAAO,QAAQ;GAAE,MAAM;GAAY,SAAS;EAAoB;EACtF,SAAS,QAAQ;EACjB,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,aAAa,QAAQ,eAAe,CAAC;EACrC,UAAU,QA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SAAS;GACT,WAAW,OAAO;GACR;GACA;GACV,UAAU,OAAO;GACjB,UAAU,OAAO;EACnB;EAEA,IAAI,SAAS,SAAS,GACpB,IAAI,KAAK,QAAQ,UAAU,WAAW,4BAA4B,SAAS,KAAK,IAAI,GAAG;EAGzF,IAAI,QAAQ,QAAQ,UAAU,QAAQ,+BAA+B,OAAO,UAAU,EAAE;EACxF,MAAM,aAAa,QAAQ,WAAW,SAAS,MAAM;EACrD,MAAM,cAAc,QAAQ,WAAW,SAAS,MAAM;EAEtD,MAAM,aAAa,QAAQ,QAAQ,SAAS,QAAQ,IAAI;EACxD,MAAM,cAAc,QAAQ,QAAQ,SAAS,QAAQ,IAAI;EAEzD,OAAO;CACT,SAAS,OAAO;EACd,MAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU;EAC9D,MAAM,OAAO,gBAAgB,KAAK;EAElC,MAAM,YAAY,IAAI,UACpB,wBAAwB,gBACxB,MACA,iBAAiB,QAAQ,QAAQ,MACnC;EAEA,IAAI,MAAM,QAAQ,UAAU,SAAS,UAAU,OAAO;EAEtD,MAAM,aAAa,QAAQ,SAAS,SAAS,SAAS;EACtD,MAAM,cAAc,QAAQ,SAAS,SAAS,SAAS;EACvD,MAAM,aAAa,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAC3D,MAAM,cAAc,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAE5D,MAAM;CACR;AACF"}
@@ -74,6 +74,8 @@ async function runEmitContributions(connectors, context) {
74
74
  * - `external` concatenates and dedupes — it is a set of package names, and
75
75
  * under `singleBundle` each contributor adds its own optional peers.
76
76
  * - `loader` merges per extension, for the same reason as `define`.
77
+ * - `plugins` concatenate in contribution order. They are constructed inside
78
+ * a hook, so this does not reopen the closed-contribution constraint.
77
79
  */
78
80
  function mergeEsbuildPatches(base, patch) {
79
81
  const merged = {
@@ -89,6 +91,7 @@ function mergeEsbuildPatches(base, patch) {
89
91
  ...base.loader,
90
92
  ...patch.loader
91
93
  };
94
+ if (base.plugins || patch.plugins) merged.plugins = [...base.plugins ?? [], ...patch.plugins ?? []];
92
95
  return merged;
93
96
  }
94
97
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"build-contributions.mjs","names":[],"sources":["../../../../../../../core/src/production/build-contributions.ts"],"sourcesContent":["import type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\n\n/**\n * `Error` with the `cause` option typed. Same shim as\n * `application.ts` — lib.es2022 declares `cause` on `ErrorOptions`, but the\n * package still compiles against an older lib in some consumers.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * The only keys a `build` contribution may carry.\n *\n * The runtime half of the closed-contribution constraint: the\n * type already makes `build: { plugins: [...] }` unrepresentable, but a\n * plain `warlock.config.js`, an `as any`, or a connector compiled against an\n * older core all slip past the type. Rejected rather than ignored — the same\n * posture as the `tsconfig` guard in `resolve-build-config`: dropping the key\n * quietly would leave the author believing their plugin ran.\n */\nconst ALLOWED_CONTRIBUTION_KEYS = [\"generate\", \"emit\"] as const;\n\n/**\n * What the generate pass produced, merged across every contributor.\n */\nexport type GenerateContributionsResult = {\n /** Entry lines in contributor order, appended after `./routes` */\n entryImports: string[];\n /** The contributors' esbuild patches, merged into one */\n esbuild: ConnectorEsbuildPatch;\n};\n\n/**\n * Reject a contribution object carrying anything but the two hooks.\n *\n * @throws Error naming the connector and the offending key\n */\nexport function assertClosedContribution(connector: Connector): void {\n const contribution = connector.build;\n\n if (!contribution) return;\n\n for (const key of Object.keys(contribution)) {\n if ((ALLOWED_CONTRIBUTION_KEYS as readonly string[]).includes(key)) continue;\n\n throw new Error(\n `Connector \"${connector.name}\" declares an unsupported build contribution key \"${key}\". ` +\n `A build contribution carries exactly two optional hooks — ` +\n `${ALLOWED_CONTRIBUTION_KEYS.join(\" and \")} — and no data. ` +\n `Anything a hook needs (plugins, pipelines, aliases) must be constructed inside ` +\n `that hook, so it never lands in the connector's static import graph.`,\n );\n }\n}\n\n/**\n * Drain every connector's `generate` hook, in array order, sequentially.\n *\n * Semantics are copied from `Application.runStartupValidators`\n * (`application.ts:304-329`) on purpose: ordered, awaited one at a time, and\n * a throw is rethrown wrapped in an error NAMING the contributor. A\n * contributor failure IS the build failing — that is what makes\n * \"green build, no client bundle\" unrepresentable rather than merely\n * unlikely.\n */\nexport async function runGenerateContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<GenerateContributionsResult> {\n const entryImports: string[] = [];\n let esbuild: ConnectorEsbuildPatch = {};\n\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const generate = connector.build?.generate;\n\n if (!generate) continue;\n\n const result = await runHook(connector, \"generate\", () => generate(context));\n\n if (!result) continue;\n\n if (result.entryImports) {\n entryImports.push(...result.entryImports);\n }\n\n if (result.esbuild) {\n esbuild = mergeEsbuildPatches(esbuild, result.esbuild);\n }\n }\n\n return { entryImports, esbuild };\n}\n\n/**\n * Drain every connector's `emit` hook, in array order, sequentially.\n *\n * Runs after esbuild and before `.warlock/production` is removed, so a hook\n * may still read what `generate` wrote there.\n */\nexport async function runEmitContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<void> {\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const emit = connector.build?.emit;\n\n if (!emit) continue;\n\n await runHook(connector, \"emit\", () => emit(context));\n }\n}\n\n/**\n * Merge two contributor patches. Later wins, except:\n *\n * - `define` merges per key — two contributors defining different\n * `import.meta.env.*` entries must both survive; a wholesale replace would\n * drop one silently.\n * - `external` concatenates and dedupes — it is a set of package names, and\n * under `singleBundle` each contributor adds its own optional peers.\n * - `loader` merges per extension, for the same reason as `define`.\n */\nexport function mergeEsbuildPatches(\n base: ConnectorEsbuildPatch,\n patch: ConnectorEsbuildPatch,\n): ConnectorEsbuildPatch {\n const merged: ConnectorEsbuildPatch = { ...base, ...patch };\n\n if (base.define || patch.define) {\n merged.define = { ...base.define, ...patch.define };\n }\n\n if (base.external || patch.external) {\n merged.external = dedupe([...(base.external ?? []), ...(patch.external ?? [])]);\n }\n\n if (base.loader || patch.loader) {\n merged.loader = { ...base.loader, ...patch.loader };\n }\n\n return merged;\n}\n\n/**\n * Concatenation order preserved — esbuild does not care, but a stable order\n * keeps build output diffable.\n */\nexport function dedupe(values: string[]): string[] {\n return [...new Set(values)];\n}\n\n/**\n * Run one hook and rename its failure after the connector that owns it.\n */\nasync function runHook<Result>(\n connector: Connector,\n hook: \"generate\" | \"emit\",\n run: () => Result | Promise<Result>,\n): Promise<Result> {\n try {\n return await run();\n } catch (error) {\n const cause = error instanceof Error ? error.message : String(error);\n\n throw new ErrorWithCause(\n `Build contribution \"${connector.name}\" failed during ${hook}: ${cause}. ` +\n `The build cannot continue — an artifact this connector was responsible for ` +\n `is missing, and shipping the bundle without it would fail at runtime instead.`,\n { cause: error },\n );\n }\n}\n"],"mappings":";AASA,MAAM,iBAAiB;;;;;;;;;;;AAYvB,MAAM,4BAA4B,CAAC,YAAY,MAAM;;;;;;AAiBrD,SAAgB,yBAAyB,WAA4B;CACnE,MAAM,eAAe,UAAU;CAE/B,IAAI,CAAC,cAAc;CAEnB,KAAK,MAAM,OAAO,OAAO,KAAK,YAAY,GAAG;EAC3C,IAAK,0BAAgD,SAAS,GAAG,GAAG;EAEpE,MAAM,IAAI,MACR,cAAc,UAAU,KAAK,oDAAoD,IAAI,+DAEhF,0BAA0B,KAAK,OAAO,EAAE,oKAG/C;CACF;AACF;;;;;;;;;;;AAYA,eAAsB,yBACpB,YACA,SACsC;CACtC,MAAM,eAAyB,CAAC;CAChC,IAAI,UAAiC,CAAC;CAEtC,KAAK,MAAM,aAAa,YAAY;EAClC,yBAAyB,SAAS;EAElC,MAAM,WAAW,UAAU,OAAO;EAElC,IAAI,CAAC,UAAU;EAEf,MAAM,SAAS,MAAM,QAAQ,WAAW,kBAAkB,SAAS,OAAO,CAAC;EAE3E,IAAI,CAAC,QAAQ;EAEb,IAAI,OAAO,cACT,aAAa,KAAK,GAAG,OAAO,YAAY;EAG1C,IAAI,OAAO,SACT,UAAU,oBAAoB,SAAS,OAAO,OAAO;CAEzD;CAEA,OAAO;EAAE;EAAc;CAAQ;AACjC;;;;;;;AAQA,eAAsB,qBACpB,YACA,SACe;CACf,KAAK,MAAM,aAAa,YAAY;EAClC,yBAAyB,SAAS;EAElC,MAAM,OAAO,UAAU,OAAO;EAE9B,IAAI,CAAC,MAAM;EAEX,MAAM,QAAQ,WAAW,cAAc,KAAK,OAAO,CAAC;CACtD;AACF;;;;;;;;;;;AAYA,SAAgB,oBACd,MACA,OACuB;CACvB,MAAM,SAAgC;EAAE,GAAG;EAAM,GAAG;CAAM;CAE1D,IAAI,KAAK,UAAU,MAAM,QACvB,OAAO,SAAS;EAAE,GAAG,KAAK;EAAQ,GAAG,MAAM;CAAO;CAGpD,IAAI,KAAK,YAAY,MAAM,UACzB,OAAO,WAAW,OAAO,CAAC,GAAI,KAAK,YAAY,CAAC,GAAI,GAAI,MAAM,YAAY,CAAC,CAAE,CAAC;CAGhF,IAAI,KAAK,UAAU,MAAM,QACvB,OAAO,SAAS;EAAE,GAAG,KAAK;EAAQ,GAAG,MAAM;CAAO;CAGpD,OAAO;AACT;;;;;AAMA,SAAgB,OAAO,QAA4B;CACjD,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;;;;AAKA,eAAe,QACb,WACA,MACA,KACiB;CACjB,IAAI;EACF,OAAO,MAAM,IAAI;CACnB,SAAS,OAAO;EACd,MAAM,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAEnE,MAAM,IAAI,eACR,uBAAuB,UAAU,KAAK,kBAAkB,KAAK,IAAI,MAAM,6JAGvE,EAAE,OAAO,MAAM,CACjB;CACF;AACF"}
1
+ {"version":3,"file":"build-contributions.mjs","names":[],"sources":["../../../../../../../core/src/production/build-contributions.ts"],"sourcesContent":["import type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\n\n/**\n * `Error` with the `cause` option typed. Same shim as\n * `application.ts` — lib.es2022 declares `cause` on `ErrorOptions`, but the\n * package still compiles against an older lib in some consumers.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * The only keys a `build` contribution may carry.\n *\n * The runtime half of the closed-contribution constraint: the\n * type already makes `build: { plugins: [...] }` unrepresentable, but a\n * plain `warlock.config.js`, an `as any`, or a connector compiled against an\n * older core all slip past the type. Rejected rather than ignored — the same\n * posture as the `tsconfig` guard in `resolve-build-config`: dropping the key\n * quietly would leave the author believing their plugin ran.\n */\nconst ALLOWED_CONTRIBUTION_KEYS = [\"generate\", \"emit\"] as const;\n\n/**\n * What the generate pass produced, merged across every contributor.\n */\nexport type GenerateContributionsResult = {\n /** Entry lines in contributor order, appended after `./routes` */\n entryImports: string[];\n /** The contributors' esbuild patches, merged into one */\n esbuild: ConnectorEsbuildPatch;\n};\n\n/**\n * Reject a contribution object carrying anything but the two hooks.\n *\n * @throws Error naming the connector and the offending key\n */\nexport function assertClosedContribution(connector: Connector): void {\n const contribution = connector.build;\n\n if (!contribution) return;\n\n for (const key of Object.keys(contribution)) {\n if ((ALLOWED_CONTRIBUTION_KEYS as readonly string[]).includes(key)) continue;\n\n throw new Error(\n `Connector \"${connector.name}\" declares an unsupported build contribution key \"${key}\". ` +\n `A build contribution carries exactly two optional hooks — ` +\n `${ALLOWED_CONTRIBUTION_KEYS.join(\" and \")} — and no data. ` +\n `Anything a hook needs (plugins, pipelines, aliases) must be constructed inside ` +\n `that hook, so it never lands in the connector's static import graph.`,\n );\n }\n}\n\n/**\n * Drain every connector's `generate` hook, in array order, sequentially.\n *\n * Semantics are copied from `Application.runStartupValidators`\n * (`application.ts:304-329`) on purpose: ordered, awaited one at a time, and\n * a throw is rethrown wrapped in an error NAMING the contributor. A\n * contributor failure IS the build failing — that is what makes\n * \"green build, no client bundle\" unrepresentable rather than merely\n * unlikely.\n */\nexport async function runGenerateContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<GenerateContributionsResult> {\n const entryImports: string[] = [];\n let esbuild: ConnectorEsbuildPatch = {};\n\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const generate = connector.build?.generate;\n\n if (!generate) continue;\n\n const result = await runHook(connector, \"generate\", () => generate(context));\n\n if (!result) continue;\n\n if (result.entryImports) {\n entryImports.push(...result.entryImports);\n }\n\n if (result.esbuild) {\n esbuild = mergeEsbuildPatches(esbuild, result.esbuild);\n }\n }\n\n return { entryImports, esbuild };\n}\n\n/**\n * Drain every connector's `emit` hook, in array order, sequentially.\n *\n * Runs after esbuild and before `.warlock/production` is removed, so a hook\n * may still read what `generate` wrote there.\n */\nexport async function runEmitContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<void> {\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const emit = connector.build?.emit;\n\n if (!emit) continue;\n\n await runHook(connector, \"emit\", () => emit(context));\n }\n}\n\n/**\n * Merge two contributor patches. Later wins, except:\n *\n * - `define` merges per key — two contributors defining different\n * `import.meta.env.*` entries must both survive; a wholesale replace would\n * drop one silently.\n * - `external` concatenates and dedupes — it is a set of package names, and\n * under `singleBundle` each contributor adds its own optional peers.\n * - `loader` merges per extension, for the same reason as `define`.\n * - `plugins` concatenate in contribution order. They are constructed inside\n * a hook, so this does not reopen the closed-contribution constraint.\n */\nexport function mergeEsbuildPatches(\n base: ConnectorEsbuildPatch,\n patch: ConnectorEsbuildPatch,\n): ConnectorEsbuildPatch {\n const merged: ConnectorEsbuildPatch = { ...base, ...patch };\n\n if (base.define || patch.define) {\n merged.define = { ...base.define, ...patch.define };\n }\n\n if (base.external || patch.external) {\n merged.external = dedupe([...(base.external ?? []), ...(patch.external ?? [])]);\n }\n\n if (base.loader || patch.loader) {\n merged.loader = { ...base.loader, ...patch.loader };\n }\n\n if (base.plugins || patch.plugins) {\n merged.plugins = [...(base.plugins ?? []), ...(patch.plugins ?? [])];\n }\n\n return merged;\n}\n\n/**\n * Concatenation order preserved — esbuild does not care, but a stable order\n * keeps build output diffable.\n */\nexport function dedupe(values: string[]): string[] {\n return [...new Set(values)];\n}\n\n/**\n * Run one hook and rename its failure after the connector that owns it.\n */\nasync function runHook<Result>(\n connector: Connector,\n hook: \"generate\" | \"emit\",\n run: () => Result | Promise<Result>,\n): Promise<Result> {\n try {\n return await run();\n } catch (error) {\n const cause = error instanceof Error ? error.message : String(error);\n\n throw new ErrorWithCause(\n `Build contribution \"${connector.name}\" failed during ${hook}: ${cause}. ` +\n `The build cannot continue — an artifact this connector was responsible for ` +\n `is missing, and shipping the bundle without it would fail at runtime instead.`,\n { cause: error },\n );\n }\n}\n"],"mappings":";AASA,MAAM,iBAAiB;;;;;;;;;;;AAYvB,MAAM,4BAA4B,CAAC,YAAY,MAAM;;;;;;AAiBrD,SAAgB,yBAAyB,WAA4B;CACnE,MAAM,eAAe,UAAU;CAE/B,IAAI,CAAC,cAAc;CAEnB,KAAK,MAAM,OAAO,OAAO,KAAK,YAAY,GAAG;EAC3C,IAAK,0BAAgD,SAAS,GAAG,GAAG;EAEpE,MAAM,IAAI,MACR,cAAc,UAAU,KAAK,oDAAoD,IAAI,+DAEhF,0BAA0B,KAAK,OAAO,EAAE,oKAG/C;CACF;AACF;;;;;;;;;;;AAYA,eAAsB,yBACpB,YACA,SACsC;CACtC,MAAM,eAAyB,CAAC;CAChC,IAAI,UAAiC,CAAC;CAEtC,KAAK,MAAM,aAAa,YAAY;EAClC,yBAAyB,SAAS;EAElC,MAAM,WAAW,UAAU,OAAO;EAElC,IAAI,CAAC,UAAU;EAEf,MAAM,SAAS,MAAM,QAAQ,WAAW,kBAAkB,SAAS,OAAO,CAAC;EAE3E,IAAI,CAAC,QAAQ;EAEb,IAAI,OAAO,cACT,aAAa,KAAK,GAAG,OAAO,YAAY;EAG1C,IAAI,OAAO,SACT,UAAU,oBAAoB,SAA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
 
3
3
  //#region ../core/src/production/esbuild-plugins.ts
4
+ const esmRequire = createRequire(import.meta.url);
4
5
  const nativeNodeModulesPlugin = {
5
6
  name: "native-node-modules",
6
7
  setup(build) {
@@ -8,7 +9,7 @@ const nativeNodeModulesPlugin = {
8
9
  filter: /\.node$/,
9
10
  namespace: "file"
10
11
  }, (args) => ({
11
- path: __require.resolve(args.path, { paths: [args.resolveDir] }),
12
+ path: esmRequire.resolve(args.path, { paths: [args.resolveDir] }),
12
13
  namespace: "node-file"
13
14
  }));
14
15
  build.onLoad({
@@ -1 +1 @@
1
- {"version":3,"file":"esbuild-plugins.mjs","names":[],"sources":["../../../../../../../core/src/production/esbuild-plugins.ts"],"sourcesContent":["import type { OnLoadArgs, OnResolveArgs, PluginBuild } from \"esbuild\";\n\nexport const nativeNodeModulesPlugin = {\n name: \"native-node-modules\",\n setup(build: PluginBuild) {\n build.onResolve({ filter: /\\.node$/, namespace: \"file\" }, (args: OnResolveArgs) => ({\n path: require.resolve(args.path, { paths: [args.resolveDir] }),\n namespace: \"node-file\",\n }));\n\n build.onLoad({ filter: /.*/, namespace: \"node-file\" }, (args: OnLoadArgs) => ({\n contents: `\n import path from ${JSON.stringify(args.path)}\n try { module.exports = require(path) }\n catch {}\n `,\n }));\n\n build.onResolve({ filter: /\\.node$/, namespace: \"node-file\" }, (args: OnResolveArgs) => ({\n path: args.path,\n namespace: \"file\",\n }));\n\n const opts = build.initialOptions;\n opts.loader = opts.loader || {};\n opts.loader[\".node\"] = \"file\";\n },\n};\n"],"mappings":";;;AAEA,MAAa,0BAA0B;CACrC,MAAM;CACN,MAAM,OAAoB;EACxB,MAAM,UAAU;GAAE,QAAQ;GAAW,WAAW;EAAO,IAAI,UAAyB;GAClF,gBAAc,QAAQ,KAAK,MAAM,EAAE,OAAO,CAAC,KAAK,UAAU,EAAE,CAAC;GAC7D,WAAW;EACb,EAAE;EAEF,MAAM,OAAO;GAAE,QAAQ;GAAM,WAAW;EAAY,IAAI,UAAsB,EAC5E,UAAU;6BACa,KAAK,UAAU,KAAK,IAAI,EAAE;;;UAInD,EAAE;EAEF,MAAM,UAAU;GAAE,QAAQ;GAAW,WAAW;EAAY,IAAI,UAAyB;GACvF,MAAM,KAAK;GACX,WAAW;EACb,EAAE;EAEF,MAAM,OAAO,MAAM;EACnB,KAAK,SAAS,KAAK,UAAU,CAAC;EAC9B,KAAK,OAAO,WAAW;CACzB;AACF"}
1
+ {"version":3,"file":"esbuild-plugins.mjs","names":[],"sources":["../../../../../../../core/src/production/esbuild-plugins.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport type { OnLoadArgs, OnResolveArgs, PluginBuild } from \"esbuild\";\n\nconst esmRequire = createRequire(import.meta.url);\n\nexport const nativeNodeModulesPlugin = {\n name: \"native-node-modules\",\n setup(build: PluginBuild) {\n build.onResolve({ filter: /\\.node$/, namespace: \"file\" }, (args: OnResolveArgs) => ({\n path: esmRequire.resolve(args.path, { paths: [args.resolveDir] }),\n namespace: \"node-file\",\n }));\n\n build.onLoad({ filter: /.*/, namespace: \"node-file\" }, (args: OnLoadArgs) => ({\n contents: `\n import path from ${JSON.stringify(args.path)}\n try { module.exports = require(path) }\n catch {}\n `,\n }));\n\n build.onResolve({ filter: /\\.node$/, namespace: \"node-file\" }, (args: OnResolveArgs) => ({\n path: args.path,\n namespace: \"file\",\n }));\n\n const opts = build.initialOptions;\n opts.loader = opts.loader || {};\n opts.loader[\".node\"] = \"file\";\n },\n};\n"],"mappings":";;;AAGA,MAAM,aAAa,cAAc,OAAO,KAAK,GAAG;AAEhD,MAAa,0BAA0B;CACrC,MAAM;CACN,MAAM,OAAoB;EACxB,MAAM,UAAU;GAAE,QAAQ;GAAW,WAAW;EAAO,IAAI,UAAyB;GAClF,MAAM,WAAW,QAAQ,KAAK,MAAM,EAAE,OAAO,CAAC,KAAK,UAAU,EAAE,CAAC;GAChE,WAAW;EACb,EAAE;EAEF,MAAM,OAAO;GAAE,QAAQ;GAAM,WAAW;EAAY,IAAI,UAAsB,EAC5E,UAAU;6BACa,KAAK,UAAU,KAAK,IAAI,EAAE;;;UAInD,EAAE;EAEF,MAAM,UAAU;GAAE,QAAQ;GAAW,WAAW;EAAY,IAAI,UAAyB;GACvF,MAAM,KAAK;GACX,WAAW;EACb,EAAE;EAEF,MAAM,OAAO,MAAM;EACnB,KAAK,SAAS,KAAK,UAAU,CAAC;EAC9B,KAAK,OAAO,WAAW;CACzB;AACF"}