@tech4good/platform-email 0.0.0-stage → 0.1.0-alpha.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.
- package/README.md +40 -2
- package/dist/index.d.ts +5 -0
- package/dist/index.js +10 -0
- package/dist/mock.d.ts +14 -0
- package/dist/mock.js +21 -0
- package/dist/resend.d.ts +37 -0
- package/dist/resend.js +101 -0
- package/dist/types.d.ts +31 -0
- package/dist/types.js +2 -0
- package/package.json +32 -4
package/README.md
CHANGED
|
@@ -1,3 +1,41 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@tech4good/platform-email`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Zero-dependency server-side transactional email sender for Tech4Good Firebase Cloud Functions, built around [Resend](https://resend.com) with dry-run and mock adapters for local emulators and tests.
|
|
4
|
+
|
|
5
|
+
> **Server-side only:** Install this package in `functions/package.json` (Node >= 22), never in the Angular browser bundle, so `RESEND_API_KEY` remains protected in Firebase Secret Manager.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { defineSecret } from 'firebase-functions/params';
|
|
11
|
+
import { createResendEmailSender, escapeHtml } from '@tech4good/platform-email';
|
|
12
|
+
|
|
13
|
+
const resendApiKey = defineSecret('RESEND_API_KEY');
|
|
14
|
+
|
|
15
|
+
export function getEmailSender() {
|
|
16
|
+
return createResendEmailSender({
|
|
17
|
+
apiKey: resendApiKey.value(),
|
|
18
|
+
defaultFrom: process.env['EMAIL_FROM'] || 'App <notifications@mail.tech4good.dev>',
|
|
19
|
+
defaultReplyTo: process.env['EMAIL_REPLY_TO'],
|
|
20
|
+
allowDryRunWhenUnconfigured: true,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
await getEmailSender().send({
|
|
25
|
+
to: 'parent@example.com',
|
|
26
|
+
subject: 'Confirmation',
|
|
27
|
+
text: 'Plain text body',
|
|
28
|
+
html: `<p>Hello ${escapeHtml('world')}</p>`,
|
|
29
|
+
idempotencyKey: 'confirm-user-123',
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Testing
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { createMockEmailSender } from '@tech4good/platform-email';
|
|
37
|
+
|
|
38
|
+
const sender = createMockEmailSender();
|
|
39
|
+
await sender.send({ to: 'a@example.test', subject: 'Hi', text: 'Hello' });
|
|
40
|
+
// sender.sent[0].subject === 'Hi'
|
|
41
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type { EmailMessage, EmailSendResult, EmailSender } from './types';
|
|
2
|
+
export { DEFAULT_RESEND_API_URL, ResendEmailError, createResendEmailSender, escapeHtml, } from './resend';
|
|
3
|
+
export type { ResendEmailSenderOptions } from './resend';
|
|
4
|
+
export { createMockEmailSender } from './mock';
|
|
5
|
+
export type { MockEmailSender, MockEmailSenderOptions } from './mock';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createMockEmailSender = exports.escapeHtml = exports.createResendEmailSender = exports.ResendEmailError = exports.DEFAULT_RESEND_API_URL = void 0;
|
|
4
|
+
var resend_1 = require("./resend");
|
|
5
|
+
Object.defineProperty(exports, "DEFAULT_RESEND_API_URL", { enumerable: true, get: function () { return resend_1.DEFAULT_RESEND_API_URL; } });
|
|
6
|
+
Object.defineProperty(exports, "ResendEmailError", { enumerable: true, get: function () { return resend_1.ResendEmailError; } });
|
|
7
|
+
Object.defineProperty(exports, "createResendEmailSender", { enumerable: true, get: function () { return resend_1.createResendEmailSender; } });
|
|
8
|
+
Object.defineProperty(exports, "escapeHtml", { enumerable: true, get: function () { return resend_1.escapeHtml; } });
|
|
9
|
+
var mock_1 = require("./mock");
|
|
10
|
+
Object.defineProperty(exports, "createMockEmailSender", { enumerable: true, get: function () { return mock_1.createMockEmailSender; } });
|
package/dist/mock.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { EmailMessage, EmailSendResult, EmailSender } from './types';
|
|
2
|
+
/** In-memory test double for `EmailSender` that records sent messages. */
|
|
3
|
+
export interface MockEmailSender extends EmailSender {
|
|
4
|
+
/** All messages passed to `send()` since creation or the last `reset()`. */
|
|
5
|
+
readonly sent: EmailMessage[];
|
|
6
|
+
/** Clears recorded messages. */
|
|
7
|
+
reset(): void;
|
|
8
|
+
}
|
|
9
|
+
export interface MockEmailSenderOptions {
|
|
10
|
+
/** Optional hook to simulate failures or return custom IDs in tests. */
|
|
11
|
+
onSend?: (message: EmailMessage, index: number) => Promise<EmailSendResult> | EmailSendResult;
|
|
12
|
+
}
|
|
13
|
+
/** Creates an in-memory `EmailSender` for unit and emulator tests. */
|
|
14
|
+
export declare function createMockEmailSender(options?: MockEmailSenderOptions): MockEmailSender;
|
package/dist/mock.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createMockEmailSender = createMockEmailSender;
|
|
4
|
+
/** Creates an in-memory `EmailSender` for unit and emulator tests. */
|
|
5
|
+
function createMockEmailSender(options = {}) {
|
|
6
|
+
const sent = [];
|
|
7
|
+
return {
|
|
8
|
+
sent,
|
|
9
|
+
reset() {
|
|
10
|
+
sent.length = 0;
|
|
11
|
+
},
|
|
12
|
+
async send(message) {
|
|
13
|
+
const index = sent.length;
|
|
14
|
+
sent.push(message);
|
|
15
|
+
if (options.onSend) {
|
|
16
|
+
return await options.onSend(message, index);
|
|
17
|
+
}
|
|
18
|
+
return { id: `mock-${index + 1}`, dryRun: true };
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
package/dist/resend.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { EmailSender } from './types';
|
|
2
|
+
export declare const DEFAULT_RESEND_API_URL = "https://api.resend.com/emails";
|
|
3
|
+
/** Options for configuring a Resend-backed transactional email sender. */
|
|
4
|
+
export interface ResendEmailSenderOptions {
|
|
5
|
+
/** Resend API key (typically injected from Firebase Secret Manager as `RESEND_API_KEY`). */
|
|
6
|
+
apiKey: string;
|
|
7
|
+
/** Default `from` header used when a message omits `from`. */
|
|
8
|
+
defaultFrom?: string;
|
|
9
|
+
/** Default `reply_to` address(es) used when a message omits `replyTo`. */
|
|
10
|
+
defaultReplyTo?: string | string[];
|
|
11
|
+
/** Override the Resend API endpoint (useful for testing or proxies). */
|
|
12
|
+
apiUrl?: string;
|
|
13
|
+
/** Custom `fetch` implementation for dependency injection in tests. */
|
|
14
|
+
fetchImpl?: typeof fetch;
|
|
15
|
+
/**
|
|
16
|
+
* When `true` and `apiKey` is empty/whitespace (e.g., local Firebase emulators),
|
|
17
|
+
* logs a warning and returns `{ id: 'dry-run', dryRun: true }` instead of throwing.
|
|
18
|
+
*/
|
|
19
|
+
allowDryRunWhenUnconfigured?: boolean;
|
|
20
|
+
/** Logger used for dry-run warnings; defaults to `console`. */
|
|
21
|
+
logger?: Pick<Console, 'warn'>;
|
|
22
|
+
}
|
|
23
|
+
/** Error raised when the Resend API rejects an email delivery request. */
|
|
24
|
+
export declare class ResendEmailError extends Error {
|
|
25
|
+
readonly status: number;
|
|
26
|
+
readonly detail: string;
|
|
27
|
+
constructor(status: number, detail: string);
|
|
28
|
+
}
|
|
29
|
+
/** Escapes HTML special characters for safe interpolation inside HTML email templates. */
|
|
30
|
+
export declare function escapeHtml(value: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* Creates a zero-dependency Resend transactional email sender using Node's built-in `fetch`.
|
|
33
|
+
*
|
|
34
|
+
* Designed for server-side environments (such as Firebase Cloud Functions) so API keys
|
|
35
|
+
* are never bundled into browser code.
|
|
36
|
+
*/
|
|
37
|
+
export declare function createResendEmailSender(options: ResendEmailSenderOptions): EmailSender;
|
package/dist/resend.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ResendEmailError = exports.DEFAULT_RESEND_API_URL = void 0;
|
|
4
|
+
exports.escapeHtml = escapeHtml;
|
|
5
|
+
exports.createResendEmailSender = createResendEmailSender;
|
|
6
|
+
exports.DEFAULT_RESEND_API_URL = 'https://api.resend.com/emails';
|
|
7
|
+
/** Error raised when the Resend API rejects an email delivery request. */
|
|
8
|
+
class ResendEmailError extends Error {
|
|
9
|
+
status;
|
|
10
|
+
detail;
|
|
11
|
+
constructor(status, detail) {
|
|
12
|
+
super(`Resend API error (${status}): ${detail}`);
|
|
13
|
+
this.name = 'ResendEmailError';
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.detail = detail;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
exports.ResendEmailError = ResendEmailError;
|
|
19
|
+
/** Escapes HTML special characters for safe interpolation inside HTML email templates. */
|
|
20
|
+
function escapeHtml(value) {
|
|
21
|
+
return value
|
|
22
|
+
.replace(/&/g, '&')
|
|
23
|
+
.replace(/</g, '<')
|
|
24
|
+
.replace(/>/g, '>')
|
|
25
|
+
.replace(/"/g, '"')
|
|
26
|
+
.replace(/'/g, ''');
|
|
27
|
+
}
|
|
28
|
+
function normalizeAddresses(value) {
|
|
29
|
+
if (!value)
|
|
30
|
+
return [];
|
|
31
|
+
const list = Array.isArray(value) ? value : [value];
|
|
32
|
+
return list.map((entry) => entry.trim()).filter(Boolean);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Creates a zero-dependency Resend transactional email sender using Node's built-in `fetch`.
|
|
36
|
+
*
|
|
37
|
+
* Designed for server-side environments (such as Firebase Cloud Functions) so API keys
|
|
38
|
+
* are never bundled into browser code.
|
|
39
|
+
*/
|
|
40
|
+
function createResendEmailSender(options) {
|
|
41
|
+
const apiKey = options.apiKey.trim();
|
|
42
|
+
const apiUrl = options.apiUrl || exports.DEFAULT_RESEND_API_URL;
|
|
43
|
+
const fetchFn = options.fetchImpl ?? fetch;
|
|
44
|
+
const logger = options.logger ?? console;
|
|
45
|
+
return {
|
|
46
|
+
async send(message) {
|
|
47
|
+
const to = normalizeAddresses(message.to);
|
|
48
|
+
if (to.length === 0) {
|
|
49
|
+
throw new Error('Email message must include at least one recipient in `to`.');
|
|
50
|
+
}
|
|
51
|
+
const from = (message.from ?? options.defaultFrom ?? '').trim();
|
|
52
|
+
if (!from) {
|
|
53
|
+
throw new Error('Email message must specify `from` or configure `defaultFrom`.');
|
|
54
|
+
}
|
|
55
|
+
const subject = message.subject.trim();
|
|
56
|
+
if (!subject) {
|
|
57
|
+
throw new Error('Email message must include a non-empty `subject`.');
|
|
58
|
+
}
|
|
59
|
+
if (!apiKey) {
|
|
60
|
+
if (options.allowDryRunWhenUnconfigured) {
|
|
61
|
+
logger.warn(`[@tech4good/platform-email] RESEND_API_KEY is not configured; dry-run skipping email "${subject}" to ${to.length} recipient(s).`);
|
|
62
|
+
return { id: 'dry-run', dryRun: true };
|
|
63
|
+
}
|
|
64
|
+
throw new Error('RESEND_API_KEY is required to send email via Resend.');
|
|
65
|
+
}
|
|
66
|
+
const replyToList = normalizeAddresses(message.replyTo ?? options.defaultReplyTo);
|
|
67
|
+
const payload = {
|
|
68
|
+
from,
|
|
69
|
+
to,
|
|
70
|
+
subject,
|
|
71
|
+
text: message.text,
|
|
72
|
+
};
|
|
73
|
+
if (message.html !== undefined)
|
|
74
|
+
payload['html'] = message.html;
|
|
75
|
+
if (replyToList.length === 1)
|
|
76
|
+
payload['reply_to'] = replyToList[0];
|
|
77
|
+
else if (replyToList.length > 1)
|
|
78
|
+
payload['reply_to'] = replyToList;
|
|
79
|
+
if (message.tags && message.tags.length > 0)
|
|
80
|
+
payload['tags'] = message.tags;
|
|
81
|
+
const headers = {
|
|
82
|
+
Authorization: `Bearer ${apiKey}`,
|
|
83
|
+
'Content-Type': 'application/json',
|
|
84
|
+
};
|
|
85
|
+
if (message.idempotencyKey?.trim()) {
|
|
86
|
+
headers['Idempotency-Key'] = message.idempotencyKey.trim();
|
|
87
|
+
}
|
|
88
|
+
const response = await fetchFn(apiUrl, {
|
|
89
|
+
method: 'POST',
|
|
90
|
+
headers,
|
|
91
|
+
body: JSON.stringify(payload),
|
|
92
|
+
});
|
|
93
|
+
if (!response.ok) {
|
|
94
|
+
const detail = (await response.text().catch(() => '')) || response.statusText || 'Unknown error';
|
|
95
|
+
throw new ResendEmailError(response.status, detail);
|
|
96
|
+
}
|
|
97
|
+
const body = (await response.json());
|
|
98
|
+
return { id: body.id || 'sent', dryRun: false };
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Provider-agnostic transactional email message payload. */
|
|
2
|
+
export interface EmailMessage {
|
|
3
|
+
/** One or more recipient email addresses. */
|
|
4
|
+
to: string | string[];
|
|
5
|
+
/** Sender address (e.g., `"App Name <notifications@mail.example.org>"`). Falls back to sender `defaultFrom`. */
|
|
6
|
+
from?: string;
|
|
7
|
+
/** Optional reply-to address(es). Falls back to sender `defaultReplyTo`. */
|
|
8
|
+
replyTo?: string | string[];
|
|
9
|
+
/** Email subject line. */
|
|
10
|
+
subject: string;
|
|
11
|
+
/** Plain-text email body (always required for accessibility and deliverability). */
|
|
12
|
+
text: string;
|
|
13
|
+
/** Optional HTML email body. */
|
|
14
|
+
html?: string;
|
|
15
|
+
/** Optional idempotency key forwarded to the provider to prevent duplicate delivery on retries. */
|
|
16
|
+
idempotencyKey?: string;
|
|
17
|
+
/** Optional key-value metadata tags supported by transactional email providers. */
|
|
18
|
+
tags?: Array<{
|
|
19
|
+
name: string;
|
|
20
|
+
value: string;
|
|
21
|
+
}>;
|
|
22
|
+
}
|
|
23
|
+
/** Result returned after a transactional email is accepted (or skipped in dry-run mode). */
|
|
24
|
+
export interface EmailSendResult {
|
|
25
|
+
id: string;
|
|
26
|
+
dryRun?: boolean;
|
|
27
|
+
}
|
|
28
|
+
/** Provider-agnostic server-side transactional email sender interface. */
|
|
29
|
+
export interface EmailSender {
|
|
30
|
+
send(message: EmailMessage): Promise<EmailSendResult>;
|
|
31
|
+
}
|
package/dist/types.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tech4good/platform-email",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "Server-side transactional email sender (Resend + mock/dry-run adapters) for Tech4Good Firebase Cloud Functions.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22"
|
|
22
|
+
},
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsc -p tsconfig.json",
|
|
25
|
+
"test": "tsc -p tsconfig.test.json && jasmine \"test-dist/test/*.spec.js\"",
|
|
26
|
+
"prepack": "npm run build"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/jasmine": "~5.1.0",
|
|
30
|
+
"@types/node": "^18.19.47",
|
|
31
|
+
"jasmine": "^5.1.0",
|
|
32
|
+
"typescript": "~5.8.3"
|
|
33
|
+
}
|
|
34
|
+
}
|