@warlock.js/core 5.23.2 → 5.25.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 (207) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/bin/warlock.js +0 -0
  3. package/esm/application/application.d.mts +21 -0
  4. package/esm/application/application.d.mts.map +1 -1
  5. package/esm/application/application.mjs +29 -1
  6. package/esm/application/application.mjs.map +1 -1
  7. package/esm/application/boot-signal.d.mts +2 -1
  8. package/esm/application/boot-signal.d.mts.map +1 -1
  9. package/esm/application/boot-signal.mjs.map +1 -1
  10. package/esm/application/index.d.mts +1 -0
  11. package/esm/application/index.mjs +1 -0
  12. package/esm/application/roles.d.mts +72 -0
  13. package/esm/application/roles.d.mts.map +1 -0
  14. package/esm/application/roles.mjs +124 -0
  15. package/esm/application/roles.mjs.map +1 -0
  16. package/esm/cli/commands/add.command.mjs.map +1 -1
  17. package/esm/cli/commands/create-database.command.mjs.map +1 -1
  18. package/esm/cli/commands/dev-server.command.mjs.map +1 -1
  19. package/esm/cli/commands/doctor/boot-for-diagnostics.mjs.map +1 -1
  20. package/esm/cli/commands/drop-tables.command.mjs.map +1 -1
  21. package/esm/cli/commands/generate/utils/path-resolver.mjs.map +1 -1
  22. package/esm/cli/commands/migrate.command.mjs.map +1 -1
  23. package/esm/cli/commands/routes.command.mjs.map +1 -1
  24. package/esm/cli/commands/seed.command.mjs.map +1 -1
  25. package/esm/cli/commands/start-production.command.mjs +54 -5
  26. package/esm/cli/commands/start-production.command.mjs.map +1 -1
  27. package/esm/cli/commands/storage-put.action.mjs.map +1 -1
  28. package/esm/cli/commands/storage-put.command.mjs.map +1 -1
  29. package/esm/cli/commands/typings-generator.command.mjs +17 -1
  30. package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
  31. package/esm/cli/commands/update.command.mjs.map +1 -1
  32. package/esm/cli/commands-loader.mjs.map +1 -1
  33. package/esm/config/config-loader.d.mts.map +1 -1
  34. package/esm/config/config-loader.mjs +3 -1
  35. package/esm/config/config-loader.mjs.map +1 -1
  36. package/esm/connectors/connectors-manager.mjs.map +1 -1
  37. package/esm/connectors/database-connector.mjs.map +1 -1
  38. package/esm/connectors/herald-connector.mjs.map +1 -1
  39. package/esm/connectors/http-connector.d.mts.map +1 -1
  40. package/esm/connectors/http-connector.mjs +7 -0
  41. package/esm/connectors/http-connector.mjs.map +1 -1
  42. package/esm/connectors/logger-connector.mjs.map +1 -1
  43. package/esm/connectors/mail-connector.mjs.map +1 -1
  44. package/esm/connectors/types.d.mts +8 -0
  45. package/esm/connectors/types.d.mts.map +1 -1
  46. package/esm/connectors/types.mjs.map +1 -1
  47. package/esm/database/create-database-action.mjs.map +1 -1
  48. package/esm/database/drop-tables-action.mjs.map +1 -1
  49. package/esm/database/migrate-action.mjs +2 -1
  50. package/esm/database/migrate-action.mjs.map +1 -1
  51. package/esm/database/models/database-log/database-log.mjs.map +1 -1
  52. package/esm/database/seed-command-action.mjs +2 -1
  53. package/esm/database/seed-command-action.mjs.map +1 -1
  54. package/esm/dev-server/dependency-graph.mjs.map +1 -1
  55. package/esm/dev-server/development-server.mjs +2 -0
  56. package/esm/dev-server/development-server.mjs.map +1 -1
  57. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  58. package/esm/dev-server/layer-executor.mjs.map +1 -1
  59. package/esm/dev-server/manifest-manager.mjs.map +1 -1
  60. package/esm/dev-server/module-loader.mjs +10 -5
  61. package/esm/dev-server/module-loader.mjs.map +1 -1
  62. package/esm/dev-server/register-installed-devtools.mjs +47 -0
  63. package/esm/dev-server/register-installed-devtools.mjs.map +1 -0
  64. package/esm/dev-server/run-connector-typings.mjs +28 -0
  65. package/esm/dev-server/run-connector-typings.mjs.map +1 -0
  66. package/esm/dev-server/special-file-patterns.mjs +3 -1
  67. package/esm/dev-server/special-file-patterns.mjs.map +1 -1
  68. package/esm/dev-server/special-files-collector.d.mts +2 -2
  69. package/esm/dev-server/special-files-collector.d.mts.map +1 -1
  70. package/esm/dev-server/special-files-collector.mjs +7 -4
  71. package/esm/dev-server/special-files-collector.mjs.map +1 -1
  72. package/esm/encryption/password.mjs.map +1 -1
  73. package/esm/generations/add-command.action.mjs +3 -1
  74. package/esm/generations/add-command.action.mjs.map +1 -1
  75. package/esm/generations/features/access.feature.mjs.map +1 -1
  76. package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -1
  77. package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -1
  78. package/esm/generations/features/ai-google.feature.mjs.map +1 -1
  79. package/esm/generations/features/ai-ollama.feature.mjs.map +1 -1
  80. package/esm/generations/features/ai-openai.feature.mjs.map +1 -1
  81. package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -1
  82. package/esm/generations/features/ai-tools.feature.mjs.map +1 -1
  83. package/esm/generations/features/ai-workspace.feature.mjs.map +1 -1
  84. package/esm/generations/features/ai.feature.mjs.map +1 -1
  85. package/esm/generations/features/devtools.feature.mjs +23 -0
  86. package/esm/generations/features/devtools.feature.mjs.map +1 -0
  87. package/esm/generations/features/herald.feature.mjs.map +1 -1
  88. package/esm/generations/features/image.feature.mjs.map +1 -1
  89. package/esm/generations/features/index.mjs +2 -0
  90. package/esm/generations/features/index.mjs.map +1 -1
  91. package/esm/generations/features/mail.feature.mjs.map +1 -1
  92. package/esm/generations/features/mongodb.feature.mjs.map +1 -1
  93. package/esm/generations/features/notifications.feature.mjs.map +1 -1
  94. package/esm/generations/features/postgres.feature.mjs.map +1 -1
  95. package/esm/generations/features/react-email.feature.mjs.map +1 -1
  96. package/esm/generations/features/react.feature.mjs.map +1 -1
  97. package/esm/generations/features/redis.feature.mjs.map +1 -1
  98. package/esm/generations/features/s3.feature.mjs.map +1 -1
  99. package/esm/generations/features/scheduler.feature.mjs.map +1 -1
  100. package/esm/generations/features/ses.feature.mjs.map +1 -1
  101. package/esm/generations/features/socket.feature.mjs.map +1 -1
  102. package/esm/generations/features/test.feature.mjs +6 -2
  103. package/esm/generations/features/test.feature.mjs.map +1 -1
  104. package/esm/generations/features/types.mjs.map +1 -1
  105. package/esm/generations/features/web.feature.mjs.map +1 -1
  106. package/esm/http/database/RequestLog.mjs.map +1 -1
  107. package/esm/http/index.d.mts +2 -1
  108. package/esm/http/index.mjs +2 -1
  109. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  110. package/esm/http/middleware/inject-request-context.mjs +9 -1
  111. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  112. package/esm/http/request.d.mts +7 -0
  113. package/esm/http/request.d.mts.map +1 -1
  114. package/esm/http/request.mjs +8 -0
  115. package/esm/http/request.mjs.map +1 -1
  116. package/esm/http/response.d.mts +5 -5
  117. package/esm/http/response.d.mts.map +1 -1
  118. package/esm/http/response.mjs.map +1 -1
  119. package/esm/http/server-rebuilt.d.mts +20 -0
  120. package/esm/http/server-rebuilt.d.mts.map +1 -0
  121. package/esm/http/server-rebuilt.mjs +21 -0
  122. package/esm/http/server-rebuilt.mjs.map +1 -0
  123. package/esm/http/tracing/index.mjs +1 -1
  124. package/esm/http/tracing/tracing-dispatcher.d.mts +13 -6
  125. package/esm/http/tracing/tracing-dispatcher.d.mts.map +1 -1
  126. package/esm/http/tracing/tracing-dispatcher.mjs +46 -14
  127. package/esm/http/tracing/tracing-dispatcher.mjs.map +1 -1
  128. package/esm/http/tracing/tracing.type.d.mts +2 -1
  129. package/esm/http/tracing/tracing.type.d.mts.map +1 -1
  130. package/esm/http/types.d.mts +9 -0
  131. package/esm/http/types.d.mts.map +1 -1
  132. package/esm/image/image.mjs.map +1 -1
  133. package/esm/index.d.mts +4 -2
  134. package/esm/index.mjs +4 -2
  135. package/esm/loader/app-module-importer.d.mts +17 -0
  136. package/esm/loader/app-module-importer.d.mts.map +1 -0
  137. package/esm/loader/app-module-importer.mjs +20 -0
  138. package/esm/loader/app-module-importer.mjs.map +1 -0
  139. package/esm/logger/logger.mjs.map +1 -1
  140. package/esm/mail/events.d.mts +7 -0
  141. package/esm/mail/events.d.mts.map +1 -1
  142. package/esm/mail/events.mjs +7 -0
  143. package/esm/mail/events.mjs.map +1 -1
  144. package/esm/mail/send-mail.d.mts.map +1 -1
  145. package/esm/mail/send-mail.mjs +23 -2
  146. package/esm/mail/send-mail.mjs.map +1 -1
  147. package/esm/mail/types.d.mts +5 -1
  148. package/esm/mail/types.d.mts.map +1 -1
  149. package/esm/mail/types.mjs.map +1 -1
  150. package/esm/manifest/manifest-manager.mjs.map +1 -1
  151. package/esm/production/build-contributions.mjs +19 -3
  152. package/esm/production/build-contributions.mjs.map +1 -1
  153. package/esm/production/production-builder.mjs +28 -8
  154. package/esm/production/production-builder.mjs.map +1 -1
  155. package/esm/production/production-supervisor.mjs +6 -0
  156. package/esm/production/production-supervisor.mjs.map +1 -1
  157. package/esm/production/resolve-build-config.d.mts +1 -1
  158. package/esm/production/resolve-build-config.mjs +15 -0
  159. package/esm/production/resolve-build-config.mjs.map +1 -1
  160. package/esm/production/route-registration-child.mjs +14 -2
  161. package/esm/production/route-registration-child.mjs.map +1 -1
  162. package/esm/production/route-registration-snapshot.mjs +9 -2
  163. package/esm/production/route-registration-snapshot.mjs.map +1 -1
  164. package/esm/resource/resource-field-builder.mjs +1 -1
  165. package/esm/resource/resource-field-builder.mjs.map +1 -1
  166. package/esm/resource/resource.d.mts +5 -0
  167. package/esm/resource/resource.d.mts.map +1 -1
  168. package/esm/resource/resource.mjs +17 -6
  169. package/esm/resource/resource.mjs.map +1 -1
  170. package/esm/router/router.d.mts.map +1 -1
  171. package/esm/router/router.mjs +1 -0
  172. package/esm/router/router.mjs.map +1 -1
  173. package/esm/router/types.d.mts +2 -1
  174. package/esm/router/types.d.mts.map +1 -1
  175. package/esm/tests/index.d.mts +3 -2
  176. package/esm/tests/index.mjs +3 -2
  177. package/esm/tests/vitest-setup.d.mts +16 -1
  178. package/esm/tests/vitest-setup.d.mts.map +1 -1
  179. package/esm/tests/vitest-setup.mjs +20 -2
  180. package/esm/tests/vitest-setup.mjs.map +1 -1
  181. package/esm/use-cases/use-case-events.mjs.map +1 -1
  182. package/esm/utils/is-test-file.mjs +15 -0
  183. package/esm/utils/is-test-file.mjs.map +1 -0
  184. package/esm/utils/normalized-path.d.mts +3 -1
  185. package/esm/utils/normalized-path.d.mts.map +1 -1
  186. package/esm/utils/normalized-path.mjs +4 -2
  187. package/esm/utils/normalized-path.mjs.map +1 -1
  188. package/esm/utils/paths.mjs.map +1 -1
  189. package/esm/validation/plugins/database-plugin.mjs.map +1 -1
  190. package/esm/validation/validateAll.mjs +9 -3
  191. package/esm/validation/validateAll.mjs.map +1 -1
  192. package/esm/warlock-config/default-configurations.mjs +1 -0
  193. package/esm/warlock-config/default-configurations.mjs.map +1 -1
  194. package/esm/warlock-config/types.d.mts +7 -0
  195. package/esm/warlock-config/types.d.mts.map +1 -1
  196. package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
  197. package/llms-full.txt +264 -139
  198. package/package.json +15 -11
  199. package/skills/configure-app/SKILL.md +2 -0
  200. package/skills/define-resource/SKILL.md +4 -0
  201. package/skills/request-tracing/SKILL.md +38 -15
  202. package/skills/run-app/SKILL.md +71 -34
  203. package/skills/send-mail/SKILL.md +55 -25
  204. package/skills/test-http/SKILL.md +19 -8
  205. package/skills/test-service/SKILL.md +61 -40
  206. package/skills/warlock-conventions/SKILL.md +26 -18
  207. package/skills/write-cli-command/SKILL.md +50 -45
