@bernierllc/email-webhook-events 1.4.0 → 1.6.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 (52) hide show
  1. package/dist/EmailWebhookEventsService.js +4 -0
  2. package/dist/EmailWebhookEventsService.js.map +1 -1
  3. package/dist/analytics/AnalyticsEngine.js +2 -1
  4. package/dist/analytics/AnalyticsEngine.js.map +1 -1
  5. package/dist/errors.d.ts +12 -0
  6. package/dist/errors.d.ts.map +1 -0
  7. package/dist/errors.js +25 -0
  8. package/dist/errors.js.map +1 -0
  9. package/dist/index.d.ts +1 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +3 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/persistence/InMemoryPersistenceAdapter.js +2 -4
  14. package/dist/persistence/InMemoryPersistenceAdapter.js.map +1 -1
  15. package/package.json +6 -2
  16. package/.eslintrc.cjs +0 -30
  17. package/CHANGELOG.md +0 -131
  18. package/__tests__/EmailWebhookEventsService.test.ts +0 -251
  19. package/__tests__/WebhookEventCallbacks.test.ts +0 -343
  20. package/__tests__/analytics/AnalyticsEngine.test.ts +0 -250
  21. package/__tests__/fixtures/sendgrid-webhooks/.gitkeep +0 -0
  22. package/__tests__/fixtures/sendgrid-webhooks/README.md +0 -63
  23. package/__tests__/fixtures/sendgrid-webhooks/deferred.json +0 -31
  24. package/__tests__/fixtures/sendgrid-webhooks/delivered.json +0 -83
  25. package/__tests__/fixtures/sendgrid-webhooks/open.json +0 -83
  26. package/__tests__/integration/ngrok-tunnel-manager.ts +0 -88
  27. package/__tests__/integration/sendgrid-webhook-integration.test.ts +0 -272
  28. package/__tests__/integration/webhook-server.ts +0 -188
  29. package/__tests__/mocks/README.md +0 -172
  30. package/__tests__/mocks/index.ts +0 -94
  31. package/__tests__/mocks/sendgrid-api-responses.ts +0 -391
  32. package/__tests__/mocks/sendgrid-webhook-payloads.ts +0 -463
  33. package/__tests__/normalizers/MailgunNormalizer.test.ts +0 -149
  34. package/__tests__/normalizers/PostmarkNormalizer.test.ts +0 -112
  35. package/__tests__/normalizers/SESNormalizer.test.ts +0 -168
  36. package/__tests__/normalizers/SMTP2GONormalizer.test.ts +0 -83
  37. package/__tests__/normalizers/SendGridNormalizer.test.ts +0 -181
  38. package/__tests__/persistence/PersistenceAdapter.test.ts +0 -103
  39. package/jest.config.cjs +0 -38
  40. package/src/EmailWebhookEventsService.ts +0 -290
  41. package/src/analytics/AnalyticsEngine.ts +0 -230
  42. package/src/index.ts +0 -40
  43. package/src/normalizers/EventNormalizer.ts +0 -13
  44. package/src/normalizers/MailgunNormalizer.ts +0 -72
  45. package/src/normalizers/PostmarkNormalizer.ts +0 -72
  46. package/src/normalizers/SESNormalizer.ts +0 -117
  47. package/src/normalizers/SMTP2GONormalizer.ts +0 -54
  48. package/src/normalizers/SendGridNormalizer.ts +0 -63
  49. package/src/persistence/InMemoryPersistenceAdapter.ts +0 -68
  50. package/src/persistence/PersistenceAdapter.ts +0 -15
  51. package/src/types.ts +0 -261
  52. package/tsconfig.json +0 -31
