@lovable.dev/email-js 0.1.0-rc.1 → 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 CHANGED
@@ -121,3 +121,76 @@ await setEmailUnsubscribe(
121
121
  { apiKey },
122
122
  );
123
123
  ```
124
+
125
+ ### Handling email webhooks
126
+
127
+ `createEmailWebhookHandler` verifies the `X-Lovable-Signature` on each delivery
128
+ (signed with the project's `LOVABLE_API_KEY`) and dispatches to the handler
129
+ registered for the event type. Write only handler bodies — verification stays
130
+ inside the package.
131
+
132
+ ```ts
133
+ import { createEmailWebhookHandler } from "@lovable.dev/email-js";
134
+
135
+ const handler = createEmailWebhookHandler({
136
+ apiKey: Deno.env.get("LOVABLE_API_KEY")!,
137
+ on: {
138
+ "email.bounced": async (event) => {
139
+ await markEmailUndeliverable(event.data.recipient);
140
+ },
141
+ "email.unsubscribed": async (event) => {
142
+ await recordOptOut(event.data.recipient);
143
+ },
144
+ },
145
+ });
146
+
147
+ Deno.serve(handler);
148
+ ```
149
+
150
+ Event types: `email.bounced`, `email.complaint`, `email.unsubscribed`,
151
+ `email.resubscribed` (defined but not yet emitted). Events without a
152
+ registered handler are acknowledged with 200. A handler that throws returns
153
+ 500 and the delivery is retried (up to 5 attempts in total, with backoff) —
154
+ use `event.event_id` (also sent as the `X-Lovable-Delivery` header) to
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,22 @@ 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,
35
+ createEmailWebhookHandler: () => createEmailWebhookHandler,
24
36
  getEmailUnsubscribe: () => getEmailUnsubscribe,
25
37
  listEmailLogs: () => listEmailLogs,
26
38
  parseEmailWebhookPayload: () => parseEmailWebhookPayload,
@@ -29,6 +41,9 @@ __export(src_exports, {
29
41
  });
30
42
  module.exports = __toCommonJS(src_exports);
31
43
 
44
+ // src/auth-email-handler.ts
45
+ var import_webhooks_js2 = require("@lovable.dev/webhooks-js");
46
+
32
47
  // src/http.ts
33
48
  var DEFAULT_AUTH_HEADER = "Authorization";
34
49
  var DEFAULT_API_BASE_URL = "https://api.lovable.dev";
@@ -131,6 +146,148 @@ async function sendLovableEmail(payload, options) {
131
146
  return await response.json();
132
147
  }
133
148
 
149
+ // src/webhook-handler.ts
150
+ var import_webhooks_js = require("@lovable.dev/webhooks-js");
151
+
152
+ // src/webhook.ts
153
+ function parseEmailWebhookPayload(body) {
154
+ const parsed = JSON.parse(body);
155
+ if (!parsed || typeof parsed !== "object") {
156
+ throw new Error("Invalid email webhook payload: missing version or type");
157
+ }
158
+ const payload = parsed;
159
+ if (typeof payload.version !== "string" || typeof payload.type !== "string") {
160
+ throw new Error("Invalid email webhook payload: missing version or type");
161
+ }
162
+ return payload;
163
+ }
164
+
165
+ // src/webhook-handler.ts
166
+ var WEBHOOK_ERROR_STATUS = {
167
+ missing_secret: 401,
168
+ missing_timestamp: 401,
169
+ invalid_timestamp: 401,
170
+ stale_timestamp: 401,
171
+ invalid_signature: 401,
172
+ body_too_large: 400,
173
+ invalid_json: 400,
174
+ invalid_payload: 400
175
+ };
176
+ function parseEmailWebhookEvent(body) {
177
+ return parseEmailWebhookPayload(body);
178
+ }
179
+ function createEmailWebhookHandler(options) {
180
+ const { apiKey, on } = options;
181
+ if (!apiKey) {
182
+ throw new Error("Missing Lovable API key");
183
+ }
184
+ return async (req) => {
185
+ if (req.method !== "POST") {
186
+ return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
187
+ }
188
+ let event;
189
+ try {
190
+ ({ payload: event } = await (0, import_webhooks_js.verifyWebhookRequest)({ req, secret: apiKey, parser: parseEmailWebhookEvent }));
191
+ } catch (error) {
192
+ if (error instanceof import_webhooks_js.WebhookError) {
193
+ return Response.json({ error: error.message }, { status: WEBHOOK_ERROR_STATUS[error.code] });
194
+ }
195
+ console.error("[email-js] webhook verification failed:", error);
196
+ return Response.json({ error: "Webhook verification failed" }, { status: 500 });
197
+ }
198
+ if (event.version !== "1") {
199
+ return Response.json({ received: true });
200
+ }
201
+ const handler = on[event.type];
202
+ if (handler) {
203
+ try {
204
+ await handler(event);
205
+ } catch (error) {
206
+ console.error("[email-js] webhook handler failed:", error);
207
+ return Response.json({ error: "Handler failed" }, { status: 500 });
208
+ }
209
+ }
210
+ return Response.json({ received: true });
211
+ };
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
+
134
291
  // src/logs.ts
135
292
  var LOGS_PATH = "/v1/messaging/email/logs";
136
293
  function buildLogsQuery(filters) {
@@ -177,22 +334,11 @@ async function setEmailUnsubscribe(request, options) {
177
334
  body: { subscribed: request.subscribed }
178
335
  });
179
336
  }
180
-
181
- // src/webhook.ts
182
- function parseEmailWebhookPayload(body) {
183
- const parsed = JSON.parse(body);
184
- if (!parsed || typeof parsed !== "object") {
185
- throw new Error("Invalid email webhook payload: missing version or type");
186
- }
187
- const payload = parsed;
188
- if (typeof payload.version !== "string" || typeof payload.type !== "string") {
189
- throw new Error("Invalid email webhook payload: missing version or type");
190
- }
191
- return payload;
192
- }
193
337
  // Annotate the CommonJS export names for ESM import in node:
194
338
  0 && (module.exports = {
195
339
  EmailAPIError,
340
+ createAuthEmailHandler,
341
+ createEmailWebhookHandler,
196
342
  getEmailUnsubscribe,
197
343
  listEmailLogs,
198
344
  parseEmailWebhookPayload,
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;
@@ -76,6 +79,62 @@ interface EmailUnsubscribeResponse {
76
79
  domain: string;
77
80
  subscribed: boolean;
78
81
  }
82
+ type EmailWebhookEventType = "email.bounced" | "email.complaint" | "email.unsubscribed" | "email.resubscribed";
83
+ interface WebhookEnvelope<Type extends string, Data> {
84
+ event_id: string;
85
+ run_id: string;
86
+ type: Type;
87
+ project_id: string;
88
+ environment: "dev" | "prod";
89
+ data: Data;
90
+ timestamp: string;
91
+ version: string;
92
+ replay_id?: string;
93
+ }
94
+ type EmailWebhookEvent<T extends EmailWebhookEventType = EmailWebhookEventType> = WebhookEnvelope<T, {
95
+ event: T;
96
+ recipient: string;
97
+ message_id: string;
98
+ }>;
99
+ type EmailWebhookHandlers = {
100
+ [T in EmailWebhookEventType]?: (event: EmailWebhookEvent<T>) => void | Promise<void>;
101
+ };
102
+ interface EmailWebhookHandlerOptions {
103
+ apiKey: string;
104
+ on: EmailWebhookHandlers;
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>;
79
138
 
80
139
  declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
81
140
 
@@ -94,4 +153,6 @@ declare function setEmailUnsubscribe(request: SetEmailUnsubscribeRequest, option
94
153
 
95
154
  declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload;
96
155
 
97
- export { EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
156
+ declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
157
+
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;
@@ -76,6 +79,62 @@ interface EmailUnsubscribeResponse {
76
79
  domain: string;
77
80
  subscribed: boolean;
78
81
  }
82
+ type EmailWebhookEventType = "email.bounced" | "email.complaint" | "email.unsubscribed" | "email.resubscribed";
83
+ interface WebhookEnvelope<Type extends string, Data> {
84
+ event_id: string;
85
+ run_id: string;
86
+ type: Type;
87
+ project_id: string;
88
+ environment: "dev" | "prod";
89
+ data: Data;
90
+ timestamp: string;
91
+ version: string;
92
+ replay_id?: string;
93
+ }
94
+ type EmailWebhookEvent<T extends EmailWebhookEventType = EmailWebhookEventType> = WebhookEnvelope<T, {
95
+ event: T;
96
+ recipient: string;
97
+ message_id: string;
98
+ }>;
99
+ type EmailWebhookHandlers = {
100
+ [T in EmailWebhookEventType]?: (event: EmailWebhookEvent<T>) => void | Promise<void>;
101
+ };
102
+ interface EmailWebhookHandlerOptions {
103
+ apiKey: string;
104
+ on: EmailWebhookHandlers;
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>;
79
138
 
80
139
  declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
81
140
 
@@ -94,4 +153,6 @@ declare function setEmailUnsubscribe(request: SetEmailUnsubscribeRequest, option
94
153
 
95
154
  declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload;
96
155
 
97
- export { EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
156
+ declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
157
+
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,6 +103,148 @@ async function sendLovableEmail(payload, options) {
100
103
  return await response.json();
101
104
  }
102
105
 
106
+ // src/webhook-handler.ts
107
+ import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
108
+
109
+ // src/webhook.ts
110
+ function parseEmailWebhookPayload(body) {
111
+ const parsed = JSON.parse(body);
112
+ if (!parsed || typeof parsed !== "object") {
113
+ throw new Error("Invalid email webhook payload: missing version or type");
114
+ }
115
+ const payload = parsed;
116
+ if (typeof payload.version !== "string" || typeof payload.type !== "string") {
117
+ throw new Error("Invalid email webhook payload: missing version or type");
118
+ }
119
+ return payload;
120
+ }
121
+
122
+ // src/webhook-handler.ts
123
+ var WEBHOOK_ERROR_STATUS = {
124
+ missing_secret: 401,
125
+ missing_timestamp: 401,
126
+ invalid_timestamp: 401,
127
+ stale_timestamp: 401,
128
+ invalid_signature: 401,
129
+ body_too_large: 400,
130
+ invalid_json: 400,
131
+ invalid_payload: 400
132
+ };
133
+ function parseEmailWebhookEvent(body) {
134
+ return parseEmailWebhookPayload(body);
135
+ }
136
+ function createEmailWebhookHandler(options) {
137
+ const { apiKey, on } = options;
138
+ if (!apiKey) {
139
+ throw new Error("Missing Lovable API key");
140
+ }
141
+ return async (req) => {
142
+ if (req.method !== "POST") {
143
+ return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
144
+ }
145
+ let event;
146
+ try {
147
+ ({ payload: event } = await verifyWebhookRequest({ req, secret: apiKey, parser: parseEmailWebhookEvent }));
148
+ } catch (error) {
149
+ if (error instanceof WebhookError) {
150
+ return Response.json({ error: error.message }, { status: WEBHOOK_ERROR_STATUS[error.code] });
151
+ }
152
+ console.error("[email-js] webhook verification failed:", error);
153
+ return Response.json({ error: "Webhook verification failed" }, { status: 500 });
154
+ }
155
+ if (event.version !== "1") {
156
+ return Response.json({ received: true });
157
+ }
158
+ const handler = on[event.type];
159
+ if (handler) {
160
+ try {
161
+ await handler(event);
162
+ } catch (error) {
163
+ console.error("[email-js] webhook handler failed:", error);
164
+ return Response.json({ error: "Handler failed" }, { status: 500 });
165
+ }
166
+ }
167
+ return Response.json({ received: true });
168
+ };
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
+
103
248
  // src/logs.ts
104
249
  var LOGS_PATH = "/v1/messaging/email/logs";
105
250
  function buildLogsQuery(filters) {
@@ -146,21 +291,10 @@ async function setEmailUnsubscribe(request, options) {
146
291
  body: { subscribed: request.subscribed }
147
292
  });
148
293
  }
149
-
150
- // src/webhook.ts
151
- function parseEmailWebhookPayload(body) {
152
- const parsed = JSON.parse(body);
153
- if (!parsed || typeof parsed !== "object") {
154
- throw new Error("Invalid email webhook payload: missing version or type");
155
- }
156
- const payload = parsed;
157
- if (typeof payload.version !== "string" || typeof payload.type !== "string") {
158
- throw new Error("Invalid email webhook payload: missing version or type");
159
- }
160
- return payload;
161
- }
162
294
  export {
163
295
  EmailAPIError,
296
+ createAuthEmailHandler,
297
+ createEmailWebhookHandler,
164
298
  getEmailUnsubscribe,
165
299
  listEmailLogs,
166
300
  parseEmailWebhookPayload,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/email-js",
3
- "version": "0.1.0-rc.1",
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",