@@ -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 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 }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AEtD,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 * Notify development and test tooling of a captured mail without allowing a\n * synchronous listener failure to interrupt delivery.\n */\nfunction triggerCapturedMail(captured: CapturedMail): void {\n try {\n mailEvents.trigger(\"CAPTURED\", captured);\n } catch (error) {\n log.error(\"mail\", \"event\", `Captured mail event handler error: ${error}`);\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 id: mailId,\n options,\n normalized,\n timestamp: new Date(),\n result,\n };\n\n captureMail(captured);\n triggerCapturedMail(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 const captured: CapturedMail = {\n id: mailId,\n options,\n normalized,\n timestamp: new Date(),\n result,\n };\n\n triggerCapturedMail(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 // 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,Q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;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"}
@@ -245,9 +245,13 @@ type NormalizedMail = {
245
245
  config: MailConfigurations;
246
246
  };
247
247
  /**
248
- * Captured mail for test mode
248
+ * Captured mail for development and test modes.
249
+ *
250
+ * Attachments retain their normalized contents so test assertions can inspect
251
+ * the exact mail that would be sent.
249
252
  */
250
253
  type CapturedMail = {
254
+ /** The mail ID used for event namespacing and result correlation. */id: string;
251
255
  options: MailOptions;
252
256
  normalized: NormalizedMail;
253
257
  timestamp: Date;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/mail/types.ts"],"mappings":";;;;;;AAMA;KAAY,iBAAA;EACV,MAAA;EACA,WAAA;EACA,eAAA;EACA,MAAA;EACA,IAAA,GAAO,WAAW;AAAA;;;;KAMR,kBAAA,GAAqB,kBAAA,GAAqB,iBAAiB;AAAvE;;;AAAA,KAKY,QAAA;AAL2D;AAKvE;;AALuE,KAU3D,YAAA;;AALQ;AAKpB;KAKY,WAAA;EAGN,IAAA;EACA,OAAO;AAAA;AAJb;;;;AAAA,KAWY,cAAA;EACV,QAAA;EACA,WAAA;EACA,QAAA;EACA,GAAA;AAAA;EAGI,OAAA,EAAS,MAAM;EACf,IAAA;AAAA;EAGA,OAAA;EACA,IAAA;AAAA;;;;AAAI;AAqEV;;;;;;;;;;;;;AAwBoB;AAMpB;;;;;;;;;;;;;;AAQ6C;AAM7C;;;;;;;;;;;;;AAQM;AAON;;;;AAAyB;AAezB;;;;;;;;;;;;;KA1EY,kBAAA,GAAqB,aAAA,CAAc,OAAA;EA+FR;;;EA3FrC,MAAA;EA2EA;;;;EAtEA,GAAA;EA0EA;;;;EArEA,QAAA;EAwES;;;;EAnET,QAAA;EAwEa;;;;EAnEb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b,IAAA,EAAM,aAAA;EAAA,SACN,aAAA,GAAgB,KAAA;cAEb,OAAA,UAAiB,IAAA,EAAM,aAAA,EAAe,aAAA,GAAgB,KAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../core/src/mail/types.ts"],"sourcesContent":["import type SMTPTransport from \"nodemailer/lib/smtp-transport\";\nimport type React from \"react\";\n\n/**\n * AWS SES mail configuration\n */\nexport type SESConfigurations = {\n driver: \"ses\";\n accessKeyId: string;\n secretAccessKey: string;\n region: string;\n from?: MailAddress;\n};\n\n/**\n * Any mail configuration (SMTP or SES)\n */\nexport type MailConfigurations = SMTPConfigurations | SESConfigurations;\n\n/**\n * Mail mode determines how emails are handled\n */\nexport type MailMode = \"production\" | \"development\" | \"test\";\n\n/**\n * Mail priority levels\n */\nexport type MailPriority = \"high\" | \"normal\" | \"low\";\n\n/**\n * Email address with optional name\n */\nexport type MailAddress =\n | string\n | {\n name: string;\n address: string;\n };\n\n/**\n * Mail attachment\n * Supports both buffer/string content and file paths\n */\nexport type MailAttachment = {\n filename: string;\n contentType?: string;\n encoding?: \"base64\" | \"binary\" | \"hex\";\n cid?: string; // Content-ID for inline attachments\n} & (\n | {\n content: Buffer | string;\n path?: never;\n }\n | {\n content?: never;\n path: string; // File path - will be read automatically\n }\n);\n\n/**\n * Mail configuration for SMTP transport\n *\n * ## Basic Configuration\n *\n * ```typescript\n * setMailConfigurations({\n * host: \"smtp.gmail.com\",\n * port: 587,\n * secure: false, // true for 465, false for other ports\n * tls: true, // Use STARTTLS\n * username: \"user@gmail.com\",\n * password: \"app-password\",\n * from: { name: \"My App\", address: \"noreply@myapp.com\" },\n * });\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `host` | `string` | - | SMTP server hostname (e.g., \"smtp.gmail.com\") |\n * | `port` | `number` | 587 | SMTP port. Common: 25, 465 (SSL), 587 (TLS) |\n * | `secure` | `boolean` | false | Use SSL/TLS. Set `true` for port 465 |\n * | `tls` | `boolean` | true | Enable STARTTLS upgrade. For port 587 |\n * | `requireTLS` | `boolean` | - | Fail if STARTTLS upgrade fails |\n * | `username` | `string` | - | SMTP auth username (convenience alias) |\n * | `password` | `string` | - | SMTP auth password (convenience alias) |\n * | `auth` | `object` | - | Full auth object: `{ user, pass, type }` |\n * | `from` | `MailAddress` | - | Default sender for all emails |\n *\n * ## Provider Examples\n *\n * ### Gmail\n * ```typescript\n * { host: \"smtp.gmail.com\", port: 587, tls: true, username: \"...\", password: \"...\" }\n * ```\n *\n * ### SendGrid\n * ```typescript\n * { host: \"smtp.sendgrid.net\", port: 587, username: \"apikey\", password: \"SG.xxx\" }\n * ```\n *\n * ### AWS SES\n * ```typescript\n * { host: \"email-smtp.us-east-1.amazonaws.com\", port: 587, username: \"...\", password: \"...\" }\n * ```\n *\n * ### Mailgun\n * ```typescript\n * { host: \"smtp.mailgun.org\", port: 587, username: \"postmaster@...\", password: \"...\" }\n * ```\n *\n * ## Multi-tenant Usage\n *\n * For multi-tenant apps, pass config per-mail instead of globally:\n * ```typescript\n * await sendMail({\n * config: tenant.mailSettings, // Tenant-specific config\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n * ```\n */\nexport type SMTPConfigurations = SMTPTransport.Options & {\n /**\n * Transport driver type\n */\n driver?: \"smtp\";\n /**\n * Enable STARTTLS upgrade (alias for requireTLS)\n * Set to `true` for port 587\n */\n tls?: boolean;\n /**\n * SMTP authentication username\n * Convenience alias - can also use `auth.user`\n */\n username?: string;\n /**\n * SMTP authentication password\n * Convenience alias - can also use `auth.pass`\n */\n password?: string;\n /**\n * Default sender for all emails\n * Can be string (\"noreply@app.com\") or object ({ name, address })\n */\n from?: MailAddress;\n};\n\n/**\n * Named mailers configuration\n */\nexport type MailersConfig = {\n /**\n * Default mailer configuration\n */\n default?: MailConfigurations;\n /**\n * Named mailer configurations\n */\n mailers?: Record<string, MailConfigurations>;\n};\n\n/**\n * Mail result after sending\n */\nexport type MailResult = {\n success: boolean;\n messageId?: string;\n accepted: string[];\n rejected: string[];\n response?: string;\n envelope?: {\n from: string;\n to: string[];\n };\n};\n\n/**\n * Error codes for mail operations\n */\nexport type MailErrorCode =\n | \"CONNECTION_ERROR\"\n | \"AUTH_ERROR\"\n | \"RATE_LIMIT\"\n | \"INVALID_ADDRESS\"\n | \"REJECTED\"\n | \"TIMEOUT\"\n | \"RENDER_ERROR\"\n | \"CONFIG_ERROR\"\n | \"UNKNOWN\";\n\n/**\n * Mail event callbacks (per-mail)\n * For global events, use mailEvents.on() from events.ts\n */\nexport type MailEvents = {\n /**\n * Called before sending the email\n * Can be used to modify the mail or cancel sending\n */\n beforeSending?: (mail: MailOptions) => void | Promise<void> | false | Promise<false>;\n /**\n * Called after send attempt (success or failure)\n */\n onSent?: (\n mail: MailOptions,\n result: MailResult | null,\n error: MailError | null,\n ) => void | Promise<void>;\n /**\n * Called only on successful send\n */\n onSuccess?: (mail: MailOptions, result: MailResult) => void | Promise<void>;\n /**\n * Called only on error\n */\n onError?: (mail: MailOptions, error: MailError) => void | Promise<void>;\n};\n\n/**\n * Mail options for sending\n */\nexport type MailOptions = {\n /**\n * Unique mail ID for event namespacing\n * If not provided, one will be auto-generated\n *\n * Use this to subscribe to events for a specific mail:\n * ```typescript\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => { ... });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\n id?: string;\n\n // Recipients\n to: string | string[];\n cc?: string | string[];\n bcc?: string | string[];\n replyTo?: string;\n\n // Content\n subject: string;\n html?: string;\n text?: string;\n component?: React.ReactElement;\n\n // Configuration\n config?: MailConfigurations;\n mailer?: string;\n from?: MailAddress;\n\n // Attachments\n attachments?: MailAttachment[];\n\n // Options\n priority?: MailPriority;\n headers?: Record<string, string>;\n tags?: string[];\n\n // Meta\n correlationId?: string;\n} & MailEvents;\n\n/**\n * Internal normalized mail data\n */\nexport type NormalizedMail = {\n to: string[];\n cc: string[];\n bcc: string[];\n replyTo?: string;\n from: MailAddress;\n subject: string;\n html?: string;\n text?: string;\n attachments: MailAttachment[];\n priority: MailPriority;\n headers: Record<string, string>;\n tags: string[];\n correlationId?: string;\n config: MailConfigurations;\n};\n\n/**\n * Captured mail for test mode\n */\nexport type CapturedMail = {\n options: MailOptions;\n normalized: NormalizedMail;\n timestamp: Date;\n result?: MailResult;\n error?: MailError;\n};\n\n/**\n * Mail error class\n */\nexport class MailError extends Error {\n public readonly code: MailErrorCode;\n public readonly originalError?: Error;\n\n public constructor(message: string, code: MailErrorCode, originalError?: Error) {\n super(message);\n this.name = \"MailError\";\n this.code = code;\n this.originalError = originalError;\n }\n}\n"],"mappings":";;;;AA8SA,IAAa,YAAb,cAA+B,MAAM;CAInC,AAAO,YAAY,SAAiB,MAAqB,eAAuB;EAC9E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,gBAAgB;CACvB;AACF"}
1
+ {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../core/src/mail/types.ts"],"sourcesContent":["import type SMTPTransport from \"nodemailer/lib/smtp-transport\";\nimport type React from \"react\";\n\n/**\n * AWS SES mail configuration\n */\nexport type SESConfigurations = {\n driver: \"ses\";\n accessKeyId: string;\n secretAccessKey: string;\n region: string;\n from?: MailAddress;\n};\n\n/**\n * Any mail configuration (SMTP or SES)\n */\nexport type MailConfigurations = SMTPConfigurations | SESConfigurations;\n\n/**\n * Mail mode determines how emails are handled\n */\nexport type MailMode = \"production\" | \"development\" | \"test\";\n\n/**\n * Mail priority levels\n */\nexport type MailPriority = \"high\" | \"normal\" | \"low\";\n\n/**\n * Email address with optional name\n */\nexport type MailAddress =\n | string\n | {\n name: string;\n address: string;\n };\n\n/**\n * Mail attachment\n * Supports both buffer/string content and file paths\n */\nexport type MailAttachment = {\n filename: string;\n contentType?: string;\n encoding?: \"base64\" | \"binary\" | \"hex\";\n cid?: string; // Content-ID for inline attachments\n} & (\n | {\n content: Buffer | string;\n path?: never;\n }\n | {\n content?: never;\n path: string; // File path - will be read automatically\n }\n);\n\n/**\n * Mail configuration for SMTP transport\n *\n * ## Basic Configuration\n *\n * ```typescript\n * setMailConfigurations({\n * host: \"smtp.gmail.com\",\n * port: 587,\n * secure: false, // true for 465, false for other ports\n * tls: true, // Use STARTTLS\n * username: \"user@gmail.com\",\n * password: \"app-password\",\n * from: { name: \"My App\", address: \"noreply@myapp.com\" },\n * });\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `host` | `string` | - | SMTP server hostname (e.g., \"smtp.gmail.com\") |\n * | `port` | `number` | 587 | SMTP port. Common: 25, 465 (SSL), 587 (TLS) |\n * | `secure` | `boolean` | false | Use SSL/TLS. Set `true` for port 465 |\n * | `tls` | `boolean` | true | Enable STARTTLS upgrade. For port 587 |\n * | `requireTLS` | `boolean` | - | Fail if STARTTLS upgrade fails |\n * | `username` | `string` | - | SMTP auth username (convenience alias) |\n * | `password` | `string` | - | SMTP auth password (convenience alias) |\n * | `auth` | `object` | - | Full auth object: `{ user, pass, type }` |\n * | `from` | `MailAddress` | - | Default sender for all emails |\n *\n * ## Provider Examples\n *\n * ### Gmail\n * ```typescript\n * { host: \"smtp.gmail.com\", port: 587, tls: true, username: \"...\", password: \"...\" }\n * ```\n *\n * ### SendGrid\n * ```typescript\n * { host: \"smtp.sendgrid.net\", port: 587, username: \"apikey\", password: \"SG.xxx\" }\n * ```\n *\n * ### AWS SES\n * ```typescript\n * { host: \"email-smtp.us-east-1.amazonaws.com\", port: 587, username: \"...\", password: \"...\" }\n * ```\n *\n * ### Mailgun\n * ```typescript\n * { host: \"smtp.mailgun.org\", port: 587, username: \"postmaster@...\", password: \"...\" }\n * ```\n *\n * ## Multi-tenant Usage\n *\n * For multi-tenant apps, pass config per-mail instead of globally:\n * ```typescript\n * await sendMail({\n * config: tenant.mailSettings, // Tenant-specific config\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n * ```\n */\nexport type SMTPConfigurations = SMTPTransport.Options & {\n /**\n * Transport driver type\n */\n driver?: \"smtp\";\n /**\n * Enable STARTTLS upgrade (alias for requireTLS)\n * Set to `true` for port 587\n */\n tls?: boolean;\n /**\n * SMTP authentication username\n * Convenience alias - can also use `auth.user`\n */\n username?: string;\n /**\n * SMTP authentication password\n * Convenience alias - can also use `auth.pass`\n */\n password?: string;\n /**\n * Default sender for all emails\n * Can be string (\"noreply@app.com\") or object ({ name, address })\n */\n from?: MailAddress;\n};\n\n/**\n * Named mailers configuration\n */\nexport type MailersConfig = {\n /**\n * Default mailer configuration\n */\n default?: MailConfigurations;\n /**\n * Named mailer configurations\n */\n mailers?: Record<string, MailConfigurations>;\n};\n\n/**\n * Mail result after sending\n */\nexport type MailResult = {\n success: boolean;\n messageId?: string;\n accepted: string[];\n rejected: string[];\n response?: string;\n envelope?: {\n from: string;\n to: string[];\n };\n};\n\n/**\n * Error codes for mail operations\n */\nexport type MailErrorCode =\n | \"CONNECTION_ERROR\"\n | \"AUTH_ERROR\"\n | \"RATE_LIMIT\"\n | \"INVALID_ADDRESS\"\n | \"REJECTED\"\n | \"TIMEOUT\"\n | \"RENDER_ERROR\"\n | \"CONFIG_ERROR\"\n | \"UNKNOWN\";\n\n/**\n * Mail event callbacks (per-mail)\n * For global events, use mailEvents.on() from events.ts\n */\nexport type MailEvents = {\n /**\n * Called before sending the email\n * Can be used to modify the mail or cancel sending\n */\n beforeSending?: (mail: MailOptions) => void | Promise<void> | false | Promise<false>;\n /**\n * Called after send attempt (success or failure)\n */\n onSent?: (\n mail: MailOptions,\n result: MailResult | null,\n error: MailError | null,\n ) => void | Promise<void>;\n /**\n * Called only on successful send\n */\n onSuccess?: (mail: MailOptions, result: MailResult) => void | Promise<void>;\n /**\n * Called only on error\n */\n onError?: (mail: MailOptions, error: MailError) => void | Promise<void>;\n};\n\n/**\n * Mail options for sending\n */\nexport type MailOptions = {\n /**\n * Unique mail ID for event namespacing\n * If not provided, one will be auto-generated\n *\n * Use this to subscribe to events for a specific mail:\n * ```typescript\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => { ... });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\n id?: string;\n\n // Recipients\n to: string | string[];\n cc?: string | string[];\n bcc?: string | string[];\n replyTo?: string;\n\n // Content\n subject: string;\n html?: string;\n text?: string;\n component?: React.ReactElement;\n\n // Configuration\n config?: MailConfigurations;\n mailer?: string;\n from?: MailAddress;\n\n // Attachments\n attachments?: MailAttachment[];\n\n // Options\n priority?: MailPriority;\n headers?: Record<string, string>;\n tags?: string[];\n\n // Meta\n correlationId?: string;\n} & MailEvents;\n\n/**\n * Internal normalized mail data\n */\nexport type NormalizedMail = {\n to: string[];\n cc: string[];\n bcc: string[];\n replyTo?: string;\n from: MailAddress;\n subject: string;\n html?: string;\n text?: string;\n attachments: MailAttachment[];\n priority: MailPriority;\n headers: Record<string, string>;\n tags: string[];\n correlationId?: string;\n config: MailConfigurations;\n};\n\n/**\n * Captured mail for development and test modes.\n *\n * Attachments retain their normalized contents so test assertions can inspect\n * the exact mail that would be sent.\n */\nexport type CapturedMail = {\n /** The mail ID used for event namespacing and result correlation. */\n id: string;\n options: MailOptions;\n normalized: NormalizedMail;\n timestamp: Date;\n result?: MailResult;\n error?: MailError;\n};\n\n/**\n * Mail error class\n */\nexport class MailError extends Error {\n public readonly code: MailErrorCode;\n public readonly originalError?: Error;\n\n public constructor(message: string, code: MailErrorCode, originalError?: Error) {\n super(message);\n this.name = \"MailError\";\n this.code = code;\n this.originalError = originalError;\n }\n}\n"],"mappings":";;;;AAmTA,IAAa,YAAb,cAA+B,MAAM;CAInC,AAAO,YAAY,SAAiB,MAAqB,eAAuB;EAC9E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,gBAAgB;CACvB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"manifest-manager.mjs","names":[],"sources":["../../../../../../../core/src/manifest/manifest-manager.ts"],"sourcesContent":["import { getJsonFileAsync, putJsonFileAsync, unlinkAsync } from \"@warlock.js/fs\";\r\nimport { warlockPath } from \"../utils\";\r\n\r\n/**\r\n * Stored option metadata in manifest\r\n */\r\nexport type ManifestCommandOption = {\r\n name: string;\r\n text: string;\r\n alias?: string;\r\n description?: string;\r\n type?: \"string\" | \"boolean\" | \"number\";\r\n required?: boolean;\r\n defaultValue?: string | boolean | number;\r\n};\r\n\r\n/**\r\n * Command metadata stored in commands.json\r\n */\r\nexport type ManifestCommandData = {\r\n relativePath?: string;\r\n source: \"framework\" | \"plugin\" | \"project\";\r\n description?: string;\r\n alias?: string;\r\n options?: ManifestCommandOption[];\r\n};\r\n\r\ntype ManifestCommandsJson = {\r\n commands: Record<string, ManifestCommandData>;\r\n};\r\n\r\nexport class ManifestManager {\r\n /**\r\n * commands json\r\n */\r\n protected _commandsJson?: ManifestCommandsJson;\r\n\r\n /**\r\n * Check if commands json is changed\r\n */\r\n protected _hasChanges = false;\r\n\r\n /**\r\n * Whether commands json is loaded\r\n */\r\n protected _isLoaded = false;\r\n\r\n /**\r\n * Get if commands json has changes\r\n */\r\n public get hasChanges() {\r\n return this._hasChanges;\r\n }\r\n\r\n /**\r\n * Check if commands json is loaded\r\n */\r\n public get isCommandLoaded() {\r\n return this._isLoaded;\r\n }\r\n\r\n /**\r\n * Load commands.json file\r\n */\r\n public async loadCommands(): Promise<ManifestCommandsJson | undefined> {\r\n // now try to locate it in .warlock folder\r\n if (this._isLoaded) return this._commandsJson;\r\n\r\n try {\r\n this._commandsJson = await getJsonFileAsync(warlockPath(\"commands.json\"));\r\n\r\n this._isLoaded = true;\r\n\r\n return this._commandsJson;\r\n } catch {\r\n return;\r\n }\r\n }\r\n\r\n /**\r\n * Get commands json content\r\n */\r\n public get commandsJson() {\r\n return this._commandsJson;\r\n }\r\n\r\n /**\r\n * Save commands in commands.json file\r\n */\r\n public async saveCommands() {\r\n await putJsonFileAsync(warlockPath(\"commands.json\"), this._commandsJson);\r\n\r\n this._isLoaded = true;\r\n this._hasChanges = false;\r\n }\r\n\r\n /**\r\n * Add command info to commands list (But do not save commands)\r\n */\r\n public addCommandToList(name: string, command: ManifestCommandsJson[\"commands\"][string]) {\r\n if (!this._commandsJson) {\r\n this._commandsJson = {\r\n commands: {},\r\n };\r\n }\r\n\r\n this._commandsJson.commands[name] = command;\r\n\r\n this._hasChanges = true;\r\n }\r\n\r\n /**\r\n * Clear commands cache\r\n */\r\n public clearCommandsCache() {\r\n this._commandsJson = undefined;\r\n this._hasChanges = false;\r\n this._isLoaded = false;\r\n }\r\n\r\n /**\r\n * Remove commands.json file\r\n */\r\n public async removeCommandsFile() {\r\n try {\r\n await unlinkAsync(warlockPath(\"commands.json\"));\r\n } catch {\r\n // do nothing\r\n }\r\n }\r\n}\r\n\r\nexport const manifestManager = new ManifestManager();\r\n"],"mappings":";;;;;AA+BA,IAAa,kBAAb,MAA6B;;qBASH;mBAKF;;;;;CAKtB,IAAW,aAAa;EACtB,OAAO,KAAK;CACd;;;;CAKA,IAAW,kBAAkB;EAC3B,OAAO,KAAK;CACd;;;;CAKA,MAAa,eAA0D;EAErE,IAAI,KAAK,WAAW,OAAO,KAAK;EAEhC,IAAI;GACF,KAAK,gBAAgB,MAAM,iBAAiB,YAAY,eAAe,CAAC;GAExE,KAAK,YAAY;GAEjB,OAAO,KAAK;EACd,QAAQ;GACN;EACF;CACF;;;;CAKA,IAAW,eAAe;EACxB,OAAO,KAAK;CACd;;;;CAKA,MAAa,eAAe;EAC1B,MAAM,iBAAiB,YAAY,eAAe,GAAG,KAAK,aAAa;EAEvE,KAAK,YAAY;EACjB,KAAK,cAAc;CACrB;;;;CAKA,AAAO,iBAAiB,MAAc,SAAmD;EACvF,IAAI,CAAC,KAAK,eACR,KAAK,gBAAgB,EACnB,UAAU,CAAC,EACb;EAGF,KAAK,cAAc,SAAS,QAAQ;EAEpC,KAAK,cAAc;CACrB;;;;CAKA,AAAO,qBAAqB;EAC1B,KAAK,gBAAgB;EACrB,KAAK,cAAc;EACnB,KAAK,YAAY;CACnB;;;;CAKA,MAAa,qBAAqB;EAChC,IAAI;GACF,MAAM,YAAY,YAAY,eAAe,CAAC;EAChD,QAAQ,CAER;CACF;AACF;AAEA,MAAa,kBAAkB,IAAI,gBAAgB"}
1
+ {"version":3,"file":"manifest-manager.mjs","names":[],"sources":["../../../../../../../core/src/manifest/manifest-manager.ts"],"sourcesContent":["import { getJsonFileAsync, putJsonFileAsync, unlinkAsync } from \"@warlock.js/fs\";\nimport { warlockPath } from \"../utils\";\n\n/**\n * Stored option metadata in manifest\n */\nexport type ManifestCommandOption = {\n name: string;\n text: string;\n alias?: string;\n description?: string;\n type?: \"string\" | \"boolean\" | \"number\";\n required?: boolean;\n defaultValue?: string | boolean | number;\n};\n\n/**\n * Command metadata stored in commands.json\n */\nexport type ManifestCommandData = {\n relativePath?: string;\n source: \"framework\" | \"plugin\" | \"project\";\n description?: string;\n alias?: string;\n options?: ManifestCommandOption[];\n};\n\ntype ManifestCommandsJson = {\n commands: Record<string, ManifestCommandData>;\n};\n\nexport class ManifestManager {\n /**\n * commands json\n */\n protected _commandsJson?: ManifestCommandsJson;\n\n /**\n * Check if commands json is changed\n */\n protected _hasChanges = false;\n\n /**\n * Whether commands json is loaded\n */\n protected _isLoaded = false;\n\n /**\n * Get if commands json has changes\n */\n public get hasChanges() {\n return this._hasChanges;\n }\n\n /**\n * Check if commands json is loaded\n */\n public get isCommandLoaded() {\n return this._isLoaded;\n }\n\n /**\n * Load commands.json file\n */\n public async loadCommands(): Promise<ManifestCommandsJson | undefined> {\n // now try to locate it in .warlock folder\n if (this._isLoaded) return this._commandsJson;\n\n try {\n this._commandsJson = await getJsonFileAsync(warlockPath(\"commands.json\"));\n\n this._isLoaded = true;\n\n return this._commandsJson;\n } catch {\n return;\n }\n }\n\n /**\n * Get commands json content\n */\n public get commandsJson() {\n return this._commandsJson;\n }\n\n /**\n * Save commands in commands.json file\n */\n public async saveCommands() {\n await putJsonFileAsync(warlockPath(\"commands.json\"), this._commandsJson);\n\n this._isLoaded = true;\n this._hasChanges = false;\n }\n\n /**\n * Add command info to commands list (But do not save commands)\n */\n public addCommandToList(name: string, command: ManifestCommandsJson[\"commands\"][string]) {\n if (!this._commandsJson) {\n this._commandsJson = {\n commands: {},\n };\n }\n\n this._commandsJson.commands[name] = command;\n\n this._hasChanges = true;\n }\n\n /**\n * Clear commands cache\n */\n public clearCommandsCache() {\n this._commandsJson = undefined;\n this._hasChanges = false;\n this._isLoaded = false;\n }\n\n /**\n * Remove commands.json file\n */\n public async removeCommandsFile() {\n try {\n await unlinkAsync(warlockPath(\"commands.json\"));\n } catch {\n // do nothing\n }\n }\n}\n\nexport const manifestManager = new ManifestManager();\n"],"mappings":";;;;;AA+BA,IAAa,kBAAb,MAA6B;;qBASH;mBAKF;;;;;CAKtB,IAAW,aAAa;EACtB,OAAO,KAAK;CACd;;;;CAKA,IAAW,kBAAkB;EAC3B,OAAO,KAAK;CACd;;;;CAKA,MAAa,eAA0D;EAErE,IAAI,KAAK,WAAW,OAAO,KAAK;EAEhC,IAAI;GACF,KAAK,gBAAgB,MAAM,iBAAiB,YAAY,eAAe,CAAC;GAExE,KAAK,YAAY;GAEjB,OAAO,KAAK;EACd,QAAQ;GACN;EACF;CACF;;;;CAKA,IAAW,eAAe;EACxB,OAAO,KAAK;CACd;;;;CAKA,MAAa,eAAe;EAC1B,MAAM,iBAAiB,YAAY,eAAe,GAAG,KAAK,aAAa;EAEvE,KAAK,YAAY;EACjB,KAAK,cAAc;CACrB;;;;CAKA,AAAO,iBAAiB,MAAc,SAAmD;EACvF,IAAI,CAAC,KAAK,eACR,KAAK,gBAAgB,EACnB,UAAU,CAAC,EACb;EAGF,KAAK,cAAc,SAAS,QAAQ;EAEpC,KAAK,cAAc;CACrB;;;;CAKA,AAAO,qBAAqB;EAC1B,KAAK,gBAAgB;EACrB,KAAK,cAAc;EACnB,KAAK,YAAY;CACnB;;;;CAKA,MAAa,qBAAqB;EAChC,IAAI;GACF,MAAM,YAAY,YAAY,eAAe,CAAC;EAChD,QAAQ,CAER;CACF;AACF;AAEA,MAAa,kBAAkB,IAAI,gBAAgB"}
@@ -10,7 +10,11 @@ const ErrorWithCause = Error;
10
10
  * posture as the `tsconfig` guard in `resolve-build-config`: dropping the key
