@ts-cloud/core 0.2.2 → 0.2.4

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 (226) hide show
  1. package/dist/advanced-features.test.d.ts +1 -0
  2. package/dist/aws/cloudformation.d.ts +136 -0
  3. package/dist/aws/cloudfront.d.ts +45 -0
  4. package/dist/aws/credentials.d.ts +77 -0
  5. package/dist/aws/credentials.test.d.ts +4 -0
  6. package/dist/aws/index.d.ts +10 -0
  7. package/dist/aws/s3.d.ts +256 -0
  8. package/dist/aws/s3.test.d.ts +4 -0
  9. package/dist/aws/signature.d.ts +142 -0
  10. package/dist/aws/signature.test.d.ts +4 -0
  11. package/dist/backup/disaster-recovery.d.ts +140 -0
  12. package/dist/backup/disaster-recovery.test.d.ts +1 -0
  13. package/dist/backup/index.d.ts +8 -0
  14. package/dist/backup/manager.d.ts +172 -0
  15. package/dist/backup/manager.test.d.ts +1 -0
  16. package/dist/cicd/circleci.d.ts +50 -0
  17. package/dist/cicd/github-actions.d.ts +62 -0
  18. package/dist/cicd/gitlab-ci.d.ts +50 -0
  19. package/dist/cicd/index.d.ts +7 -0
  20. package/dist/cli/history.d.ts +137 -0
  21. package/dist/cli/index.d.ts +9 -0
  22. package/dist/cli/progress.d.ts +193 -0
  23. package/dist/cli/repl.d.ts +148 -0
  24. package/dist/cli/suggestions.d.ts +74 -0
  25. package/dist/cli/table.d.ts +73 -0
  26. package/dist/cli/table.test.d.ts +1 -0
  27. package/dist/cloudformation/builder.d.ts +93 -0
  28. package/dist/cloudformation/builder.test.d.ts +4 -0
  29. package/dist/cloudformation/builders/api-gateway.d.ts +30 -0
  30. package/dist/cloudformation/builders/cache.d.ts +35 -0
  31. package/dist/cloudformation/builders/cdn.d.ts +34 -0
  32. package/dist/cloudformation/builders/compute.d.ts +68 -0
  33. package/dist/cloudformation/builders/database.d.ts +61 -0
  34. package/dist/cloudformation/builders/functions.d.ts +32 -0
  35. package/dist/cloudformation/builders/messaging.d.ts +17 -0
  36. package/dist/cloudformation/builders/monitoring.d.ts +39 -0
  37. package/dist/cloudformation/builders/network.d.ts +14 -0
  38. package/dist/cloudformation/builders/queue.d.ts +16 -0
  39. package/dist/cloudformation/builders/security.d.ts +31 -0
  40. package/dist/cloudformation/builders/storage.d.ts +36 -0
  41. package/dist/cloudformation/index.d.ts +10 -0
  42. package/dist/cloudformation/types.d.ts +200 -0
  43. package/dist/compliance/aws-config.d.ts +175 -0
  44. package/dist/compliance/cloudtrail.d.ts +132 -0
  45. package/dist/compliance/compliance.test.d.ts +1 -0
  46. package/dist/compliance/guardduty.d.ts +176 -0
  47. package/dist/compliance/index.d.ts +12 -0
  48. package/dist/compliance/security-hub.d.ts +178 -0
  49. package/dist/containers/build-optimization.d.ts +155 -0
  50. package/dist/containers/containers.test.d.ts +1 -0
  51. package/dist/containers/image-scanning.d.ts +144 -0
  52. package/dist/containers/index.d.ts +8 -0
  53. package/dist/containers/registry.d.ts +129 -0
  54. package/dist/containers/service-mesh.d.ts +254 -0
  55. package/dist/database/database.test.d.ts +1 -0
  56. package/dist/database/index.d.ts +8 -0
  57. package/dist/database/migrations.d.ts +153 -0
  58. package/dist/database/performance.d.ts +219 -0
  59. package/dist/database/replicas.d.ts +218 -0
  60. package/dist/database/users.d.ts +165 -0
  61. package/dist/dependency-graph.d.ts +37 -0
  62. package/dist/deployment/ab-testing.d.ts +165 -0
  63. package/dist/deployment/blue-green.d.ts +140 -0
  64. package/dist/deployment/canary.d.ts +165 -0
  65. package/dist/deployment/deployment.test.d.ts +1 -0
  66. package/dist/deployment/index.d.ts +12 -0
  67. package/dist/deployment/progressive.d.ts +50 -0
  68. package/dist/dns/dns.test.d.ts +1 -0
  69. package/dist/dns/dnssec.d.ts +120 -0
  70. package/dist/dns/index.d.ts +7 -0
  71. package/dist/dns/resolver.d.ts +216 -0
  72. package/dist/dns/routing.d.ts +277 -0
  73. package/dist/email/advanced/analytics.d.ts +107 -0
  74. package/dist/email/advanced/index.d.ts +10 -0
  75. package/dist/email/advanced/rules.d.ts +131 -0
  76. package/dist/email/advanced/scheduling.d.ts +81 -0
  77. package/dist/email/advanced/search.d.ts +91 -0
  78. package/dist/email/advanced/shared-mailboxes.d.ts +109 -0
  79. package/dist/email/advanced/templates.d.ts +95 -0
  80. package/dist/email/advanced/threading.d.ts +65 -0
  81. package/dist/email/analytics.d.ts +189 -0
  82. package/dist/email/bounce-handling.d.ts +171 -0
  83. package/dist/email/email.test.d.ts +1 -0
  84. package/dist/email/handlers/__tests__/inbound.test.d.ts +1 -0
  85. package/dist/email/handlers/__tests__/outbound.test.d.ts +1 -0
  86. package/dist/email/handlers/converter.d.ts +11 -0
  87. package/dist/email/handlers/feedback.d.ts +11 -0
  88. package/dist/email/handlers/inbound.d.ts +13 -0
  89. package/dist/email/handlers/outbound.d.ts +13 -0
  90. package/dist/email/index.d.ts +10 -0
  91. package/dist/email/reputation.d.ts +133 -0
  92. package/dist/email/templates.d.ts +124 -0
  93. package/dist/errors/index.d.ts +177 -0
  94. package/dist/errors/index.test.d.ts +4 -0
  95. package/dist/health-checks/index.d.ts +35 -0
  96. package/dist/index.d.ts +15 -256
  97. package/dist/index.js +228 -80
  98. package/dist/intrinsic-functions.d.ts +77 -0
  99. package/dist/lambda/concurrency.d.ts +146 -0
  100. package/dist/lambda/destinations.d.ts +141 -0
  101. package/dist/lambda/dlq.d.ts +160 -0
  102. package/dist/lambda/index.d.ts +10 -0
  103. package/dist/lambda/lambda.test.d.ts +1 -0
  104. package/dist/lambda/layers.d.ts +117 -0
  105. package/dist/lambda/versions.d.ts +145 -0
  106. package/dist/lambda/vpc.d.ts +164 -0
  107. package/dist/local/config.d.ts +44 -0
  108. package/dist/local/index.d.ts +5 -0
  109. package/dist/local/mock-aws.d.ts +69 -0
  110. package/dist/modules/ai.d.ts +108 -0
  111. package/dist/modules/api.d.ts +157 -0
  112. package/dist/modules/auth.d.ts +262 -0
  113. package/dist/modules/cache.d.ts +108 -0
  114. package/dist/modules/cdn.d.ts +305 -0
  115. package/dist/modules/communication.d.ts +117 -0
  116. package/dist/modules/compute.d.ts +1376 -0
  117. package/dist/modules/database.d.ts +144 -0
  118. package/dist/modules/deployment.d.ts +372 -0
  119. package/dist/modules/dns.d.ts +143 -0
  120. package/dist/modules/email.d.ts +314 -0
  121. package/dist/modules/filesystem.d.ts +132 -0
  122. package/dist/modules/index.d.ts +31 -0
  123. package/dist/modules/messaging.d.ts +210 -0
  124. package/dist/modules/monitoring.d.ts +574 -0
  125. package/dist/modules/network.d.ts +148 -0
  126. package/dist/modules/parameter-store.d.ts +143 -0
  127. package/dist/modules/permissions.d.ts +245 -0
  128. package/dist/modules/phone.d.ts +125 -0
  129. package/dist/modules/queue.d.ts +411 -0
  130. package/dist/modules/redirects.d.ts +140 -0
  131. package/dist/modules/registry.d.ts +189 -0
  132. package/dist/modules/search.d.ts +135 -0
  133. package/dist/modules/secrets.d.ts +149 -0
  134. package/dist/modules/security.d.ts +219 -0
  135. package/dist/modules/sms.d.ts +130 -0
  136. package/dist/modules/storage.d.ts +344 -0
  137. package/dist/modules/workflow.d.ts +288 -0
  138. package/dist/multi-account/config.d.ts +166 -0
  139. package/dist/multi-account/index.d.ts +6 -0
  140. package/dist/multi-account/manager.d.ts +181 -0
  141. package/dist/multi-region/cross-region.d.ts +204 -0
  142. package/dist/multi-region/index.d.ts +7 -0
  143. package/dist/multi-region/manager.d.ts +136 -0
  144. package/dist/multi-region/regions.d.ts +98 -0
  145. package/dist/network-security/index.d.ts +55 -0
  146. package/dist/observability/index.d.ts +8 -0
  147. package/dist/observability/logs.d.ts +213 -0
  148. package/dist/observability/metrics.d.ts +187 -0
  149. package/dist/observability/observability.test.d.ts +1 -0
  150. package/dist/observability/synthetics.d.ts +189 -0
  151. package/dist/observability/xray.d.ts +193 -0
  152. package/dist/phone/advanced/analytics.d.ts +83 -0
  153. package/dist/phone/advanced/callbacks.d.ts +67 -0
  154. package/dist/phone/advanced/index.d.ts +7 -0
  155. package/dist/phone/advanced/ivr-builder.d.ts +130 -0
  156. package/dist/phone/advanced/recording.d.ts +62 -0
  157. package/dist/phone/handlers/__tests__/incoming-call.test.d.ts +1 -0
  158. package/dist/phone/handlers/incoming-call.d.ts +10 -0
  159. package/dist/phone/handlers/missed-call.d.ts +9 -0
  160. package/dist/phone/handlers/voicemail.d.ts +10 -0
  161. package/dist/phone/index.d.ts +5 -0
  162. package/dist/presets/api-backend.d.ts +11 -0
  163. package/dist/presets/data-pipeline.d.ts +11 -0
  164. package/dist/presets/extend.d.ts +194 -0
  165. package/dist/presets/extend.test.d.ts +4 -0
  166. package/dist/presets/fullstack-app.d.ts +12 -0
  167. package/dist/presets/index.d.ts +13 -0
  168. package/dist/presets/jamstack.d.ts +12 -0
  169. package/dist/presets/microservices.d.ts +18 -0
  170. package/dist/presets/ml-api.d.ts +13 -0
  171. package/dist/presets/nodejs-server.d.ts +14 -0
  172. package/dist/presets/nodejs-serverless.d.ts +14 -0
  173. package/dist/presets/realtime-app.d.ts +11 -0
  174. package/dist/presets/static-site.d.ts +12 -0
  175. package/dist/presets/traditional-web-app.d.ts +16 -0
  176. package/dist/presets/wordpress.d.ts +12 -0
  177. package/dist/preview/github.d.ts +32 -0
  178. package/dist/preview/github.test.d.ts +1 -0
  179. package/dist/preview/index.d.ts +10 -0
  180. package/dist/preview/manager.d.ts +101 -0
  181. package/dist/preview/manager.test.d.ts +1 -0
  182. package/dist/preview/notifications.d.ts +89 -0
  183. package/dist/preview/notifications.test.d.ts +1 -0
  184. package/dist/queue/batch-processing.d.ts +138 -0
  185. package/dist/queue/dlq-monitoring.d.ts +143 -0
  186. package/dist/queue/fifo.d.ts +131 -0
  187. package/dist/queue/index.d.ts +8 -0
  188. package/dist/queue/management.d.ts +162 -0
  189. package/dist/queue/queue.test.d.ts +1 -0
  190. package/dist/resource-mgmt/index.d.ts +44 -0
  191. package/dist/resource-naming.d.ts +26 -0
  192. package/dist/s3/index.d.ts +227 -0
  193. package/dist/schema/index.d.ts +12 -0
  194. package/dist/security/certificate-manager.d.ts +184 -0
  195. package/dist/security/index.d.ts +8 -0
  196. package/dist/security/scanning.d.ts +196 -0
  197. package/dist/security/secrets-manager.d.ts +204 -0
  198. package/dist/security/secrets-rotation.d.ts +167 -0
  199. package/dist/security/security.test.d.ts +1 -0
  200. package/dist/sms/advanced/ab-testing.d.ts +74 -0
  201. package/dist/sms/advanced/analytics.d.ts +75 -0
  202. package/dist/sms/advanced/campaigns.d.ts +96 -0
  203. package/dist/sms/advanced/chatbot.d.ts +67 -0
  204. package/dist/sms/advanced/index.d.ts +9 -0
  205. package/dist/sms/advanced/link-tracking.d.ts +60 -0
  206. package/dist/sms/advanced/mms.d.ts +60 -0
  207. package/dist/sms/handlers/__tests__/send.test.d.ts +1 -0
  208. package/dist/sms/handlers/delivery-status.d.ts +10 -0
  209. package/dist/sms/handlers/receive.d.ts +10 -0
  210. package/dist/sms/handlers/send.d.ts +10 -0
  211. package/dist/sms/index.d.ts +5 -0
  212. package/dist/stack-diff.d.ts +38 -0
  213. package/dist/static-site/index.d.ts +49 -0
  214. package/dist/template-builder.d.ts +42 -0
  215. package/dist/template-validator.d.ts +28 -0
  216. package/dist/types.d.ts +2514 -0
  217. package/dist/utils/cache.d.ts +117 -0
  218. package/dist/utils/diff.d.ts +52 -0
  219. package/dist/utils/hash.d.ts +73 -0
  220. package/dist/utils/index.d.ts +7 -0
  221. package/dist/utils/parallel.d.ts +78 -0
  222. package/dist/validators/credentials.d.ts +30 -0
  223. package/dist/validators/credentials.test.d.ts +4 -0
  224. package/dist/validators/quotas.d.ts +64 -0
  225. package/dist/validators/quotas.test.d.ts +4 -0
  226. package/package.json +2 -2