@@ -1,188 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- import express from 'express';
10
- import { writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
11
- import { join } from 'path';
12
-
13
- export interface CapturedWebhook {
14
- headers: Record<string, string>;
15
- body: any;
16
- timestamp: string;
17
- eventType: string;
18
- }
19
-
20
- export class WebhookTestServer {
21
- private app: express.Application;
22
- private server: any;
23
- private capturedWebhooks: CapturedWebhook[] = [];
24
- private fixturesDir: string;
25
- private port: number;
26
-
27
- constructor(port: number = 3000) {
28
- this.port = port;
29
- this.app = express();
30
- this.fixturesDir = join(__dirname, '../fixtures/sendgrid-webhooks');
31
-
32
- // Ensure fixtures directory exists
33
- if (!existsSync(this.fixturesDir)) {
34
- mkdirSync(this.fixturesDir, { recursive: true });
35
- }
36
-
37
- // Middleware to capture raw body
38
- this.app.use(express.json({ verify: (req: any, res, buf) => {
39
- req.rawBody = buf.toString('utf8');
40
- }}));
41
-
42
- // Log all incoming requests
43
- this.app.use((req, res, next) => {
44
- console.log(`📥 ${req.method} ${req.path}`);
45
- next();
46
- });
47
-
48
- // Webhook endpoint - handle both root and /webhooks/sendgrid paths
49
- const webhookHandler = (req: express.Request, res: express.Response) => {
50
- console.log(`✅ Webhook received at ${req.path}`);
51
- const events = Array.isArray(req.body) ? req.body : [req.body];
52
-
53
- events.forEach((event: any) => {
54
- console.log(` 📨 Event: ${event.event} for ${event.email}`);
55
- const captured: CapturedWebhook = {
56
- headers: req.headers as Record<string, string>,
57
- body: event,
58
- timestamp: new Date().toISOString(),
59
- eventType: event.event || 'unknown'
60
- };
61
-
62
- this.capturedWebhooks.push(captured);
63
- this.saveWebhookPayload(captured);
64
- });
65
-
66
- res.status(200).json({ received: true, count: events.length });
67
- };
68
-
69
- // Handle webhooks at root (current SendGrid config)
70
- this.app.post('/', webhookHandler);
71
-
72
- // Also handle webhooks at /webhooks/sendgrid (recommended path)
73
- this.app.post('/webhooks/sendgrid', webhookHandler);
74
-
75
- // Legacy endpoint handler (keep for backward compatibility)
76
- this.app.post('/webhooks/sendgrid-old', (req, res) => {
77
- const events = Array.isArray(req.body) ? req.body : [req.body];
78
-
79
- events.forEach((event: any) => {
80
- const captured: CapturedWebhook = {
81
- headers: req.headers as Record<string, string>,
82
- body: event,
83
- timestamp: new Date().toISOString(),
84
- eventType: event.event || 'unknown'
85
- };
86
-
87
- this.capturedWebhooks.push(captured);
88
- this.saveWebhookPayload(captured);
89
- });
90
-
91
- res.status(200).json({ received: true, count: events.length });
92
- });
93
-
94
- // Health check
95
- this.app.get('/health', (req, res) => {
96
- res.json({ status: 'ok', captured: this.capturedWebhooks.length });
97
- });
98
-
99
- // Catch-all for any other POST (in case SendGrid hits a different path)
100
- this.app.post('*', (req, res) => {
101
- console.log(`⚠️ Unhandled POST to: ${req.path}`);
102
- console.log('Body:', JSON.stringify(req.body, null, 2));
103
-
104
- // Still capture it as a webhook
105
- const events = Array.isArray(req.body) ? req.body : [req.body];
106
- events.forEach((event: any) => {
107
- const captured: CapturedWebhook = {
108
- headers: req.headers as Record<string, string>,
109
- body: event,
110
- timestamp: new Date().toISOString(),
111
- eventType: event.event || 'unknown'
112
- };
113
- this.capturedWebhooks.push(captured);
114
- this.saveWebhookPayload(captured);
115
- });
116
-
117
- res.status(200).json({ received: true, path: req.path });
118
- });
119
-
120
- // 404 handler
121
- this.app.use((req, res) => {
122
- console.log(`❌ 404: ${req.method} ${req.path}`);
123
- res.status(404).json({ error: 'Not found', path: req.path, method: req.method });
124
- });
125
- }
126
-
127
- private saveWebhookPayload(webhook: CapturedWebhook): void {
128
- const eventType = webhook.eventType;
129
- const filePath = join(this.fixturesDir, `${eventType}.json`);
130
-
131
- let existing: CapturedWebhook[] = [];
132
- if (existsSync(filePath)) {
133
- try {
134
- existing = JSON.parse(readFileSync(filePath, 'utf8'));
135
- } catch (error) {
136
- // If file is corrupted, start fresh
137
- console.warn(`Failed to read existing webhook file ${filePath}, starting fresh`);
138
- existing = [];
139
- }
140
- }
141
-
142
- existing.push(webhook);
143
- writeFileSync(filePath, JSON.stringify(existing, null, 2));
144
- }
145
-
146
- async start(): Promise<void> {
147
- return new Promise((resolve, reject) => {
148
- try {
149
- this.server = this.app.listen(this.port, () => {
150
- console.log(`Webhook test server running on port ${this.port}`);
151
- resolve();
152
- });
153
-
154
- this.server.on('error', (error: Error) => {
155
- reject(error);
156
- });
157
- } catch (error) {
158
- reject(error);
159
- }
160
- });
161
- }
162
-
163
- async stop(): Promise<void> {
164
- return new Promise((resolve) => {
165
- if (this.server) {
166
- this.server.close(() => {
167
- console.log('Webhook test server stopped');
168
- resolve();
169
- });
170
- } else {
171
- resolve();
172
- }
173
- });
174
- }
175
-
176
- getCapturedWebhooks(): CapturedWebhook[] {
177
- return [...this.capturedWebhooks];
178
- }
179
-
180
- clearCapturedWebhooks(): void {
181
- this.capturedWebhooks = [];
182
- }
183
-
184
- getPort(): number {
185
- return this.port;
186
- }
187
- }
188
-
@@ -1,172 +0,0 @@
1
- # SendGrid Mock Fixtures
2
-
3
- > **Philosophy: "Only mock services that are not owned by us"**
4
-
5
- These mock fixtures are based on **REAL SendGrid webhook payload structures** captured during integration testing. They accurately reflect the actual format and fields that SendGrid sends.
6
-
7
- > ⚠️ **SANITIZED DATA**: All email addresses, IPs, message IDs, signatures, API keys, and other identifiable data have been replaced with fake test values (using RFC 5737 test IPs like `192.0.2.x` and `example.com` domains). The **structure** is real, the **values** are safe for version control.
8
-
9
- ## Testing Strategy
10
-
11
- | Service Type | Mock Strategy | Example |
12
- |--------------|---------------|---------|
13
- | External APIs | ✅ Mock | SendGrid, Stripe, AWS |
14
- | Internal packages | ❌ Use Real | @bernierllc/*, @unicorn-love/* |
15
-
16
- ### Why This Approach?
17
-
18
- 1. **Confidence**: Tests using real internal packages catch real integration issues
19
- 2. **Accuracy**: Mocks based on real payloads prevent "mock drift"
20
- 3. **Speed**: Mocking external APIs is fast and doesn't require network
21
- 4. **Reliability**: No flaky tests from external service downtime
22
-
23
- ## Available Mocks
24
-
25
- ### Webhook Payloads (Receiving Side)
26
-
27
- For testing webhook processing:
28
-
29
- ```typescript
30
- import {
31
- createDeliveredEvent,
32
- createOpenEvent,
33
- createBounceEvent,
34
- createClickEvent,
35
- createWebhookPayload,
36
- REAL_DELIVERED_EVENT,
37
- REAL_OPEN_EVENT
38
- } from '../mocks';
39
-
40
- // Create a mock delivered webhook
41
- const deliveredEvent = createDeliveredEvent({
42
- email: 'user@example.com'
43
- });
44
-
45
- // Use real captured payload as-is
46
- const realPayload = REAL_DELIVERED_EVENT;
47
-
48
- // Create complete webhook with headers
49
- const webhook = createWebhookPayload(deliveredEvent);
50
- ```
51
-
52
- ### API Responses (Sending Side)
53
-
54
- For testing email sending:
55
-
56
- ```typescript
57
- import {
58
- createSuccessResponse,
59
- createRateLimitResponse,
60
- createValidationErrorResponse,
61
- mockSuccessfulSend,
62
- mockRateLimitThenSuccess
63
- } from '../mocks';
64
-
65
- // Mock successful send
66
- const successResponse = createSuccessResponse();
67
-
68
- // Mock rate limit then success (for retry testing)
69
- const fetchMock = mockRateLimitThenSuccess();
70
- ```
71
-
72
- ## Real Captured Payloads
73
-
74
- These constants contain **actual payloads** from SendGrid:
75
-
76
- | Constant | Description |
77
- |----------|-------------|
78
- | `REAL_SENDGRID_HEADERS` | Actual HTTP headers from webhook requests |
79
- | `REAL_DELIVERED_EVENT` | Real "delivered" event payload |
80
- | `REAL_OPEN_EVENT` | Real "open" event payload |
81
- | `REAL_DEFERRED_EVENT` | Real "deferred" event payload |
82
-
83
- ## Test Scenarios
84
-
85
- Pre-built scenarios for common test cases:
86
-
87
- ```typescript
88
- import {
89
- createEmailLifecycleEvents,
90
- createFailedDeliveryEvents,
91
- createSpamScenarioEvents
92
- } from '../mocks';
93
-
94
- // Email lifecycle: delivered -> open -> click
95
- const lifecycle = createEmailLifecycleEvents('user@example.com');
96
-
97
- // Failed delivery: deferred -> deferred -> bounce
98
- const failedDelivery = createFailedDeliveryEvents('bad@example.com');
99
-
100
- // Spam scenario: delivered -> open -> spam report
101
- const spamReport = createSpamScenarioEvents('user@example.com');
102
- ```
103
-
104
- ## File Structure
105
-
106
- ```
107
- __tests__/mocks/
108
- ├── index.ts # Central exports
109
- ├── sendgrid-webhook-payloads.ts # Webhook receiving mocks
110
- ├── sendgrid-api-responses.ts # API sending mocks
111
- └── README.md # This file
112
-
113
- __tests__/fixtures/sendgrid-webhooks/
114
- ├── delivered.json # Raw captured payloads
115
- ├── open.json
116
- ├── deferred.json
117
- └── README.md
118
- ```
119
-
120
- ## Updating Mocks
121
-
122
- If SendGrid changes their payload format:
123
-
124
- 1. Run the integration tests to capture new payloads:
125
- ```bash
126
- RUN_INTEGRATION_TESTS=true npm test -- sendgrid-webhook-integration --run
127
- ```
128
-
129
- 2. New payloads are saved to `__tests__/fixtures/sendgrid-webhooks/`
130
-
131
- 3. Update the mock factories in `sendgrid-webhook-payloads.ts` with any new fields
132
-
133
- ## Example Test
134
-
135
- ```typescript
136
- // Jest provides describe, it, expect as globals; use jest.fn() instead of vi.fn()
137
- import { EmailWebhookEventsService } from '../../src';
138
- import { createDeliveredEvent, createWebhookPayload } from '../mocks';
139
-
140
- describe('EmailWebhookEventsService', () => {
141
- it('should process a delivered webhook', async () => {
142
- // Arrange - use mock based on real data
143
- const event = createDeliveredEvent({ email: 'test@example.com' });
144
- const payload = createWebhookPayload(event);
145
-
146
- const service = new EmailWebhookEventsService({...});
147
- await service.initialize();
148
-
149
- // Act - use REAL service implementation
150
- const result = await service.processWebhook({
151
- provider: EmailProvider.SENDGRID,
152
- payload: payload.body,
153
- headers: payload.headers
154
- });
155
-
156
- // Assert
157
- expect(result.success).toBe(true);
158
- expect(result.event?.type).toBe('delivered');
159
- });
160
- });
161
- ```
162
-
163
- ## Contributing
164
-
165
- When adding new event types or updating mocks:
166
-
167
- 1. Run integration tests to capture real payloads
168
- 2. Add the new type interface
169
- 3. Create a factory function with sensible defaults
170
- 4. Add the type to the `SendGridWebhookEvent` union
171
- 5. Export from `index.ts`
172
-
@@ -1,94 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- /**
10
- * SendGrid Mock Exports
11
- *
12
- * Central export point for all SendGrid mocks used in testing.
13
- *
14
- * Philosophy: "Only mock services that are not owned by us"
15
- * - SendGrid is an external service → we mock it
16
- * - Our internal @bernierllc/* packages → use real implementations
17
- *
18
- * Usage:
19
- * ```typescript
20
- * import {
21
- * createDeliveredEvent,
22
- * createSuccessResponse,
23
- * REAL_DELIVERED_EVENT
24
- * } from '../mocks';
25
- * ```
26
- */
27
-
28
- // Webhook payload mocks (receiving side)
29
- export {
30
- // Types
31
- type SendGridWebhookHeaders,
32
- type SendGridDeliveredEvent,
33
- type SendGridOpenEvent,
34
- type SendGridDeferredEvent,
35
- type SendGridBounceEvent,
36
- type SendGridClickEvent,
37
- type SendGridSpamReportEvent,
38
- type SendGridUnsubscribeEvent,
39
- type SendGridDroppedEvent,
40
- type SendGridWebhookEvent,
41
- type SendGridWebhookPayload,
42
-
43
- // Real captured payloads
44
- REAL_SENDGRID_HEADERS,
45
- REAL_DELIVERED_EVENT,
46
- REAL_OPEN_EVENT,
47
- REAL_DEFERRED_EVENT,
48
-
49
- // Factory functions
50
- createMockHeaders,
51
- createDeliveredEvent,
52
- createOpenEvent,
53
- createClickEvent,
54
- createBounceEvent,
55
- createDeferredEvent,
56
- createSpamReportEvent,
57
- createUnsubscribeEvent,
58
- createDroppedEvent,
59
- createWebhookPayload,
60
- createBatchedEvents,
61
-
62
- // Test scenarios
63
- createEmailLifecycleEvents,
64
- createFailedDeliveryEvents,
65
- createSpamScenarioEvents
66
- } from './sendgrid-webhook-payloads';
67
-
68
- // API response mocks (sending side)
69
- export {
70
- // Types
71
- type SendGridSuccessResponse,
72
- type SendGridErrorResponse,
73
- type SendGridRateLimitResponse,
74
- type SendGridUserProfile,
75
-
76
- // Factory functions
77
- createSuccessResponse,
78
- createValidationErrorResponse,
79
- createAuthErrorResponse,
80
- createForbiddenResponse,
81
- createSenderIdentityErrorResponse,
82
- createRateLimitResponse,
83
- createServerErrorResponse,
84
- createServiceUnavailableResponse,
85
- createMockFetchResponse,
86
- createUserProfileResponse,
87
-
88
- // Test scenario helpers
89
- mockSuccessfulSend,
90
- mockRateLimitThenSuccess,
91
- mockServerErrorThenSuccess,
92
- mockPermanentFailure
93
- } from './sendgrid-api-responses';
94
-