11
11
  * quietly would leave the author believing their plugin ran.
12
12
  */
13
- const ALLOWED_CONTRIBUTION_KEYS = ["generate", "emit"];
13
+ const ALLOWED_CONTRIBUTION_KEYS = [
14
+ "generate",
15
+ "emit",
16
+ "typings"
17
+ ];
14
18
  /**
15
19
  * Reject a contribution object carrying anything but the two hooks.
16
20
  *
@@ -21,7 +25,7 @@ function assertClosedContribution(connector) {
21
25
  if (!contribution) return;
22
26
  for (const key of Object.keys(contribution)) {
23
27
  if (ALLOWED_CONTRIBUTION_KEYS.includes(key)) continue;
24
- throw new Error(`Connector "${connector.name}" declares an unsupported build contribution key "${key}". A build contribution carries exactly two optional hooks — ${ALLOWED_CONTRIBUTION_KEYS.join(" and ")} — and no data. Anything a hook needs (plugins, pipelines, aliases) must be constructed inside that hook, so it never lands in the connector's static import graph.`);
28
+ throw new Error(`Connector "${connector.name}" declares an unsupported build contribution key "${key}". A build contribution carries exactly these optional hooks — ${ALLOWED_CONTRIBUTION_KEYS.join(", ")} — and no data. Anything a hook needs (plugins, pipelines, aliases) must be constructed inside that hook, so it never lands in the connector's static import graph.`);
25
29
  }
26
30
  }
27
31
  /**
@@ -66,6 +70,18 @@ async function runEmitContributions(connectors, context) {
66
70
  }
67
71
  }
68
72
  /**
73
+ * Drain every connector's `typings` hook, in array order, sequentially.
74
+ * Connectors without one — every API-only app — are skipped without error.
75
+ */
76
+ async function runTypingsContributions(connectors, context) {
77
+ for (const connector of connectors) {
78
+ assertClosedContribution(connector);
79
+ const typings = connector.build?.typings;
80
+ if (!typings) continue;
81
+ await runHook(connector, "typings", () => typings(context));
82
+ }
83
+ }
84
+ /**
69
85
  * Merge two contributor patches. Later wins, except:
70
86
  *
71
87
  * - `define` merges per key — two contributors defining different
@@ -114,5 +130,5 @@ async function runHook(connector, hook, run) {
114
130
  }
115
131
 
116
132
  //#endregion
117
- export { dedupe, runEmitContributions, runGenerateContributions };
133
+ export { dedupe, runEmitContributions, runGenerateContributions, runTypingsContributions };
118
134
  //# sourceMappingURL=build-contributions.mjs.map
@@ -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 * - `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,0B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;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\", \"typings\"] 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 these optional hooks — ` +\n `${ALLOWED_CONTRIBUTION_KEYS.join(\", \")} — 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 * Drain every connector's `typings` hook, in array order, sequentially.\n * Connectors without one — every API-only app — are skipped without error.\n */\nexport async function runTypingsContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<void> {\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const typings = connector.build?.typings;\n\n if (!typings) continue;\n\n await runHook(connector, \"typings\", () => typings(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\" | \"typings\",\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;;;;;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B;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,IAAI,KAAK,WAAW,MAAM,SACxB,OAAO,UAAU,CAAC,GAAI,KAAK,WAAW,CAAC,GAAI,GAAI,MAAM,WAAW,CAAC,CAAE;CAGrE,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"}
@@ -4,7 +4,7 @@ import { assertNoReservedConnectorNames } from "../connectors/assert-no-reserved
4
4
  import { assertUniqueConnectorNames } from "../connectors/assert-unique-connector-names.mjs";
5
5
  import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
6
6
  import { tsconfigManager } from "../dev-server/tsconfig-manager.mjs";
7
- import { isConfigFile, isEventFile, isLocaleFile, isMainFile, isRouteFile } from "../dev-server/special-file-patterns.mjs";
7
+ import { isConfigFile, isEventFile, isLocaleFile, isMainFile, isRouteFile, isWorkerFile } from "../dev-server/special-file-patterns.mjs";
8
8
  import { configKeyFromPath } from "../config/config-key-from-path.mjs";
9
9
  import { assertGeneratedImportsAreDeclared } from "./assert-generated-imports.mjs";
10
10
  import { bundleFrameworkDependencies } from "./bundle-framework-dependencies.mjs";
@@ -86,7 +86,8 @@ var ProductionBuilder = class {
86
86
  locales: false,
87
87
  events: false,
88
88
  main: false,
89
- routes: false
89
+ routes: false,
90
+ workers: false
90
91
  };
91
92
  }
