@lovable.dev/email-js 0.1.0-rc.2 → 0.1.0-rc.3
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 +41 -0
- package/dist/index.cjs +141 -47
- package/dist/index.d.cts +45 -9
- package/dist/index.d.ts +45 -9
- package/dist/index.js +130 -47
- package/package.json +21 -1
package/README.md
CHANGED
|
@@ -153,3 +153,44 @@ registered handler are acknowledged with 200. A handler that throws returns
|
|
|
153
153
|
500 and the delivery is retried (up to 5 attempts in total, with backoff) —
|
|
154
154
|
use `event.event_id` (also sent as the `X-Lovable-Delivery` header) to
|
|
155
155
|
deduplicate redeliveries.
|
|
156
|
+
|
|
157
|
+
### Handling auth email webhooks
|
|
158
|
+
|
|
159
|
+
`createAuthEmailHandler` is the auth counterpart: it verifies the delivery the
|
|
160
|
+
same way, then renders and sends the requested auth email (requires the
|
|
161
|
+
optional `react` and `@react-email/render` peer dependencies). The `emails`
|
|
162
|
+
map is total — all six action types (`signup`, `invite`, `magiclink`,
|
|
163
|
+
`recovery`, `email_change`, `reauthentication`) must be present, so a missing
|
|
164
|
+
handler is a compile error rather than a silently-unsent password reset.
|
|
165
|
+
|
|
166
|
+
```tsx
|
|
167
|
+
import { createAuthEmailHandler } from "@lovable.dev/email-js";
|
|
168
|
+
|
|
169
|
+
const handler = createAuthEmailHandler({
|
|
170
|
+
apiKey: process.env.LOVABLE_API_KEY!,
|
|
171
|
+
from: "My App <noreply@notify.example.com>", // sender domain derived from the address
|
|
172
|
+
sendUrl: process.env.LOVABLE_SEND_URL,
|
|
173
|
+
emails: {
|
|
174
|
+
signup: { subject: "Confirm your email", render: (data) => <SignupEmail confirmationUrl={data.url} /> },
|
|
175
|
+
invite: { subject: "You've been invited", render: (data) => <InviteEmail confirmationUrl={data.url} /> },
|
|
176
|
+
magiclink: { subject: "Your login link", render: (data) => <MagicLinkEmail confirmationUrl={data.url} /> },
|
|
177
|
+
recovery: { subject: "Reset your password", render: (data) => <RecoveryEmail confirmationUrl={data.url} /> },
|
|
178
|
+
email_change: { subject: "Confirm your new email", render: (data) => <EmailChangeEmail confirmationUrl={data.url} /> },
|
|
179
|
+
reauthentication: { subject: "Your verification code", render: (data) => <ReauthenticationEmail token={data.token ?? ""} /> },
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
`render` may be async — look up personalization data first, and fall back
|
|
185
|
+
(`?? "friend"`) instead of throwing when it's missing: auth emails are
|
|
186
|
+
load-bearing. A per-type entry can also be a single async function returning
|
|
187
|
+
`{ subject, element }` when subject and body share one lookup.
|
|
188
|
+
|
|
189
|
+
The auth webhook is a work request, not a notification, so its failure
|
|
190
|
+
semantics differ from `createEmailWebhookHandler`: unknown action types and
|
|
191
|
+
payload versions return 400 (a permanent delivery failure recorded on the
|
|
192
|
+
run) instead of being acked, and a render failure or retryable send failure
|
|
193
|
+
returns 500 so the delivery is retried — the payload's `run_id` doubles as
|
|
194
|
+
the send idempotency key, so retries cannot double-send. Permanent send
|
|
195
|
+
rejections (for example an expired run) also return 400 rather than burning
|
|
196
|
+
retries on a deterministic failure.
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,12 +17,21 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
21
31
|
var src_exports = {};
|
|
22
32
|
__export(src_exports, {
|
|
23
33
|
EmailAPIError: () => EmailAPIError,
|
|
34
|
+
createAuthEmailHandler: () => createAuthEmailHandler,
|
|
24
35
|
createEmailWebhookHandler: () => createEmailWebhookHandler,
|
|
25
36
|
getEmailUnsubscribe: () => getEmailUnsubscribe,
|
|
26
37
|
listEmailLogs: () => listEmailLogs,
|
|
@@ -30,6 +41,9 @@ __export(src_exports, {
|
|
|
30
41
|
});
|
|
31
42
|
module.exports = __toCommonJS(src_exports);
|
|
32
43
|
|
|
44
|
+
// src/auth-email-handler.ts
|
|
45
|
+
var import_webhooks_js2 = require("@lovable.dev/webhooks-js");
|
|
46
|
+
|
|
33
47
|
// src/http.ts
|
|
34
48
|
var DEFAULT_AUTH_HEADER = "Authorization";
|
|
35
49
|
var DEFAULT_API_BASE_URL = "https://api.lovable.dev";
|
|
@@ -132,52 +146,8 @@ async function sendLovableEmail(payload, options) {
|
|
|
132
146
|
return await response.json();
|
|
133
147
|
}
|
|
134
148
|
|
|
135
|
-
// src/
|
|
136
|
-
var
|
|
137
|
-
function buildLogsQuery(filters) {
|
|
138
|
-
const params = new URLSearchParams();
|
|
139
|
-
if (filters.recipient)
|
|
140
|
-
params.set("recipient", filters.recipient);
|
|
141
|
-
if (filters.event_type)
|
|
142
|
-
params.set("event_type", filters.event_type);
|
|
143
|
-
if (filters.status)
|
|
144
|
-
params.set("status", filters.status);
|
|
145
|
-
if (filters.tag)
|
|
146
|
-
params.set("tag", filters.tag);
|
|
147
|
-
if (filters.since)
|
|
148
|
-
params.set("since", filters.since);
|
|
149
|
-
if (filters.until)
|
|
150
|
-
params.set("until", filters.until);
|
|
151
|
-
if (filters.limit !== void 0)
|
|
152
|
-
params.set("limit", String(filters.limit));
|
|
153
|
-
if (filters.cursor)
|
|
154
|
-
params.set("cursor", filters.cursor);
|
|
155
|
-
const query = params.toString();
|
|
156
|
-
return query ? `?${query}` : "";
|
|
157
|
-
}
|
|
158
|
-
async function listEmailLogs(filters, options) {
|
|
159
|
-
const body = await emailApiRequest(options, `${LOGS_PATH}${buildLogsQuery(filters)}`);
|
|
160
|
-
return { ...body, data: body.data ?? [] };
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// src/unsubscribe.ts
|
|
164
|
-
var UNSUBSCRIBES_PATH = "/v1/messaging/email/unsubscribes";
|
|
165
|
-
function buildUnsubscribePath(recipient, domain) {
|
|
166
|
-
if (!recipient.includes("@")) {
|
|
167
|
-
throw new Error("Invalid recipient");
|
|
168
|
-
}
|
|
169
|
-
const query = new URLSearchParams({ domain }).toString();
|
|
170
|
-
return `${UNSUBSCRIBES_PATH}/${encodeURIComponent(recipient)}?${query}`;
|
|
171
|
-
}
|
|
172
|
-
async function getEmailUnsubscribe(request, options) {
|
|
173
|
-
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain));
|
|
174
|
-
}
|
|
175
|
-
async function setEmailUnsubscribe(request, options) {
|
|
176
|
-
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain), {
|
|
177
|
-
method: "PUT",
|
|
178
|
-
body: { subscribed: request.subscribed }
|
|
179
|
-
});
|
|
180
|
-
}
|
|
149
|
+
// src/webhook-handler.ts
|
|
150
|
+
var import_webhooks_js = require("@lovable.dev/webhooks-js");
|
|
181
151
|
|
|
182
152
|
// src/webhook.ts
|
|
183
153
|
function parseEmailWebhookPayload(body) {
|
|
@@ -193,7 +163,6 @@ function parseEmailWebhookPayload(body) {
|
|
|
193
163
|
}
|
|
194
164
|
|
|
195
165
|
// src/webhook-handler.ts
|
|
196
|
-
var import_webhooks_js = require("@lovable.dev/webhooks-js");
|
|
197
166
|
var WEBHOOK_ERROR_STATUS = {
|
|
198
167
|
missing_secret: 401,
|
|
199
168
|
missing_timestamp: 401,
|
|
@@ -241,9 +210,134 @@ function createEmailWebhookHandler(options) {
|
|
|
241
210
|
return Response.json({ received: true });
|
|
242
211
|
};
|
|
243
212
|
}
|
|
213
|
+
|
|
214
|
+
// src/auth-email-handler.ts
|
|
215
|
+
function parseAuthEmailWebhookPayload(body) {
|
|
216
|
+
const parsed = JSON.parse(body);
|
|
217
|
+
const payload = parsed;
|
|
218
|
+
if (!parsed || typeof parsed !== "object" || typeof payload.version !== "string" || payload.type !== "auth" || !payload.data || typeof payload.data !== "object" || typeof payload.data.action_type !== "string" || typeof payload.data.email !== "string") {
|
|
219
|
+
throw new Error("Invalid auth email webhook payload");
|
|
220
|
+
}
|
|
221
|
+
return payload;
|
|
222
|
+
}
|
|
223
|
+
function domainOfAddress(from) {
|
|
224
|
+
const match = /@([^@\s<>]+)>?\s*$/.exec(from.trim());
|
|
225
|
+
return match?.[1];
|
|
226
|
+
}
|
|
227
|
+
function createAuthEmailHandler(options) {
|
|
228
|
+
const { apiKey, from, emails } = options;
|
|
229
|
+
if (!apiKey) {
|
|
230
|
+
throw new Error("Missing Lovable API key");
|
|
231
|
+
}
|
|
232
|
+
const senderDomain = options.senderDomain ?? domainOfAddress(from);
|
|
233
|
+
if (!senderDomain) {
|
|
234
|
+
throw new Error(`Cannot derive a sender domain from "${from}"; pass senderDomain`);
|
|
235
|
+
}
|
|
236
|
+
return async (req) => {
|
|
237
|
+
if (req.method !== "POST") {
|
|
238
|
+
return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
|
|
239
|
+
}
|
|
240
|
+
let event;
|
|
241
|
+
try {
|
|
242
|
+
({ payload: event } = await (0, import_webhooks_js2.verifyWebhookRequest)({ req, secret: apiKey, parser: parseAuthEmailWebhookPayload }));
|
|
243
|
+
} catch (error) {
|
|
244
|
+
if (error instanceof import_webhooks_js2.WebhookError) {
|
|
245
|
+
return Response.json({ error: error.message }, { status: WEBHOOK_ERROR_STATUS[error.code] });
|
|
246
|
+
}
|
|
247
|
+
console.error("[email-js] auth webhook verification failed:", error);
|
|
248
|
+
return Response.json({ error: "Webhook verification failed" }, { status: 500 });
|
|
249
|
+
}
|
|
250
|
+
if (!event.run_id) {
|
|
251
|
+
return Response.json({ error: "Missing run_id" }, { status: 400 });
|
|
252
|
+
}
|
|
253
|
+
if (event.version !== "1") {
|
|
254
|
+
return Response.json({ error: `Unsupported payload version: ${event.version}` }, { status: 400 });
|
|
255
|
+
}
|
|
256
|
+
const actionType = event.data.action_type;
|
|
257
|
+
const definition = Object.prototype.hasOwnProperty.call(emails, actionType) ? emails[actionType] : void 0;
|
|
258
|
+
if (!definition) {
|
|
259
|
+
return Response.json({ error: `Unknown auth email action type: ${actionType}` }, { status: 400 });
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
const { render } = await import("@react-email/render");
|
|
263
|
+
const { subject, element } = typeof definition === "function" ? await definition(event.data) : { subject: definition.subject, element: await definition.render(event.data) };
|
|
264
|
+
const html = await render(element);
|
|
265
|
+
const text = await render(element, { plainText: true });
|
|
266
|
+
await sendLovableEmail(
|
|
267
|
+
{
|
|
268
|
+
run_id: event.run_id,
|
|
269
|
+
to: event.data.email,
|
|
270
|
+
from,
|
|
271
|
+
sender_domain: senderDomain,
|
|
272
|
+
subject,
|
|
273
|
+
html,
|
|
274
|
+
text,
|
|
275
|
+
purpose: "transactional",
|
|
276
|
+
label: actionType
|
|
277
|
+
},
|
|
278
|
+
{ apiKey, sendUrl: options.sendUrl }
|
|
279
|
+
);
|
|
280
|
+
} catch (error) {
|
|
281
|
+
console.error("[email-js] auth email send failed:", error);
|
|
282
|
+
if (error instanceof EmailAPIError && !error.retryable) {
|
|
283
|
+
return Response.json({ error: "Email send rejected" }, { status: 400 });
|
|
284
|
+
}
|
|
285
|
+
return Response.json({ error: "Failed to send email" }, { status: 500 });
|
|
286
|
+
}
|
|
287
|
+
return Response.json({ success: true, sent: true });
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// src/logs.ts
|
|
292
|
+
var LOGS_PATH = "/v1/messaging/email/logs";
|
|
293
|
+
function buildLogsQuery(filters) {
|
|
294
|
+
const params = new URLSearchParams();
|
|
295
|
+
if (filters.recipient)
|
|
296
|
+
params.set("recipient", filters.recipient);
|
|
297
|
+
if (filters.event_type)
|
|
298
|
+
params.set("event_type", filters.event_type);
|
|
299
|
+
if (filters.status)
|
|
300
|
+
params.set("status", filters.status);
|
|
301
|
+
if (filters.tag)
|
|
302
|
+
params.set("tag", filters.tag);
|
|
303
|
+
if (filters.since)
|
|
304
|
+
params.set("since", filters.since);
|
|
305
|
+
if (filters.until)
|
|
306
|
+
params.set("until", filters.until);
|
|
307
|
+
if (filters.limit !== void 0)
|
|
308
|
+
params.set("limit", String(filters.limit));
|
|
309
|
+
if (filters.cursor)
|
|
310
|
+
params.set("cursor", filters.cursor);
|
|
311
|
+
const query = params.toString();
|
|
312
|
+
return query ? `?${query}` : "";
|
|
313
|
+
}
|
|
314
|
+
async function listEmailLogs(filters, options) {
|
|
315
|
+
const body = await emailApiRequest(options, `${LOGS_PATH}${buildLogsQuery(filters)}`);
|
|
316
|
+
return { ...body, data: body.data ?? [] };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// src/unsubscribe.ts
|
|
320
|
+
var UNSUBSCRIBES_PATH = "/v1/messaging/email/unsubscribes";
|
|
321
|
+
function buildUnsubscribePath(recipient, domain) {
|
|
322
|
+
if (!recipient.includes("@")) {
|
|
323
|
+
throw new Error("Invalid recipient");
|
|
324
|
+
}
|
|
325
|
+
const query = new URLSearchParams({ domain }).toString();
|
|
326
|
+
return `${UNSUBSCRIBES_PATH}/${encodeURIComponent(recipient)}?${query}`;
|
|
327
|
+
}
|
|
328
|
+
async function getEmailUnsubscribe(request, options) {
|
|
329
|
+
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain));
|
|
330
|
+
}
|
|
331
|
+
async function setEmailUnsubscribe(request, options) {
|
|
332
|
+
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain), {
|
|
333
|
+
method: "PUT",
|
|
334
|
+
body: { subscribed: request.subscribed }
|
|
335
|
+
});
|
|
336
|
+
}
|
|
244
337
|
// Annotate the CommonJS export names for ESM import in node:
|
|
245
338
|
0 && (module.exports = {
|
|
246
339
|
EmailAPIError,
|
|
340
|
+
createAuthEmailHandler,
|
|
247
341
|
createEmailWebhookHandler,
|
|
248
342
|
getEmailUnsubscribe,
|
|
249
343
|
listEmailLogs,
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ReactElement } from 'react';
|
|
1
2
|
import { EmailWebhookPayload } from '@lovable.dev/webhooks-js';
|
|
2
3
|
export { EmailWebhookPayload } from '@lovable.dev/webhooks-js';
|
|
3
4
|
|
|
@@ -28,7 +29,7 @@ interface SendEmailOptions {
|
|
|
28
29
|
apiKey: string;
|
|
29
30
|
authHeader?: string;
|
|
30
31
|
apiBaseUrl?: string;
|
|
31
|
-
sendUrl?: string;
|
|
32
|
+
sendUrl?: string | undefined;
|
|
32
33
|
idempotencyKey?: string;
|
|
33
34
|
}
|
|
34
35
|
interface EmailClientOptions {
|
|
@@ -61,6 +62,8 @@ interface EmailLogsPagination {
|
|
|
61
62
|
interface ListEmailLogsResponse {
|
|
62
63
|
data: EmailEvent[];
|
|
63
64
|
pagination: EmailLogsPagination;
|
|
65
|
+
/** Earliest timestamp visible under the workspace plan's retention window; an older `since` is clamped to it. */
|
|
66
|
+
history_starts_at: string;
|
|
64
67
|
}
|
|
65
68
|
interface GetEmailUnsubscribeRequest {
|
|
66
69
|
recipient: string;
|
|
@@ -77,21 +80,22 @@ interface EmailUnsubscribeResponse {
|
|
|
77
80
|
subscribed: boolean;
|
|
78
81
|
}
|
|
79
82
|
type EmailWebhookEventType = "email.bounced" | "email.complaint" | "email.unsubscribed" | "email.resubscribed";
|
|
80
|
-
interface
|
|
83
|
+
interface WebhookEnvelope<Type extends string, Data> {
|
|
81
84
|
event_id: string;
|
|
82
85
|
run_id: string;
|
|
83
|
-
type:
|
|
86
|
+
type: Type;
|
|
84
87
|
project_id: string;
|
|
85
88
|
environment: "dev" | "prod";
|
|
86
|
-
data:
|
|
87
|
-
event: T;
|
|
88
|
-
recipient: string;
|
|
89
|
-
message_id: string;
|
|
90
|
-
};
|
|
89
|
+
data: Data;
|
|
91
90
|
timestamp: string;
|
|
92
91
|
version: string;
|
|
93
92
|
replay_id?: string;
|
|
94
93
|
}
|
|
94
|
+
type EmailWebhookEvent<T extends EmailWebhookEventType = EmailWebhookEventType> = WebhookEnvelope<T, {
|
|
95
|
+
event: T;
|
|
96
|
+
recipient: string;
|
|
97
|
+
message_id: string;
|
|
98
|
+
}>;
|
|
95
99
|
type EmailWebhookHandlers = {
|
|
96
100
|
[T in EmailWebhookEventType]?: (event: EmailWebhookEvent<T>) => void | Promise<void>;
|
|
97
101
|
};
|
|
@@ -99,6 +103,38 @@ interface EmailWebhookHandlerOptions {
|
|
|
99
103
|
apiKey: string;
|
|
100
104
|
on: EmailWebhookHandlers;
|
|
101
105
|
}
|
|
106
|
+
type AuthEmailActionType = "signup" | "invite" | "magiclink" | "recovery" | "email_change" | "reauthentication";
|
|
107
|
+
interface AuthEmailHookData {
|
|
108
|
+
action_type: AuthEmailActionType;
|
|
109
|
+
url: string;
|
|
110
|
+
email: string;
|
|
111
|
+
old_email: string | null;
|
|
112
|
+
new_email: string | null;
|
|
113
|
+
site_url: string | null;
|
|
114
|
+
token: string | null;
|
|
115
|
+
new_token: string | null;
|
|
116
|
+
callback_url?: string;
|
|
117
|
+
}
|
|
118
|
+
type AuthEmailWebhookPayload = WebhookEnvelope<"auth", AuthEmailHookData>;
|
|
119
|
+
interface AuthEmailContent {
|
|
120
|
+
subject: string;
|
|
121
|
+
element: ReactElement;
|
|
122
|
+
}
|
|
123
|
+
type AuthEmailDefinition = {
|
|
124
|
+
subject: string;
|
|
125
|
+
render: (data: AuthEmailHookData) => ReactElement | Promise<ReactElement>;
|
|
126
|
+
} | ((data: AuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
|
|
127
|
+
type AuthEmailDefinitions = Record<AuthEmailActionType, AuthEmailDefinition>;
|
|
128
|
+
interface AuthEmailHandlerOptions {
|
|
129
|
+
apiKey: string;
|
|
130
|
+
from: string;
|
|
131
|
+
/** Defaults to the domain of `from`. */
|
|
132
|
+
senderDomain?: string;
|
|
133
|
+
sendUrl?: string | undefined;
|
|
134
|
+
emails: AuthEmailDefinitions;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
declare function createAuthEmailHandler(options: AuthEmailHandlerOptions): (req: Request) => Promise<Response>;
|
|
102
138
|
|
|
103
139
|
declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
|
|
104
140
|
|
|
@@ -119,4 +155,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload;
|
|
|
119
155
|
|
|
120
156
|
declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
|
|
121
157
|
|
|
122
|
-
export { EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
|
|
158
|
+
export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ReactElement } from 'react';
|
|
1
2
|
import { EmailWebhookPayload } from '@lovable.dev/webhooks-js';
|
|
2
3
|
export { EmailWebhookPayload } from '@lovable.dev/webhooks-js';
|
|
3
4
|
|
|
@@ -28,7 +29,7 @@ interface SendEmailOptions {
|
|
|
28
29
|
apiKey: string;
|
|
29
30
|
authHeader?: string;
|
|
30
31
|
apiBaseUrl?: string;
|
|
31
|
-
sendUrl?: string;
|
|
32
|
+
sendUrl?: string | undefined;
|
|
32
33
|
idempotencyKey?: string;
|
|
33
34
|
}
|
|
34
35
|
interface EmailClientOptions {
|
|
@@ -61,6 +62,8 @@ interface EmailLogsPagination {
|
|
|
61
62
|
interface ListEmailLogsResponse {
|
|
62
63
|
data: EmailEvent[];
|
|
63
64
|
pagination: EmailLogsPagination;
|
|
65
|
+
/** Earliest timestamp visible under the workspace plan's retention window; an older `since` is clamped to it. */
|
|
66
|
+
history_starts_at: string;
|
|
64
67
|
}
|
|
65
68
|
interface GetEmailUnsubscribeRequest {
|
|
66
69
|
recipient: string;
|
|
@@ -77,21 +80,22 @@ interface EmailUnsubscribeResponse {
|
|
|
77
80
|
subscribed: boolean;
|
|
78
81
|
}
|
|
79
82
|
type EmailWebhookEventType = "email.bounced" | "email.complaint" | "email.unsubscribed" | "email.resubscribed";
|
|
80
|
-
interface
|
|
83
|
+
interface WebhookEnvelope<Type extends string, Data> {
|
|
81
84
|
event_id: string;
|
|
82
85
|
run_id: string;
|
|
83
|
-
type:
|
|
86
|
+
type: Type;
|
|
84
87
|
project_id: string;
|
|
85
88
|
environment: "dev" | "prod";
|
|
86
|
-
data:
|
|
87
|
-
event: T;
|
|
88
|
-
recipient: string;
|
|
89
|
-
message_id: string;
|
|
90
|
-
};
|
|
89
|
+
data: Data;
|
|
91
90
|
timestamp: string;
|
|
92
91
|
version: string;
|
|
93
92
|
replay_id?: string;
|
|
94
93
|
}
|
|
94
|
+
type EmailWebhookEvent<T extends EmailWebhookEventType = EmailWebhookEventType> = WebhookEnvelope<T, {
|
|
95
|
+
event: T;
|
|
96
|
+
recipient: string;
|
|
97
|
+
message_id: string;
|
|
98
|
+
}>;
|
|
95
99
|
type EmailWebhookHandlers = {
|
|
96
100
|
[T in EmailWebhookEventType]?: (event: EmailWebhookEvent<T>) => void | Promise<void>;
|
|
97
101
|
};
|
|
@@ -99,6 +103,38 @@ interface EmailWebhookHandlerOptions {
|
|
|
99
103
|
apiKey: string;
|
|
100
104
|
on: EmailWebhookHandlers;
|
|
101
105
|
}
|
|
106
|
+
type AuthEmailActionType = "signup" | "invite" | "magiclink" | "recovery" | "email_change" | "reauthentication";
|
|
107
|
+
interface AuthEmailHookData {
|
|
108
|
+
action_type: AuthEmailActionType;
|
|
109
|
+
url: string;
|
|
110
|
+
email: string;
|
|
111
|
+
old_email: string | null;
|
|
112
|
+
new_email: string | null;
|
|
113
|
+
site_url: string | null;
|
|
114
|
+
token: string | null;
|
|
115
|
+
new_token: string | null;
|
|
116
|
+
callback_url?: string;
|
|
117
|
+
}
|
|
118
|
+
type AuthEmailWebhookPayload = WebhookEnvelope<"auth", AuthEmailHookData>;
|
|
119
|
+
interface AuthEmailContent {
|
|
120
|
+
subject: string;
|
|
121
|
+
element: ReactElement;
|
|
122
|
+
}
|
|
123
|
+
type AuthEmailDefinition = {
|
|
124
|
+
subject: string;
|
|
125
|
+
render: (data: AuthEmailHookData) => ReactElement | Promise<ReactElement>;
|
|
126
|
+
} | ((data: AuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
|
|
127
|
+
type AuthEmailDefinitions = Record<AuthEmailActionType, AuthEmailDefinition>;
|
|
128
|
+
interface AuthEmailHandlerOptions {
|
|
129
|
+
apiKey: string;
|
|
130
|
+
from: string;
|
|
131
|
+
/** Defaults to the domain of `from`. */
|
|
132
|
+
senderDomain?: string;
|
|
133
|
+
sendUrl?: string | undefined;
|
|
134
|
+
emails: AuthEmailDefinitions;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
declare function createAuthEmailHandler(options: AuthEmailHandlerOptions): (req: Request) => Promise<Response>;
|
|
102
138
|
|
|
103
139
|
declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
|
|
104
140
|
|
|
@@ -119,4 +155,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload;
|
|
|
119
155
|
|
|
120
156
|
declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
|
|
121
157
|
|
|
122
|
-
export { EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
|
|
158
|
+
export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
// src/auth-email-handler.ts
|
|
2
|
+
import { WebhookError as WebhookError2, verifyWebhookRequest as verifyWebhookRequest2 } from "@lovable.dev/webhooks-js";
|
|
3
|
+
|
|
1
4
|
// src/http.ts
|
|
2
5
|
var DEFAULT_AUTH_HEADER = "Authorization";
|
|
3
6
|
var DEFAULT_API_BASE_URL = "https://api.lovable.dev";
|
|
@@ -100,52 +103,8 @@ async function sendLovableEmail(payload, options) {
|
|
|
100
103
|
return await response.json();
|
|
101
104
|
}
|
|
102
105
|
|
|
103
|
-
// src/
|
|
104
|
-
|
|
105
|
-
function buildLogsQuery(filters) {
|
|
106
|
-
const params = new URLSearchParams();
|
|
107
|
-
if (filters.recipient)
|
|
108
|
-
params.set("recipient", filters.recipient);
|
|
109
|
-
if (filters.event_type)
|
|
110
|
-
params.set("event_type", filters.event_type);
|
|
111
|
-
if (filters.status)
|
|
112
|
-
params.set("status", filters.status);
|
|
113
|
-
if (filters.tag)
|
|
114
|
-
params.set("tag", filters.tag);
|
|
115
|
-
if (filters.since)
|
|
116
|
-
params.set("since", filters.since);
|
|
117
|
-
if (filters.until)
|
|
118
|
-
params.set("until", filters.until);
|
|
119
|
-
if (filters.limit !== void 0)
|
|
120
|
-
params.set("limit", String(filters.limit));
|
|
121
|
-
if (filters.cursor)
|
|
122
|
-
params.set("cursor", filters.cursor);
|
|
123
|
-
const query = params.toString();
|
|
124
|
-
return query ? `?${query}` : "";
|
|
125
|
-
}
|
|
126
|
-
async function listEmailLogs(filters, options) {
|
|
127
|
-
const body = await emailApiRequest(options, `${LOGS_PATH}${buildLogsQuery(filters)}`);
|
|
128
|
-
return { ...body, data: body.data ?? [] };
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// src/unsubscribe.ts
|
|
132
|
-
var UNSUBSCRIBES_PATH = "/v1/messaging/email/unsubscribes";
|
|
133
|
-
function buildUnsubscribePath(recipient, domain) {
|
|
134
|
-
if (!recipient.includes("@")) {
|
|
135
|
-
throw new Error("Invalid recipient");
|
|
136
|
-
}
|
|
137
|
-
const query = new URLSearchParams({ domain }).toString();
|
|
138
|
-
return `${UNSUBSCRIBES_PATH}/${encodeURIComponent(recipient)}?${query}`;
|
|
139
|
-
}
|
|
140
|
-
async function getEmailUnsubscribe(request, options) {
|
|
141
|
-
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain));
|
|
142
|
-
}
|
|
143
|
-
async function setEmailUnsubscribe(request, options) {
|
|
144
|
-
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain), {
|
|
145
|
-
method: "PUT",
|
|
146
|
-
body: { subscribed: request.subscribed }
|
|
147
|
-
});
|
|
148
|
-
}
|
|
106
|
+
// src/webhook-handler.ts
|
|
107
|
+
import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
|
|
149
108
|
|
|
150
109
|
// src/webhook.ts
|
|
151
110
|
function parseEmailWebhookPayload(body) {
|
|
@@ -161,7 +120,6 @@ function parseEmailWebhookPayload(body) {
|
|
|
161
120
|
}
|
|
162
121
|
|
|
163
122
|
// src/webhook-handler.ts
|
|
164
|
-
import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
|
|
165
123
|
var WEBHOOK_ERROR_STATUS = {
|
|
166
124
|
missing_secret: 401,
|
|
167
125
|
missing_timestamp: 401,
|
|
@@ -209,8 +167,133 @@ function createEmailWebhookHandler(options) {
|
|
|
209
167
|
return Response.json({ received: true });
|
|
210
168
|
};
|
|
211
169
|
}
|
|
170
|
+
|
|
171
|
+
// src/auth-email-handler.ts
|
|
172
|
+
function parseAuthEmailWebhookPayload(body) {
|
|
173
|
+
const parsed = JSON.parse(body);
|
|
174
|
+
const payload = parsed;
|
|
175
|
+
if (!parsed || typeof parsed !== "object" || typeof payload.version !== "string" || payload.type !== "auth" || !payload.data || typeof payload.data !== "object" || typeof payload.data.action_type !== "string" || typeof payload.data.email !== "string") {
|
|
176
|
+
throw new Error("Invalid auth email webhook payload");
|
|
177
|
+
}
|
|
178
|
+
return payload;
|
|
179
|
+
}
|
|
180
|
+
function domainOfAddress(from) {
|
|
181
|
+
const match = /@([^@\s<>]+)>?\s*$/.exec(from.trim());
|
|
182
|
+
return match?.[1];
|
|
183
|
+
}
|
|
184
|
+
function createAuthEmailHandler(options) {
|
|
185
|
+
const { apiKey, from, emails } = options;
|
|
186
|
+
if (!apiKey) {
|
|
187
|
+
throw new Error("Missing Lovable API key");
|
|
188
|
+
}
|
|
189
|
+
const senderDomain = options.senderDomain ?? domainOfAddress(from);
|
|
190
|
+
if (!senderDomain) {
|
|
191
|
+
throw new Error(`Cannot derive a sender domain from "${from}"; pass senderDomain`);
|
|
192
|
+
}
|
|
193
|
+
return async (req) => {
|
|
194
|
+
if (req.method !== "POST") {
|
|
195
|
+
return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
|
|
196
|
+
}
|
|
197
|
+
let event;
|
|
198
|
+
try {
|
|
199
|
+
({ payload: event } = await verifyWebhookRequest2({ req, secret: apiKey, parser: parseAuthEmailWebhookPayload }));
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (error instanceof WebhookError2) {
|
|
202
|
+
return Response.json({ error: error.message }, { status: WEBHOOK_ERROR_STATUS[error.code] });
|
|
203
|
+
}
|
|
204
|
+
console.error("[email-js] auth webhook verification failed:", error);
|
|
205
|
+
return Response.json({ error: "Webhook verification failed" }, { status: 500 });
|
|
206
|
+
}
|
|
207
|
+
if (!event.run_id) {
|
|
208
|
+
return Response.json({ error: "Missing run_id" }, { status: 400 });
|
|
209
|
+
}
|
|
210
|
+
if (event.version !== "1") {
|
|
211
|
+
return Response.json({ error: `Unsupported payload version: ${event.version}` }, { status: 400 });
|
|
212
|
+
}
|
|
213
|
+
const actionType = event.data.action_type;
|
|
214
|
+
const definition = Object.prototype.hasOwnProperty.call(emails, actionType) ? emails[actionType] : void 0;
|
|
215
|
+
if (!definition) {
|
|
216
|
+
return Response.json({ error: `Unknown auth email action type: ${actionType}` }, { status: 400 });
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
const { render } = await import("@react-email/render");
|
|
220
|
+
const { subject, element } = typeof definition === "function" ? await definition(event.data) : { subject: definition.subject, element: await definition.render(event.data) };
|
|
221
|
+
const html = await render(element);
|
|
222
|
+
const text = await render(element, { plainText: true });
|
|
223
|
+
await sendLovableEmail(
|
|
224
|
+
{
|
|
225
|
+
run_id: event.run_id,
|
|
226
|
+
to: event.data.email,
|
|
227
|
+
from,
|
|
228
|
+
sender_domain: senderDomain,
|
|
229
|
+
subject,
|
|
230
|
+
html,
|
|
231
|
+
text,
|
|
232
|
+
purpose: "transactional",
|
|
233
|
+
label: actionType
|
|
234
|
+
},
|
|
235
|
+
{ apiKey, sendUrl: options.sendUrl }
|
|
236
|
+
);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
console.error("[email-js] auth email send failed:", error);
|
|
239
|
+
if (error instanceof EmailAPIError && !error.retryable) {
|
|
240
|
+
return Response.json({ error: "Email send rejected" }, { status: 400 });
|
|
241
|
+
}
|
|
242
|
+
return Response.json({ error: "Failed to send email" }, { status: 500 });
|
|
243
|
+
}
|
|
244
|
+
return Response.json({ success: true, sent: true });
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// src/logs.ts
|
|
249
|
+
var LOGS_PATH = "/v1/messaging/email/logs";
|
|
250
|
+
function buildLogsQuery(filters) {
|
|
251
|
+
const params = new URLSearchParams();
|
|
252
|
+
if (filters.recipient)
|
|
253
|
+
params.set("recipient", filters.recipient);
|
|
254
|
+
if (filters.event_type)
|
|
255
|
+
params.set("event_type", filters.event_type);
|
|
256
|
+
if (filters.status)
|
|
257
|
+
params.set("status", filters.status);
|
|
258
|
+
if (filters.tag)
|
|
259
|
+
params.set("tag", filters.tag);
|
|
260
|
+
if (filters.since)
|
|
261
|
+
params.set("since", filters.since);
|
|
262
|
+
if (filters.until)
|
|
263
|
+
params.set("until", filters.until);
|
|
264
|
+
if (filters.limit !== void 0)
|
|
265
|
+
params.set("limit", String(filters.limit));
|
|
266
|
+
if (filters.cursor)
|
|
267
|
+
params.set("cursor", filters.cursor);
|
|
268
|
+
const query = params.toString();
|
|
269
|
+
return query ? `?${query}` : "";
|
|
270
|
+
}
|
|
271
|
+
async function listEmailLogs(filters, options) {
|
|
272
|
+
const body = await emailApiRequest(options, `${LOGS_PATH}${buildLogsQuery(filters)}`);
|
|
273
|
+
return { ...body, data: body.data ?? [] };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// src/unsubscribe.ts
|
|
277
|
+
var UNSUBSCRIBES_PATH = "/v1/messaging/email/unsubscribes";
|
|
278
|
+
function buildUnsubscribePath(recipient, domain) {
|
|
279
|
+
if (!recipient.includes("@")) {
|
|
280
|
+
throw new Error("Invalid recipient");
|
|
281
|
+
}
|
|
282
|
+
const query = new URLSearchParams({ domain }).toString();
|
|
283
|
+
return `${UNSUBSCRIBES_PATH}/${encodeURIComponent(recipient)}?${query}`;
|
|
284
|
+
}
|
|
285
|
+
async function getEmailUnsubscribe(request, options) {
|
|
286
|
+
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain));
|
|
287
|
+
}
|
|
288
|
+
async function setEmailUnsubscribe(request, options) {
|
|
289
|
+
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain), {
|
|
290
|
+
method: "PUT",
|
|
291
|
+
body: { subscribed: request.subscribed }
|
|
292
|
+
});
|
|
293
|
+
}
|
|
212
294
|
export {
|
|
213
295
|
EmailAPIError,
|
|
296
|
+
createAuthEmailHandler,
|
|
214
297
|
createEmailWebhookHandler,
|
|
215
298
|
getEmailUnsubscribe,
|
|
216
299
|
listEmailLogs,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lovable.dev/email-js",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.3",
|
|
4
4
|
"description": "Lovable Email JS",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -23,8 +23,28 @@
|
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@lovable.dev/webhooks-js": "0.0.1"
|
|
25
25
|
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@react-email/render": ">=1.0.0",
|
|
28
|
+
"react": ">=18",
|
|
29
|
+
"react-dom": ">=18"
|
|
30
|
+
},
|
|
31
|
+
"peerDependenciesMeta": {
|
|
32
|
+
"@react-email/render": {
|
|
33
|
+
"optional": true
|
|
34
|
+
},
|
|
35
|
+
"react": {
|
|
36
|
+
"optional": true
|
|
37
|
+
},
|
|
38
|
+
"react-dom": {
|
|
39
|
+
"optional": true
|
|
40
|
+
}
|
|
41
|
+
},
|
|
26
42
|
"devDependencies": {
|
|
43
|
+
"@react-email/render": "^1.0.0",
|
|
27
44
|
"@types/node": "^22",
|
|
45
|
+
"@types/react": "^19",
|
|
46
|
+
"react": "^19.0.0",
|
|
47
|
+
"react-dom": "^19.0.0",
|
|
28
48
|
"rimraf": "^5.0.0",
|
|
29
49
|
"tsup": "^7.2.0",
|
|
30
50
|
"typescript": "^5",
|