@@ -0,0 +1,189 @@
1
+ /**
2
+ * SES Email Analytics
3
+ * Email tracking, analytics, and reporting
4
+ */
5
+ export interface EmailEvent {
6
+ id: string;
7
+ messageId: string;
8
+ eventType: 'send' | 'delivery' | 'open' | 'click' | 'bounce' | 'complaint' | 'reject' | 'renderingFailure';
9
+ timestamp: Date;
10
+ recipient: string;
11
+ subject?: string;
12
+ tags?: Record<string, string>;
13
+ }
14
+ export interface OpenEvent extends EmailEvent {
15
+ eventType: 'open';
16
+ ipAddress: string;
17
+ userAgent: string;
18
+ }
19
+ export interface ClickEvent extends EmailEvent {
20
+ eventType: 'click';
21
+ link: string;
22
+ ipAddress: string;
23
+ userAgent: string;
24
+ }
25
+ export interface EmailCampaign {
26
+ id: string;
27
+ name: string;
28
+ subject: string;
29
+ fromEmail: string;
30
+ tags: Record<string, string>;
31
+ sentCount: number;
32
+ deliveredCount: number;
33
+ openCount: number;
34
+ clickCount: number;
35
+ bounceCount: number;
36
+ complaintCount: number;
37
+ createdAt: Date;
38
+ }
39
+ export interface AnalyticsReport {
40
+ id: string;
41
+ campaignId?: string;
42
+ startDate: Date;
43
+ endDate: Date;
44
+ totalSent: number;
45
+ totalDelivered: number;
46
+ totalOpened: number;
47
+ totalClicked: number;
48
+ totalBounced: number;
49
+ totalComplaints: number;
50
+ deliveryRate: number;
51
+ openRate: number;
52
+ clickRate: number;
53
+ clickToOpenRate: number;
54
+ bounceRate: number;
55
+ complaintRate: number;
56
+ topLinks: Array<{
57
+ link: string;
58
+ clicks: number;
59
+ }>;
60
+ deviceBreakdown: Record<string, number>;
61
+ locationBreakdown: Record<string, number>;
62
+ }
63
+ export interface ABTest {
64
+ id: string;
65
+ name: string;
66
+ variants: ABTestVariant[];
67
+ status: 'draft' | 'running' | 'completed';
68
+ startedAt?: Date;
69
+ completedAt?: Date;
70
+ winner?: string;
71
+ }
72
+ export interface ABTestVariant {
73
+ id: string;
74
+ name: string;
75
+ subject: string;
76
+ content: string;
77
+ weight: number;
78
+ sentCount: number;
79
+ openCount: number;
80
+ clickCount: number;
81
+ conversionCount: number;
82
+ }
83
+ /**
84
+ * Email analytics manager
85
+ */
86
+ export declare class EmailAnalyticsManager {
87
+ private events;
88
+ private campaigns;
89
+ private reports;
90
+ private abTests;
91
+ private eventCounter;
92
+ private campaignCounter;
93
+ private reportCounter;
94
+ private abTestCounter;
95
+ /**
96
+ * Track email event
97
+ */
98
+ trackEvent(event: Omit<EmailEvent, 'id'>): EmailEvent;
99
+ /**
100
+ * Track open event
101
+ */
102
+ trackOpen(options: {
103
+ messageId: string;
104
+ recipient: string;
105
+ ipAddress: string;
106
+ userAgent: string;
107
+ tags?: Record<string, string>;
108
+ }): OpenEvent;
109
+ /**
110
+ * Track click event
111
+ */
112
+ trackClick(options: {
113
+ messageId: string;
114
+ recipient: string;
115
+ link: string;
116
+ ipAddress: string;
117
+ userAgent: string;
118
+ tags?: Record<string, string>;
119
+ }): ClickEvent;
120
+ /**
121
+ * Create campaign
122
+ */
123
+ createCampaign(campaign: Omit<EmailCampaign, 'id' | 'sentCount' | 'deliveredCount' | 'openCount' | 'clickCount' | 'bounceCount' | 'complaintCount' | 'createdAt'>): EmailCampaign;
124
+ /**
125
+ * Update campaign stats
126
+ */
127
+ private updateCampaignStats;
128
+ /**
129
+ * Generate analytics report
130
+ */
131
+ generateReport(options: {
132
+ campaignId?: string;
133
+ startDate: Date;
134
+ endDate: Date;
135
+ }): AnalyticsReport;
136
+ /**
137
+ * Create A/B test
138
+ */
139
+ createABTest(options: {
140
+ name: string;
141
+ variants: Array<{
142
+ name: string;
143
+ subject: string;
144
+ content: string;
145
+ weight: number;
146
+ }>;
147
+ }): ABTest;
148
+ /**
149
+ * Start A/B test
150
+ */
151
+ startABTest(abTestId: string): ABTest;
152
+ /**
153
+ * Complete A/B test
154
+ */
155
+ completeABTest(abTestId: string): ABTest;
156
+ /**
157
+ * Get campaign
158
+ */
159
+ getCampaign(id: string): EmailCampaign | undefined;
160
+ /**
161
+ * List campaigns
162
+ */
163
+ listCampaigns(): EmailCampaign[];
164
+ /**
165
+ * Get events
166
+ */
167
+ getEvents(options?: {
168
+ messageId?: string;
169
+ eventType?: string;
170
+ startDate?: Date;
171
+ endDate?: Date;
172
+ }): EmailEvent[];
173
+ /**
174
+ * Generate CloudFormation for tracking configuration
175
+ */
176
+ generateTrackingConfigurationCF(options: {
177
+ configurationSetName: string;
178
+ openTracking?: boolean;
179
+ clickTracking?: boolean;
180
+ }): any;
181
+ /**
182
+ * Clear all data
183
+ */
184
+ clear(): void;
185
+ }
186
+ /**
187
+ * Global email analytics manager instance
188
+ */
189
+ export declare const emailAnalyticsManager: EmailAnalyticsManager;
@@ -0,0 +1,171 @@
1
+ /**
2
+ * SES Bounce and Complaint Handling
3
+ * Automated bounce processing and reputation management
4
+ */
5
+ export interface BounceEvent {
6
+ id: string;
7
+ timestamp: Date;
8
+ messageId: string;
9
+ recipient: string;
10
+ bounceType: 'Permanent' | 'Transient' | 'Undetermined';
11
+ bounceSubType: string;
12
+ diagnosticCode?: string;
13
+ feedbackId: string;
14
+ }
15
+ export interface ComplaintEvent {
16
+ id: string;
17
+ timestamp: Date;
18
+ messageId: string;
19
+ recipients: string[];
20
+ complaintFeedbackType?: string;
21
+ userAgent?: string;
22
+ feedbackId: string;
23
+ arrivalDate?: Date;
24
+ }
25
+ export interface BounceHandler {
26
+ id: string;
27
+ name: string;
28
+ bounceThreshold: number;
29
+ complaintThreshold: number;
30
+ suppressionDuration: number;
31
+ autoSuppress: boolean;
32
+ notificationTopicArn?: string;
33
+ }
34
+ export interface SuppressionListEntry {
35
+ id: string;
36
+ emailAddress: string;
37
+ reason: 'BOUNCE' | 'COMPLAINT';
38
+ suppressedAt: Date;
39
+ expiresAt?: Date;
40
+ bounceCount?: number;
41
+ complaintCount?: number;
42
+ }
43
+ export interface ReputationMetrics {
44
+ id: string;
45
+ timestamp: Date;
46
+ bounceRate: number;
47
+ complaintRate: number;
48
+ sendingQuota: number;
49
+ maxSendRate: number;
50
+ sentLast24Hours: number;
51
+ reputationStatus: 'Good' | 'Warning' | 'Probation' | 'Shutdown';
52
+ }
53
+ /**
54
+ * Bounce and complaint handler
55
+ */
56
+ export declare class BounceComplaintHandler {
57
+ private bounces;
58
+ private complaints;
59
+ private handlers;
60
+ private suppressionList;
61
+ private metrics;
62
+ private bounceCounter;
63
+ private complaintCounter;
64
+ private handlerCounter;
65
+ private suppressionCounter;
66
+ private metricsCounter;
67
+ /**
68
+ * Record bounce event
69
+ */
70
+ recordBounce(bounce: Omit<BounceEvent, 'id'>): BounceEvent;
71
+ /**
72
+ * Record complaint event
73
+ */
74
+ recordComplaint(complaint: Omit<ComplaintEvent, 'id'>): ComplaintEvent;
75
+ /**
76
+ * Create bounce handler
77
+ */
78
+ createBounceHandler(handler: Omit<BounceHandler, 'id'>): BounceHandler;
79
+ /**
80
+ * Create automatic bounce handler
81
+ */
82
+ createAutomaticBounceHandler(options: {
83
+ name: string;
84
+ notificationTopicArn: string;
85
+ }): BounceHandler;
86
+ /**
87
+ * Add to suppression list
88
+ */
89
+ addToSuppressionList(entry: {
90
+ emailAddress: string;
91
+ reason: 'BOUNCE' | 'COMPLAINT';
92
+ expirationDays?: number;
93
+ }): SuppressionListEntry;
94
+ /**
95
+ * Remove from suppression list
96
+ */
97
+ removeFromSuppressionList(emailAddress: string): boolean;
98
+ /**
99
+ * Check if email is suppressed
100
+ */
101
+ isSuppressed(emailAddress: string): boolean;
102
+ /**
103
+ * Get bounce statistics
104
+ */
105
+ getBounceStatistics(startDate: Date, endDate: Date): {
106
+ totalBounces: number;
107
+ permanentBounces: number;
108
+ transientBounces: number;
109
+ bounceRate: number;
110
+ topRecipients: Array<{
111
+ email: string;
112
+ count: number;
113
+ }>;
114
+ };
115
+ /**
116
+ * Get complaint statistics
117
+ */
118
+ getComplaintStatistics(startDate: Date, endDate: Date): {
119
+ totalComplaints: number;
120
+ uniqueComplainters: number;
121
+ complaintRate: number;
122
+ };
123
+ /**
124
+ * Calculate reputation metrics
125
+ */
126
+ calculateReputationMetrics(): ReputationMetrics;
127
+ /**
128
+ * Get bounce events
129
+ */
130
+ getBounces(messageId?: string): BounceEvent[];
131
+ /**
132
+ * Get complaint events
133
+ */
134
+ getComplaints(messageId?: string): ComplaintEvent[];
135
+ /**
136
+ * List suppression list
137
+ */
138
+ listSuppressionList(reason?: 'BOUNCE' | 'COMPLAINT'): SuppressionListEntry[];
139
+ /**
140
+ * Generate CloudFormation for SNS topic subscription
141
+ */
142
+ generateSNSSubscriptionCF(options: {
143
+ topicArn: string;
144
+ endpoint: string;
145
+ protocol: 'email' | 'email-json' | 'http' | 'https' | 'sqs' | 'lambda';
146
+ }): any;
147
+ /**
148
+ * Generate CloudFormation for SES configuration set event destination
149
+ */
150
+ generateEventDestinationCF(options: {
151
+ configurationSetName: string;
152
+ eventDestinationName: string;
153
+ eventTypes: Array<'send' | 'reject' | 'bounce' | 'complaint' | 'delivery' | 'open' | 'click' | 'renderingFailure'>;
154
+ snsTopicArn?: string;
155
+ cloudWatchDestination?: {
156
+ dimensionConfigurations: Array<{
157
+ dimensionName: string;
158
+ dimensionValueSource: 'messageTag' | 'emailHeader' | 'linkTag';
159
+ defaultDimensionValue: string;
160
+ }>;
161
+ };
162
+ }): any;
163
+ /**
164
+ * Clear all data
165
+ */
166
+ clear(): void;
167
+ }
168
+ /**
169
+ * Global bounce and complaint handler instance
170
+ */
171
+ export declare const bounceComplaintHandler: BounceComplaintHandler;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Email Conversion Lambda Handler
3
+ *
4
+ * Converts raw MIME emails to readable formats:
5
+ * - Converts raw MIME to HTML/text
6
+ * - Extracts and saves attachments separately
7
+ * - Generates email previews
8
+ * - Creates searchable metadata JSON
9
+ */
10
+ export declare const handler = "\nconst { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');\nconst s3 = new S3Client({});\n\nexports.handler = async (event) => {\n console.log('Email conversion event:', JSON.stringify(event, null, 2));\n\n const bucket = process.env.EMAIL_BUCKET;\n\n for (const record of event.Records) {\n try {\n const s3Event = record.s3 || {};\n const key = decodeURIComponent(s3Event.object?.key?.replace(/\\+/g, ' ') || '');\n\n // Only process raw.eml files in mailboxes\n if (!key.endsWith('/raw.eml') || !key.startsWith('mailboxes/')) {\n continue;\n }\n\n const basePath = key.replace('/raw.eml', '');\n\n // Get raw email\n const getResult = await s3.send(new GetObjectCommand({\n Bucket: bucket,\n Key: key,\n }));\n\n const rawEmail = await getResult.Body.transformToString();\n\n // Parse email\n const parsed = parseEmail(rawEmail);\n\n // Save HTML version\n if (parsed.html) {\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: `${basePath}/body.html`,\n Body: parsed.html,\n ContentType: 'text/html',\n }));\n }\n\n // Save text version\n if (parsed.text) {\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: `${basePath}/body.txt`,\n Body: parsed.text,\n ContentType: 'text/plain',\n }));\n }\n\n // Save attachments\n if (parsed.attachments && parsed.attachments.length > 0) {\n for (let i = 0; i < parsed.attachments.length; i++) {\n const attachment = parsed.attachments[i];\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: `${basePath}/attachments/${attachment.filename}`,\n Body: Buffer.from(attachment.content, 'base64'),\n ContentType: attachment.contentType,\n }));\n }\n\n // Update metadata with attachment info\n try {\n const metaResult = await s3.send(new GetObjectCommand({\n Bucket: bucket,\n Key: `${basePath}/metadata.json`,\n }));\n const metadata = JSON.parse(await metaResult.Body.transformToString());\n\n metadata.attachments = parsed.attachments.map(a => ({\n filename: a.filename,\n contentType: a.contentType,\n size: a.size,\n }));\n metadata.converted = true;\n metadata.convertedAt = new Date().toISOString();\n\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: `${basePath}/metadata.json`,\n Body: JSON.stringify(metadata, null, 2),\n ContentType: 'application/json',\n }));\n }\ncatch (err) {\n console.log('Could not update metadata:', err.message);\n }\n }\n\n // Generate preview (first 200 chars of text)\n const preview = (parsed.text || parsed.html?.replace(/<[^>]+>/g, '') || '')\n .substring(0, 200)\n .replace(/\\s+/g, ' ')\n .trim();\n\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: `${basePath}/preview.txt`,\n Body: preview,\n ContentType: 'text/plain',\n }));\n\n console.log(`Converted email: ${key}`);\n\n }\ncatch (error) {\n console.error('Error converting email:', error);\n }\n }\n\n return { statusCode: 200, body: 'OK' };\n};\n\n// Simple MIME parser\nfunction parseEmail(rawEmail) {\n const result = {\n headers: {},\n text: null,\n html: null,\n attachments: [],\n };\n\n // Split headers and body\n const parts = rawEmail.split(/\\r?\\n\\r?\\n/);\n const headerSection = parts[0];\n const bodySection = parts.slice(1).join('\\n\\n');\n\n // Parse headers\n let currentHeader = '';\n for (const line of headerSection.split(/\\r?\\n/)) {\n if (line.match(/^[A-Za-z-]+:/)) {\n const colonIndex = line.indexOf(':');\n currentHeader = line.substring(0, colonIndex).toLowerCase();\n result.headers[currentHeader] = line.substring(colonIndex + 1).trim();\n }\nelse if (currentHeader && (line.startsWith(' ') || line.startsWith('\\t'))) {\n result.headers[currentHeader] += ' ' + line.trim();\n }\n }\n\n // Check content type\n const contentType = result.headers['content-type'] || 'text/plain';\n\n if (contentType.includes('multipart/')) {\n // Extract boundary\n const boundaryMatch = contentType.match(/boundary=\"?([^\";]+)\"?/);\n if (boundaryMatch) {\n const boundary = boundaryMatch[1];\n const mimeParts = bodySection.split('--' + boundary);\n\n for (const part of mimeParts) {\n if (part.trim() === '' || part.trim() === '--') continue;\n\n const partParts = part.split(/\\r?\\n\\r?\\n/);\n const partHeaders = partParts[0];\n const partBody = partParts.slice(1).join('\\n\\n').trim();\n\n const partContentType = (partHeaders.match(/Content-Type:\\s*([^;\\r\\n]+)/i) || [])[1] || '';\n const partEncoding = (partHeaders.match(/Content-Transfer-Encoding:\\s*([^\\r\\n]+)/i) || [])[1] || '';\n const partDisposition = (partHeaders.match(/Content-Disposition:\\s*([^;\\r\\n]+)/i) || [])[1] || '';\n\n if (partDisposition.includes('attachment') || partContentType.includes('application/')) {\n // Attachment\n const filenameMatch = partHeaders.match(/filename=\"?([^\"\\r\\n]+)\"?/i);\n const filename = filenameMatch ? filenameMatch[1] : `attachment_${result.attachments.length + 1}`;\n\n let content = partBody;\n if (partEncoding.toLowerCase() === 'base64') {\n content = partBody.replace(/\\s/g, '');\n }\n\n result.attachments.push({\n filename,\n contentType: partContentType.trim(),\n content,\n size: Buffer.from(content, 'base64').length,\n });\n }\nelse if (partContentType.includes('text/html')) {\n result.html = decodeContent(partBody, partEncoding);\n }\nelse if (partContentType.includes('text/plain')) {\n result.text = decodeContent(partBody, partEncoding);\n }\nelse if (partContentType.includes('multipart/')) {\n // Nested multipart - recursively parse\n const nestedResult = parseEmail(partHeaders + '\\n\\n' + partBody);\n if (nestedResult.html) result.html = nestedResult.html;\n if (nestedResult.text) result.text = nestedResult.text;\n result.attachments.push(...nestedResult.attachments);\n }\n }\n }\n }\nelse if (contentType.includes('text/html')) {\n result.html = bodySection;\n }\nelse {\n result.text = bodySection;\n }\n\n return result;\n}\n\nfunction decodeContent(content, encoding) {\n if (!encoding) return content;\n\n encoding = encoding.toLowerCase().trim();\n\n if (encoding === 'base64') {\n return Buffer.from(content.replace(/\\s/g, ''), 'base64').toString('utf-8');\n }\nelse if (encoding === 'quoted-printable') {\n return content\n .replace(/=\\r?\\n/g, '')\n .replace(/=([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));\n }\n\n return content;\n}\n";
11
+ export default handler;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Email Feedback Lambda Handler
3
+ *
4
+ * Processes SES bounce and complaint notifications:
5
+ * - Processes SES bounce notifications
6
+ * - Processes complaint notifications
7
+ * - Updates suppression list
8
+ * - Sends admin notifications
9
+ */
10
+ export declare const handler = "\nconst { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');\nconst { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');\n\nconst s3 = new S3Client({});\nconst sns = new SNSClient({});\n\nexports.handler = async (event) => {\n console.log('Email feedback event:', JSON.stringify(event, null, 2));\n\n const bucket = process.env.EMAIL_BUCKET;\n const adminTopicArn = process.env.ADMIN_TOPIC_ARN;\n\n for (const record of event.Records) {\n try {\n const message = JSON.parse(record.Sns?.Message || record.body || '{}');\n const notificationType = message.notificationType || message.eventType;\n\n if (!notificationType) {\n console.log('Unknown notification type, skipping');\n continue;\n }\n\n const timestamp = new Date().toISOString();\n\n if (notificationType === 'Bounce') {\n await handleBounce(message, bucket, adminTopicArn, timestamp);\n }\nelse if (notificationType === 'Complaint') {\n await handleComplaint(message, bucket, adminTopicArn, timestamp);\n }\nelse if (notificationType === 'Delivery') {\n await handleDelivery(message, bucket, timestamp);\n }\n\n }\ncatch (error) {\n console.error('Error processing feedback:', error);\n }\n }\n\n return { statusCode: 200, body: 'OK' };\n};\n\nasync function handleBounce(message, bucket, adminTopicArn, timestamp) {\n const bounce = message.bounce || {};\n const mail = message.mail || {};\n\n console.log(`Processing bounce: ${bounce.bounceType} - ${bounce.bounceSubType}`);\n\n // Get bounced recipients\n const bouncedRecipients = bounce.bouncedRecipients || [];\n\n for (const recipient of bouncedRecipients) {\n const email = recipient.emailAddress;\n\n // Add to suppression list\n await addToSuppressionList(bucket, email, 'bounce', {\n type: bounce.bounceType,\n subType: bounce.bounceSubType,\n diagnosticCode: recipient.diagnosticCode,\n action: recipient.action,\n status: recipient.status,\n timestamp,\n originalMessageId: mail.messageId,\n });\n\n console.log(`Added ${email} to suppression list (bounce)`);\n }\n\n // Log bounce event\n await logFeedbackEvent(bucket, 'bounces', {\n type: 'bounce',\n bounceType: bounce.bounceType,\n bounceSubType: bounce.bounceSubType,\n recipients: bouncedRecipients.map(r => r.emailAddress),\n messageId: mail.messageId,\n timestamp,\n });\n\n // Notify admin for hard bounces\n if (bounce.bounceType === 'Permanent' && adminTopicArn) {\n await sns.send(new PublishCommand({\n TopicArn: adminTopicArn,\n Subject: `Email Bounce Alert: ${bounce.bounceSubType}`,\n Message: JSON.stringify({\n type: 'bounce',\n bounceType: bounce.bounceType,\n bounceSubType: bounce.bounceSubType,\n recipients: bouncedRecipients.map(r => ({\n email: r.emailAddress,\n diagnosticCode: r.diagnosticCode,\n })),\n originalSubject: mail.commonHeaders?.subject,\n timestamp,\n }, null, 2),\n }));\n }\n}\n\nasync function handleComplaint(message, bucket, adminTopicArn, timestamp) {\n const complaint = message.complaint || {};\n const mail = message.mail || {};\n\n console.log(`Processing complaint: ${complaint.complaintFeedbackType}`);\n\n // Get complained recipients\n const complainedRecipients = complaint.complainedRecipients || [];\n\n for (const recipient of complainedRecipients) {\n const email = recipient.emailAddress;\n\n // Add to suppression list\n await addToSuppressionList(bucket, email, 'complaint', {\n feedbackType: complaint.complaintFeedbackType,\n userAgent: complaint.userAgent,\n timestamp,\n originalMessageId: mail.messageId,\n });\n\n console.log(`Added ${email} to suppression list (complaint)`);\n }\n\n // Log complaint event\n await logFeedbackEvent(bucket, 'complaints', {\n type: 'complaint',\n feedbackType: complaint.complaintFeedbackType,\n recipients: complainedRecipients.map(r => r.emailAddress),\n messageId: mail.messageId,\n timestamp,\n });\n\n // Always notify admin for complaints\n if (adminTopicArn) {\n await sns.send(new PublishCommand({\n TopicArn: adminTopicArn,\n Subject: `Email Complaint Alert: ${complaint.complaintFeedbackType || 'Unknown'}`,\n Message: JSON.stringify({\n type: 'complaint',\n feedbackType: complaint.complaintFeedbackType,\n recipients: complainedRecipients.map(r => r.emailAddress),\n originalSubject: mail.commonHeaders?.subject,\n timestamp,\n }, null, 2),\n }));\n }\n}\n\nasync function handleDelivery(message, bucket, timestamp) {\n const delivery = message.delivery || {};\n const mail = message.mail || {};\n\n console.log(`Processing delivery confirmation for ${delivery.recipients?.join(', ')}`);\n\n // Log delivery event\n await logFeedbackEvent(bucket, 'deliveries', {\n type: 'delivery',\n recipients: delivery.recipients,\n messageId: mail.messageId,\n processingTimeMillis: delivery.processingTimeMillis,\n smtpResponse: delivery.smtpResponse,\n timestamp,\n });\n}\n\nasync function addToSuppressionList(bucket, email, reason, details) {\n const key = 'suppression/list.json';\n let list = [];\n\n try {\n const result = await s3.send(new GetObjectCommand({\n Bucket: bucket,\n Key: key,\n }));\n list = JSON.parse(await result.Body.transformToString());\n }\ncatch {\n // List doesn't exist yet\n }\n\n // Check if already in list\n const existing = list.find(item => item.email === email);\n if (existing) {\n existing.lastUpdated = details.timestamp;\n existing.count = (existing.count || 1) + 1;\n }\nelse {\n list.push({\n email,\n reason,\n addedAt: details.timestamp,\n lastUpdated: details.timestamp,\n count: 1,\n details,\n });\n }\n\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: key,\n Body: JSON.stringify(list, null, 2),\n ContentType: 'application/json',\n }));\n}\n\nasync function logFeedbackEvent(bucket, type, event) {\n const date = new Date();\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n\n const key = `feedback/${type}/${year}/${month}/${day}/${Date.now()}-${Math.random().toString(36).substr(2)}.json`;\n\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: key,\n Body: JSON.stringify(event, null, 2),\n ContentType: 'application/json',\n }));\n}\n";
11
+ export default handler;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Inbound Email Lambda Handler
3
+ *
4
+ * Processes incoming emails from SES:
5
+ * - Parses raw MIME emails
6
+ * - Extracts metadata (from, to, subject, date, attachments)
7
+ * - Organizes by domain/account/sender structure
8
+ * - Supports + addressing (user+tag@domain.com)
9
+ * - Stores in S3 with proper structure
10
+ * - Triggers SNS notifications
11
+ */
12
+ export declare const handler = "\nconst { S3Client, GetObjectCommand, PutObjectCommand, CopyObjectCommand } = require('@aws-sdk/client-s3');\nconst s3 = new S3Client({});\n\nexports.handler = async (event) => {\n console.log('Inbound email event:', JSON.stringify(event, null, 2));\n\n for (const record of event.Records) {\n try {\n // Handle SES notification via SNS\n const sesNotification = JSON.parse(record.Sns?.Message || record.body || '{}');\n const mail = sesNotification.mail || {};\n const receipt = sesNotification.receipt || {};\n\n const bucket = process.env.EMAIL_BUCKET;\n const messageId = mail.messageId;\n\n if (!messageId) {\n console.log('No messageId found, skipping');\n continue;\n }\n\n // Get the raw email from S3\n const sourceKey = `incoming/${messageId}`;\n let rawEmail;\n\n try {\n const getResult = await s3.send(new GetObjectCommand({\n Bucket: bucket,\n Key: sourceKey,\n }));\n rawEmail = await getResult.Body.transformToString();\n }\ncatch (err) {\n console.log('Could not retrieve raw email:', err.message);\n continue;\n }\n\n // Parse email headers\n const headers = {};\n const headerSection = rawEmail.split('\\n\\n')[0];\n let currentHeader = '';\n\n for (const line of headerSection.split('\\n')) {\n if (line.match(/^[A-Za-z-]+:/)) {\n const colonIndex = line.indexOf(':');\n currentHeader = line.substring(0, colonIndex).toLowerCase();\n headers[currentHeader] = line.substring(colonIndex + 1).trim();\n }\nelse if (currentHeader && (line.startsWith(' ') || line.startsWith('\\t'))) {\n headers[currentHeader] += ' ' + line.trim();\n }\n }\n\n // Extract key metadata\n const from = headers['from'] || '';\n const to = headers['to'] || '';\n const subject = headers['subject'] || '(no subject)';\n const date = headers['date'] || new Date().toISOString();\n\n // Parse sender email\n const fromMatch = from.match(/<([^>]+)>/) || [null, from];\n const fromEmail = fromMatch[1] || from;\n const fromDomain = fromEmail.split('@')[1] || 'unknown';\n\n // Parse recipient email (handle + addressing)\n const toMatch = to.match(/<([^>]+)>/) || [null, to];\n const toEmail = toMatch[1] || to;\n const [localPart, toDomain] = toEmail.split('@');\n const baseLocalPart = localPart.split('+')[0]; // Handle user+tag@domain.com\n const tag = localPart.includes('+') ? localPart.split('+')[1] : null;\n\n // Create timestamp-based path\n const timestamp = new Date(date);\n const year = timestamp.getFullYear();\n const month = String(timestamp.getMonth() + 1).padStart(2, '0');\n const day = String(timestamp.getDate()).padStart(2, '0');\n\n // Organize by: domain/mailbox/year/month/day/sender/messageId\n const destPath = `mailboxes/${toDomain}/${baseLocalPart}/${year}/${month}/${day}/${fromDomain}/${messageId}`;\n\n // Copy raw email to organized location\n await s3.send(CopyObjectCommand({\n Bucket: bucket,\n CopySource: `${bucket}/${sourceKey}`,\n Key: `${destPath}/raw.eml`,\n }));\n\n // Create metadata JSON\n const metadata = {\n messageId,\n from: fromEmail,\n fromName: from.replace(/<[^>]+>/, '').trim(),\n to: toEmail,\n toName: to.replace(/<[^>]+>/, '').trim(),\n subject,\n date: timestamp.toISOString(),\n receivedAt: new Date().toISOString(),\n tag,\n spamVerdict: receipt.spamVerdict?.status || 'UNKNOWN',\n virusVerdict: receipt.virusVerdict?.status || 'UNKNOWN',\n spfVerdict: receipt.spfVerdict?.status || 'UNKNOWN',\n dkimVerdict: receipt.dkimVerdict?.status || 'UNKNOWN',\n dmarcVerdict: receipt.dmarcVerdict?.status || 'UNKNOWN',\n hasAttachments: rawEmail.includes('Content-Disposition: attachment'),\n };\n\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: `${destPath}/metadata.json`,\n Body: JSON.stringify(metadata, null, 2),\n ContentType: 'application/json',\n }));\n\n // Update inbox index\n const indexKey = `mailboxes/${toDomain}/${baseLocalPart}/inbox.json`;\n let inbox = [];\n\n try {\n const indexResult = await s3.send(new GetObjectCommand({\n Bucket: bucket,\n Key: indexKey,\n }));\n inbox = JSON.parse(await indexResult.Body.transformToString());\n }\ncatch {\n // Index doesn't exist yet\n }\n\n inbox.unshift({\n messageId,\n from: fromEmail,\n subject,\n date: timestamp.toISOString(),\n read: false,\n path: destPath,\n });\n\n // Keep only last 1000 emails in index\n inbox = inbox.slice(0, 1000);\n\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: indexKey,\n Body: JSON.stringify(inbox, null, 2),\n ContentType: 'application/json',\n }));\n\n console.log(`Processed email: ${messageId} from ${fromEmail} to ${toEmail}`);\n\n }\ncatch (error) {\n console.error('Error processing email:', error);\n }\n }\n\n return { statusCode: 200, body: 'OK' };\n};\n";
13
+ export default handler;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Outbound Email Lambda Handler
3
+ *
4
+ * Processes outgoing emails:
5
+ * - Accepts JSON email payloads from S3
6
+ * - Generates proper MIME messages
7
+ * - Supports HTML and plain text
8
+ * - Handles attachments (base64 encoded)
9
+ * - Tracks via configuration set
10
+ * - Stores sent emails in S3
11
+ */
12
+ export declare const handler = "\nconst { S3Client, GetObjectCommand, PutObjectCommand, DeleteObjectCommand } = require('@aws-sdk/client-s3');\nconst { SESClient, SendRawEmailCommand } = require('@aws-sdk/client-ses');\n\nconst s3 = new S3Client({});\nconst ses = new SESClient({});\n\nexports.handler = async (event) => {\n console.log('Outbound email event:', JSON.stringify(event, null, 2));\n\n const bucket = process.env.EMAIL_BUCKET;\n const configSet = process.env.CONFIG_SET || 'default';\n\n for (const record of event.Records) {\n try {\n // Get the email payload from S3\n const s3Event = record.s3 || {};\n const key = decodeURIComponent(s3Event.object?.key?.replace(/\\+/g, ' ') || '');\n\n if (!key || !key.startsWith('outbox/')) {\n continue;\n }\n\n const getResult = await s3.send(new GetObjectCommand({\n Bucket: bucket,\n Key: key,\n }));\n\n const emailData = JSON.parse(await getResult.Body.transformToString());\n\n // Build MIME message\n const boundary = `----=_Part_${Date.now()}_${Math.random().toString(36).substr(2)}`;\n const mixedBoundary = `----=_Mixed_${Date.now()}_${Math.random().toString(36).substr(2)}`;\n\n let rawMessage = '';\n\n // Headers\n rawMessage += `From: ${emailData.from}\\r\\n`;\n rawMessage += `To: ${Array.isArray(emailData.to) ? emailData.to.join(', ') : emailData.to}\\r\\n`;\n\n if (emailData.cc) {\n rawMessage += `Cc: ${Array.isArray(emailData.cc) ? emailData.cc.join(', ') : emailData.cc}\\r\\n`;\n }\n\n if (emailData.replyTo) {\n rawMessage += `Reply-To: ${emailData.replyTo}\\r\\n`;\n }\n\n rawMessage += `Subject: =?UTF-8?B?${Buffer.from(emailData.subject || '').toString('base64')}?=\\r\\n`;\n rawMessage += `Date: ${new Date().toUTCString()}\\r\\n`;\n rawMessage += `Message-ID: <${Date.now()}.${Math.random().toString(36)}@${emailData.from.split('@')[1] || 'local'}>\\r\\n`;\n rawMessage += 'MIME-Version: 1.0\\r\\n';\n\n const hasAttachments = emailData.attachments && emailData.attachments.length > 0;\n\n if (hasAttachments) {\n rawMessage += `Content-Type: multipart/mixed; boundary=\"${mixedBoundary}\"\\r\\n\\r\\n`;\n rawMessage += `--${mixedBoundary}\\r\\n`;\n }\n\n // Body (multipart alternative for HTML + text)\n if (emailData.html && emailData.text) {\n rawMessage += `Content-Type: multipart/alternative; boundary=\"${boundary}\"\\r\\n\\r\\n`;\n\n // Plain text part\n rawMessage += `--${boundary}\\r\\n`;\n rawMessage += 'Content-Type: text/plain; charset=UTF-8\\r\\n';\n rawMessage += 'Content-Transfer-Encoding: quoted-printable\\r\\n\\r\\n';\n rawMessage += emailData.text + '\\r\\n\\r\\n';\n\n // HTML part\n rawMessage += `--${boundary}\\r\\n`;\n rawMessage += 'Content-Type: text/html; charset=UTF-8\\r\\n';\n rawMessage += 'Content-Transfer-Encoding: quoted-printable\\r\\n\\r\\n';\n rawMessage += emailData.html + '\\r\\n\\r\\n';\n\n rawMessage += `--${boundary}--\\r\\n`;\n }\nelse if (emailData.html) {\n if (!hasAttachments) {\n rawMessage += 'Content-Type: text/html; charset=UTF-8\\r\\n';\n rawMessage += 'Content-Transfer-Encoding: quoted-printable\\r\\n\\r\\n';\n }\nelse {\n rawMessage += 'Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n';\n }\n rawMessage += emailData.html + '\\r\\n';\n }\nelse {\n if (!hasAttachments) {\n rawMessage += 'Content-Type: text/plain; charset=UTF-8\\r\\n';\n rawMessage += 'Content-Transfer-Encoding: quoted-printable\\r\\n\\r\\n';\n }\nelse {\n rawMessage += 'Content-Type: text/plain; charset=UTF-8\\r\\n\\r\\n';\n }\n rawMessage += (emailData.text || emailData.body || '') + '\\r\\n';\n }\n\n // Attachments\n if (hasAttachments) {\n for (const attachment of emailData.attachments) {\n rawMessage += `--${mixedBoundary}\\r\\n`;\n rawMessage += `Content-Type: ${attachment.contentType || 'application/octet-stream'}; name=\"${attachment.filename}\"\\r\\n`;\n rawMessage += 'Content-Transfer-Encoding: base64\\r\\n';\n rawMessage += `Content-Disposition: attachment; filename=\"${attachment.filename}\"\\r\\n\\r\\n`;\n rawMessage += attachment.content + '\\r\\n';\n }\n rawMessage += `--${mixedBoundary}--\\r\\n`;\n }\n\n // Send via SES\n const sendResult = await ses.send(new SendRawEmailCommand({\n RawMessage: { Data: Buffer.from(rawMessage) },\n ConfigurationSetName: configSet,\n }));\n\n console.log(`Email sent: ${sendResult.MessageId}`);\n\n // Store in sent folder\n const timestamp = new Date();\n const year = timestamp.getFullYear();\n const month = String(timestamp.getMonth() + 1).padStart(2, '0');\n const day = String(timestamp.getDate()).padStart(2, '0');\n\n const fromEmail = emailData.from.match(/<([^>]+)>/) ? emailData.from.match(/<([^>]+)>/)[1] : emailData.from;\n const [localPart, domain] = fromEmail.split('@');\n\n const sentPath = `mailboxes/${domain}/${localPart}/sent/${year}/${month}/${day}/${sendResult.MessageId}`;\n\n // Save sent email metadata\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: `${sentPath}/metadata.json`,\n Body: JSON.stringify({\n messageId: sendResult.MessageId,\n from: emailData.from,\n to: emailData.to,\n cc: emailData.cc,\n subject: emailData.subject,\n sentAt: timestamp.toISOString(),\n hasAttachments,\n }, null, 2),\n ContentType: 'application/json',\n }));\n\n // Save raw message\n await s3.send(new PutObjectCommand({\n Bucket: bucket,\n Key: `${sentPath}/raw.eml`,\n Body: rawMessage,\n ContentType: 'message/rfc822',\n }));\n\n // Delete from outbox\n await s3.send(new DeleteObjectCommand({\n Bucket: bucket,\n Key: key,\n }));\n\n }\ncatch (error) {\n console.error('Error sending email:', error);\n }\n }\n\n return { statusCode: 200, body: 'OK' };\n};\n";
13
+ export default handler;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Email Advanced Features
3
+ * Bounce handling, analytics, reputation monitoring, and template management
4
+ */
5
+ export * from './bounce-handling';
6
+ export * from './analytics';
7
+ export * from './reputation';
8
+ export * from './templates';
9
+ export * as EmailAdvanced from './advanced';
10
+ export * as EmailHandlers from './handlers/inbound';
@@ -0,0 +1,133 @@
1
+ /**
2
+ * SES Sender Reputation Monitoring
3
+ * Reputation tracking, sending limits, and deliverability monitoring
4
+ */
5
+ export interface ReputationDashboard {
6
+ id: string;
7
+ timestamp: Date;
8
+ overallScore: number;
9
+ bounceRate: number;
10
+ complaintRate: number;
11
+ spamReports: number;
12
+ blacklistStatus: BlacklistStatus[];
13
+ dkimStatus: 'VERIFIED' | 'PENDING' | 'FAILED';
14
+ spfStatus: 'PASS' | 'FAIL' | 'SOFTFAIL';
15
+ dmarcStatus: 'PASS' | 'FAIL' | 'NONE';
16
+ sendingLimits: SendingLimits;
17
+ recommendations: string[];
18
+ }
19
+ export interface BlacklistStatus {
20
+ listName: string;
21
+ listed: boolean;
22
+ listedAt?: Date;
23
+ delistUrl?: string;
24
+ }
25
+ export interface SendingLimits {
26
+ maxSendRate: number;
27
+ max24HourSend: number;
28
+ sentLast24Hours: number;
29
+ remainingQuota: number;
30
+ quotaResetTime: Date;
31
+ }
32
+ export interface WarmupPlan {
33
+ id: string;
34
+ name: string;
35
+ startDate: Date;
36
+ currentDay: number;
37
+ totalDays: number;
38
+ dailyLimits: number[];
39
+ currentLimit: number;
40
+ status: 'active' | 'paused' | 'completed';
41
+ }
42
+ export interface DomainReputation {
43
+ id: string;
44
+ domain: string;
45
+ reputationScore: number;
46
+ totalSent: number;
47
+ deliveryRate: number;
48
+ openRate: number;
49
+ clickRate: number;
50
+ bounceRate: number;
51
+ complaintRate: number;
52
+ engagementScore: number;
53
+ }
54
+ /**
55
+ * Sender reputation manager
56
+ */
57
+ export declare class SenderReputationManager {
58
+ private dashboards;
59
+ private warmupPlans;
60
+ private domainReputations;
61
+ private dashboardCounter;
62
+ private warmupCounter;
63
+ private domainCounter;
64
+ /**
65
+ * Get reputation dashboard
66
+ */
67
+ getReputationDashboard(): ReputationDashboard;
68
+ /**
69
+ * Check blacklists
70
+ */
71
+ private checkBlacklists;
72
+ /**
73
+ * Create warmup plan
74
+ */
75
+ createWarmupPlan(options: {
76
+ name: string;
77
+ initialDailyLimit: number;
78
+ targetDailyLimit: number;
79
+ durationDays: number;
80
+ }): WarmupPlan;
81
+ /**
82
+ * Create aggressive warmup plan
83
+ */
84
+ createAggressiveWarmupPlan(options: {
85
+ name: string;
86
+ }): WarmupPlan;
87
+ /**
88
+ * Create conservative warmup plan
89
+ */
90
+ createConservativeWarmupPlan(options: {
91
+ name: string;
92
+ }): WarmupPlan;
93
+ /**
94
+ * Advance warmup plan
95
+ */
96
+ advanceWarmupPlan(warmupId: string): WarmupPlan;
97
+ /**
98
+ * Track domain reputation
99
+ */
100
+ trackDomainReputation(options: {
101
+ domain: string;
102
+ totalSent: number;
103
+ delivered: number;
104
+ opened: number;
105
+ clicked: number;
106
+ bounced: number;
107
+ complained: number;
108
+ }): DomainReputation;
109
+ /**
110
+ * Get domain reputation
111
+ */
112
+ getDomainReputation(domain: string): DomainReputation | undefined;
113
+ /**
114
+ * List all domain reputations
115
+ */
116
+ listDomainReputations(): DomainReputation[];
117
+ /**
118
+ * Get warmup plan
119
+ */
120
+ getWarmupPlan(id: string): WarmupPlan | undefined;
121
+ /**
122
+ * List warmup plans
123
+ */
124
+ listWarmupPlans(): WarmupPlan[];
125
+ /**
126
+ * Clear all data
127
+ */
128
+ clear(): void;
129
+ }
130
+ /**
131
+ * Global sender reputation manager instance
132
+ */
133
+ export declare const senderReputationManager: SenderReputationManager;