92
93
  /**
@@ -177,7 +178,10 @@ var ProductionBuilder = class {
177
178
  await clearOwnedRouteTypes(rootPath());
178
179
  return;
179
180
  }
180
- this.namedApiRoutes = (await collectRouteRegistrationSnapshot({ cwd: rootPath() })).routes;
181
+ this.namedApiRoutes = (await collectRouteRegistrationSnapshot({
182
+ cwd: rootPath(),
183
+ timeoutMs: this.options.routeRegistrationTimeoutMs
184
+ })).routes;
181
185
  }
182
186
  /**
183
187
  * Drain the `generate` hooks and fold what they returned back into the
@@ -213,17 +217,19 @@ var ProductionBuilder = class {
213
217
  console.log(colors.yellow(" Generating production files..."));
214
218
  await this.generateBootstrap();
215
219
  await this.generateConfigLoader();
216
- const [locales, events, main, routes] = await Promise.all([
220
+ const [locales, events, main, routes, workers] = await Promise.all([
217
221
  this.generateLocales(),
218
222
  this.generateEvents(),
219
223
  this.generateMain(),
220
- this.generateRoutes()
224
+ this.generateRoutes(),
225
+ this.generateWorkers()
221
226
  ]);
222
227
  this.generatedFiles = {
223
228
  locales,
224
229
  events,
225
230
  main,
226
- routes
231
+ routes,
232
+ workers
227
233
  };
228
234
  }
229
235
  /**
@@ -355,6 +361,16 @@ bootstrap();
355
361
  return true;
356
362
  }
357
363
  /**
364
+ * Generate workers.ts (only if there are worker files)
365
+ * @returns true if file was generated with content
366
+ */
367
+ async generateWorkers() {
368
+ const files = await this.globModule(isWorkerFile);
369
+ if (files.length === 0) return false;
370
+ await this.generateImportsFile(files, "workers.ts");
371
+ return true;
372
+ }
373
+ /**
358
374
  * Generate a file with imports from all given files
359
375
  */
360
376
  async generateImportsFile(importPaths, outputFile) {
@@ -397,7 +413,9 @@ bootstrap();
397
413
  "// a bind-and-release on a socket that is never served, and it reports",
398
414
  "// on stderr because no log channel is configured this early.",
399
415
  "import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";",
400
- "await preflightConfiguredHttpPort();",
416
+ "if (Application.hasRole(\"api\") || Application.hasRole(\"web\")) {",
417
+ " await preflightConfiguredHttpPort();",
418
+ "}",
401
419
  "",
402
420
  "// 3. Start early-phase connectors (database, cache, logger, ...)",
403
421
  "// so data sources, cache, etc. are ready before app code runs",
@@ -407,7 +425,8 @@ bootstrap();
407
425
  if (this.generatedFiles.events) imports.push("await import(\"./events\");");
408
426
  if (this.generatedFiles.locales) imports.push("await import(\"./locales\");");
409
427
  if (this.generatedFiles.main) imports.push("await import(\"./main\");");
410
- if (this.generatedFiles.routes) imports.push("await import(\"./routes\");");
428
+ if (this.generatedFiles.routes) imports.push("if (Application.hasRole(\"api\")) {", " await import(\"./routes\");", "}");
429
+ if (this.generatedFiles.workers) imports.push("if (Application.hasRole(\"worker\")) {", " await import(\"./workers\");", "}");
411
430
  imports.push(...contributedImports);
412
431
  imports.push("", "// 5. Run startup validators registered via Application.onValidateBoot(...)", "await Application.runStartupValidators();");
413
432
  imports.push("", "// 6. Start late-phase connectors (http, socket) — routes and", "// listeners registered by app code are now ready to bind", "await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);", "", "// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire", "Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });", "connectorsManager.shutdownOnProcessKill();");
@@ -438,6 +457,7 @@ bootstrap();
438
457
  delete esbuildOptions.singleBundle;
439
458
  delete esbuildOptions.esmShim;
440
459
  delete esbuildOptions.banner;
460
+ delete esbuildOptions.routeRegistrationTimeoutMs;
441
461
  await ensureDirectoryAsync(writeOutDir);
442
462
  const alias = this.buildAliasMapFromTsconfig();
443
463
  const perEdgeExternals = !singleBundle && esbuildOptions.packages === void 0;