@lovable.dev/email-js 0.5.1-rc.0 → 0.7.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 CHANGED
@@ -91,15 +91,6 @@ await sendLovableEmail(
91
91
  All clients take the client options (`{ apiKey, apiBaseUrl?, authHeader? }`)
92
92
  as their last argument.
93
93
 
94
- ### Message body uploads
95
-
96
- Every send first uploads the message body (sender, recipients, subject, HTML
97
- and text) to Lovable's storage, then sends the request as before with a
98
- reference to that upload. The upload is best effort: when it cannot be
99
- prepared or completed in time, the SDK logs one `[email-js] upload skipped: …`
100
- warning and sends the body inline, so sends keep working without any change on
101
- your side. There is no option to turn it off.
102
-
103
94
  ### Cc and bcc
104
95
 
105
96
  `cc` and `bcc` take arrays of addresses (`"a@b.com"` or `"Name <a@b.com>"`).
@@ -229,8 +220,19 @@ const handler = createAuthEmailHandler({
229
220
  Projects on Lovable Auth pass `provider: "lovable_auth"`. Lovable Auth sends
230
221
  one-time codes rather than links, so the `emails` map is total over
231
222
  `signup_confirmation`, `sign_in_otp` and `recovery_otp`, and `render` receives
232
- `code` and `expires_at` (ISO 8601) instead of `url` and `token`. The default
233
- provider is `"lovable_cloud"`, the handler shown above.
223
+ `code`, `expires_at` (ISO 8601) and `locale` (the BCP 47 tag of the language the
224
+ user saw on the hosted sign-in page, `en` when unknown) instead of `url` and
225
+ `token`. The default provider is `"lovable_cloud"`, the handler shown above.
226
+
227
+ Two more actions are optional. `email_change_otp` is the code sent to the
228
+ address a signed-in user wants as their new sign-in email, with the same
229
+ `code` and `expires_at` as the other codes. `email_changed_notice` goes to the
230
+ previous address once the change has landed; its `render` receives
231
+ `LovableAuthNoticeEmailHookData`, which has `new_email`, the address the
232
+ account now signs in with, and no `code`. An action the map leaves out is sent
233
+ by Lovable with its built-in copy. A hook that was already active when an
234
+ optional action is added keeps the built-in copy for it until custom auth
235
+ emails are turned on again, which records the new keys.
234
236
 
235
237
  ```tsx
236
238
  const handler = createAuthEmailHandler({
@@ -242,6 +244,8 @@ const handler = createAuthEmailHandler({
242
244
  signup_confirmation: { subject: "Confirm your email", render: (data) => <CodeEmail code={data.code} expiresAt={data.expires_at} /> },
243
245
  sign_in_otp: { subject: "Your sign-in code", render: (data) => <CodeEmail code={data.code} expiresAt={data.expires_at} /> },
244
246
  recovery_otp: { subject: "Reset your password", render: (data) => <CodeEmail code={data.code} expiresAt={data.expires_at} /> },
247
+ email_change_otp: { subject: "Confirm your new email", render: (data) => <CodeEmail code={data.code} expiresAt={data.expires_at} /> },
248
+ email_changed_notice: { subject: "Security alert: your email address was changed", render: (data) => <EmailChangedEmail oldEmail={data.email} newEmail={data.new_email} /> },
245
249
  },
246
250
  });
247
251
  ```
package/dist/index.cjs CHANGED
@@ -1,7 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _lovable_dev_webhooks_js = require("@lovable.dev/webhooks-js");
3
- const SDK_HEADER = "X-Lovable-SDK";
4
- const SDK_HEADER_VALUE = `email-js/0.5.1-rc.0`;
5
3
  function resolveApiBaseUrl(apiBaseUrl) {
6
4
  return (apiBaseUrl ?? "https://api.lovable.dev").replace(/\/$/, "");
7
5
  }
@@ -52,10 +50,7 @@ async function throwIfNotOk(response) {
52
50
  }
53
51
  async function emailApiRequest(options, path, init = { method: "GET" }) {
54
52
  if (!options.apiKey) throw new Error("Missing Lovable API key");
55
- const headers = {
56
- [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey),
57
- [SDK_HEADER]: SDK_HEADER_VALUE
58
- };
53
+ const headers = { [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey) };
59
54
  if (init.body !== void 0) headers["Content-Type"] = "application/json";
60
55
  const response = await fetch(`${resolveApiBaseUrl(options.apiBaseUrl)}${path}`, {
61
56
  method: init.method,
@@ -68,11 +63,6 @@ async function emailApiRequest(options, path, init = { method: "GET" }) {
68
63
  //#endregion
69
64
  //#region src/email.ts
70
65
  const DEFAULT_SEND_PATH = "/v1/messaging/email/send";
71
- const PREPARE_UPLOADS_PATH = "/v1/messaging/email/prepare-uploads";
72
- const DEFAULT_UPLOAD_BUDGET = {
73
- prepareTimeoutMs: 3e3,
74
- putTimeoutMs: 1e4
75
- };
76
66
  const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
77
67
  const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
78
68
  const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
@@ -92,109 +82,27 @@ function formatEmailFrom(from) {
92
82
  return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
93
83
  }
94
84
  async function sendLovableEmail(payload, options) {
95
- return sendLovableEmailWithUploadBudget(payload, options, DEFAULT_UPLOAD_BUDGET);
96
- }
97
- async function sendLovableEmailWithUploadBudget(payload, options, budget) {
98
85
  const apiKey = options.apiKey;
99
86
  if (!apiKey) throw new Error("Missing Lovable API key");
100
87
  const authHeader = options.authHeader ?? "Authorization";
101
88
  const url = options.sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
102
89
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
103
- const apiHeaders = {
90
+ const headers = {
104
91
  [authHeader]: buildAuthHeaderValue(apiKey),
105
- "Content-Type": "application/json",
106
- [SDK_HEADER]: SDK_HEADER_VALUE
107
- };
108
- const headers = idempotencyKey ? {
109
- ...apiHeaders,
110
- "Idempotency-Key": idempotencyKey
111
- } : apiHeaders;
112
- const request = {
113
- ...payload,
114
- from: formatEmailFrom(payload.from)
92
+ "Content-Type": "application/json"
115
93
  };
116
- const bodyPayloadId = await uploadBody(options, apiHeaders, bodyPayloadDocument(request), budget);
117
- if (bodyPayloadId) request.body_payload_id = bodyPayloadId;
94
+ if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
118
95
  const response = await fetch(url, {
119
96
  method: "POST",
120
97
  headers,
121
- body: JSON.stringify(request)
98
+ body: JSON.stringify({
99
+ ...payload,
100
+ from: formatEmailFrom(payload.from)
101
+ })
122
102
  });
123
103
  await throwIfNotOk(response);
124
104
  return await response.json();
125
105
  }
126
- function bodyPayloadDocument(request) {
127
- const document = {
128
- v: 1,
129
- from: request.from,
130
- to: request.to,
131
- subject: request.subject,
132
- html: request.html,
133
- text: request.text
134
- };
135
- if (request.cc?.length) document.cc = request.cc;
136
- if (request.bcc?.length) document.bcc = request.bcc;
137
- if (request.reply_to) document.reply_to = request.reply_to;
138
- if (request.label) document.label = request.label;
139
- if (request.test_mode) document.test_mode = true;
140
- if (request.message_id) document.message_id = request.message_id;
141
- return document;
142
- }
143
- async function uploadBody(options, apiHeaders, document, budget) {
144
- const bytes = new TextEncoder().encode(JSON.stringify(document));
145
- let file;
146
- try {
147
- const prepareUrl = options.sendUrl ? `${new URL(options.sendUrl).origin}${PREPARE_UPLOADS_PATH}` : `${resolveApiBaseUrl(options.apiBaseUrl)}${PREPARE_UPLOADS_PATH}`;
148
- const response = await fetch(prepareUrl, {
149
- method: "POST",
150
- headers: apiHeaders,
151
- body: JSON.stringify({ files: [{ type: "body" }] }),
152
- signal: AbortSignal.timeout(budget.prepareTimeoutMs)
153
- });
154
- if (response.status === 204) return;
155
- if (!response.ok) {
156
- discardBody(response);
157
- return uploadSkipped(`prepare ${response.status}`);
158
- }
159
- file = preparedFile(await response.json());
160
- } catch (error) {
161
- return uploadSkipped(`prepare ${errorClass(error)}`);
162
- }
163
- if (!file) return uploadSkipped("prepare malformed");
164
- if (bytes.byteLength > file.size_limit_bytes) return uploadSkipped("payload above limit");
165
- try {
166
- const response = await fetch(file.upload_url, {
167
- method: "PUT",
168
- headers: {
169
- ...file.headers,
170
- "Content-Type": "application/json"
171
- },
172
- body: bytes,
173
- signal: AbortSignal.timeout(budget.putTimeoutMs)
174
- });
175
- if (!response.ok) {
176
- discardBody(response);
177
- return uploadSkipped(`put ${response.status}`);
178
- }
179
- } catch (error) {
180
- return uploadSkipped(`put ${errorClass(error)}`);
181
- }
182
- return file.payload_id;
183
- }
184
- function preparedFile(prepared) {
185
- const file = prepared?.files?.length === 1 ? prepared.files[0] : void 0;
186
- if (!file || typeof file.payload_id !== "string" || typeof file.upload_url !== "string" || typeof file.size_limit_bytes !== "number" || typeof file.headers !== "object" || file.headers === null) return;
187
- return file;
188
- }
189
- function discardBody(response) {
190
- response.body?.cancel().catch(() => void 0);
191
- }
192
- function uploadSkipped(reason) {
193
- console.warn(`[email-js] upload skipped: ${reason}`);
194
- }
195
- function errorClass(error) {
196
- return error instanceof Error ? error.name : typeof error;
197
- }
198
106
  //#endregion
199
107
  //#region src/webhook.ts
200
108
  function parseEmailWebhookPayload(body) {
@@ -252,10 +160,6 @@ function createEmailWebhookHandler(options) {
252
160
  }
253
161
  //#endregion
254
162
  //#region src/auth-email-handler.ts
255
- const AUTH_EMAIL_UPLOAD_BUDGET = {
256
- prepareTimeoutMs: 1e3,
257
- putTimeoutMs: 2e3
258
- };
259
163
  function parseAuthEmailWebhookPayload(body) {
260
164
  const parsed = JSON.parse(body);
261
165
  const payload = parsed;
@@ -266,10 +170,13 @@ function domainOfAddress(from) {
266
170
  return /@([^@\s<>]+)>?\s*$/.exec(from.trim())?.[1];
267
171
  }
268
172
  function createAuthEmailHandler(options) {
269
- if (options.provider === "lovable_auth") return createHandler(options, options.emails, (data) => typeof data.code === "string" && data.code !== "" ? void 0 : "Missing code");
270
- return createHandler(options, options.emails, () => void 0);
173
+ if (options.provider === "lovable_auth") return createHandler(options, options.emails, (data) => data.action_type === "email_changed_notice" ? typeof data.new_email === "string" && data.new_email !== "" ? void 0 : "Missing new_email" : typeof data.code === "string" && data.code !== "" ? void 0 : "Missing code", (data) => ({
174
+ ...data,
175
+ locale: typeof data.locale === "string" && data.locale !== "" ? data.locale : "en"
176
+ }));
177
+ return createHandler(options, options.emails, () => void 0, (data) => data);
271
178
  }
272
- function createHandler(options, emails, rejectReason) {
179
+ function createHandler(options, emails, rejectReason, normalize) {
273
180
  const { apiKey } = options;
274
181
  if (!apiKey) throw new Error("Missing Lovable API key");
275
182
  const from = formatEmailFrom(options.from);
@@ -302,19 +209,20 @@ function createHandler(options, emails, rejectReason) {
302
209
  action_type: actionType,
303
210
  supported_action_types: Object.keys(emails)
304
211
  }, { status: 400 });
305
- const reason = rejectReason(event.data);
212
+ const data = normalize(event.data);
213
+ const reason = rejectReason(data);
306
214
  if (reason) return Response.json({ error: reason }, { status: 400 });
307
215
  try {
308
216
  const { render } = await import("@react-email/render");
309
- const { subject, element } = typeof definition === "function" ? await definition(event.data) : {
217
+ const { subject, element } = typeof definition === "function" ? await definition(data) : {
310
218
  subject: definition.subject,
311
- element: await definition.render(event.data)
219
+ element: await definition.render(data)
312
220
  };
313
221
  const html = await render(element);
314
222
  const text = await render(element, { plainText: true });
315
- await sendLovableEmailWithUploadBudget({
223
+ await sendLovableEmail({
316
224
  run_id: event.run_id,
317
- to: event.data.email,
225
+ to: data.email,
318
226
  from,
319
227
  sender_domain: senderDomain,
320
228
  reply_to: replyTo,
@@ -326,7 +234,7 @@ function createHandler(options, emails, rejectReason) {
326
234
  }, {
327
235
  apiKey,
328
236
  sendUrl: options.sendUrl
329
- }, AUTH_EMAIL_UPLOAD_BUDGET);
237
+ });
330
238
  } catch (error) {
331
239
  console.error("[email-js] auth email send failed:", error);
332
240
  if (error instanceof EmailAPIError && !error.retryable) return Response.json({ error: "Email send rejected" }, { status: 400 });
package/dist/index.d.cts CHANGED
@@ -132,22 +132,36 @@ type AuthEmailDefinition = {
132
132
  render: (data: AuthEmailHookData) => ReactElement | Promise<ReactElement>;
133
133
  } | ((data: AuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
134
134
  type AuthEmailDefinitions = Record<AuthEmailActionType, AuthEmailDefinition>;
135
- type LovableAuthEmailActionType = "signup_confirmation" | "sign_in_otp" | "recovery_otp";
136
- interface LovableAuthEmailHookData {
137
- action_type: LovableAuthEmailActionType;
135
+ type LovableAuthCodeEmailActionType = "signup_confirmation" | "sign_in_otp" | "recovery_otp" | "email_change_otp";
136
+ type LovableAuthNoticeEmailActionType = "email_changed_notice";
137
+ type LovableAuthEmailActionType = LovableAuthCodeEmailActionType | LovableAuthNoticeEmailActionType;
138
+ interface LovableAuthEmailHookDataBase {
138
139
  email: string;
139
- code: string;
140
- expires_at: string;
140
+ locale: string;
141
141
  url: string | null;
142
142
  site_url: string | null;
143
143
  callback_url?: string;
144
144
  }
145
+ interface LovableAuthCodeEmailHookData extends LovableAuthEmailHookDataBase {
146
+ action_type: LovableAuthCodeEmailActionType;
147
+ code: string;
148
+ expires_at: string;
149
+ }
150
+ interface LovableAuthNoticeEmailHookData extends LovableAuthEmailHookDataBase {
151
+ action_type: LovableAuthNoticeEmailActionType;
152
+ new_email: string;
153
+ }
154
+ type LovableAuthEmailHookData = LovableAuthCodeEmailHookData | LovableAuthNoticeEmailHookData;
145
155
  type LovableAuthEmailWebhookPayload = WebhookEnvelope<"auth", LovableAuthEmailHookData>;
146
- type LovableAuthEmailDefinition = {
156
+ type LovableAuthEmailDefinitionFor<Data extends LovableAuthEmailHookData> = {
147
157
  subject: string;
148
- render: (data: LovableAuthEmailHookData) => ReactElement | Promise<ReactElement>;
149
- } | ((data: LovableAuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
150
- type LovableAuthEmailDefinitions = Record<LovableAuthEmailActionType, LovableAuthEmailDefinition>;
158
+ render: (data: Data) => ReactElement | Promise<ReactElement>;
159
+ } | ((data: Data) => AuthEmailContent | Promise<AuthEmailContent>);
160
+ type LovableAuthEmailDefinition = LovableAuthEmailDefinitionFor<LovableAuthEmailHookData>;
161
+ type LovableAuthEmailDefinitions = Record<"signup_confirmation" | "sign_in_otp" | "recovery_otp", LovableAuthEmailDefinitionFor<LovableAuthCodeEmailHookData>> & {
162
+ email_change_otp?: LovableAuthEmailDefinitionFor<LovableAuthCodeEmailHookData>;
163
+ email_changed_notice?: LovableAuthEmailDefinitionFor<LovableAuthNoticeEmailHookData>;
164
+ };
151
165
  interface AuthEmailHandlerBaseOptions {
152
166
  apiKey: string;
153
167
  from: EmailFrom;
@@ -200,4 +214,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload$1;
200
214
  //#region src/webhook-handler.d.ts
201
215
  declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
202
216
  //#endregion
203
- export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailFrom, type EmailFromParts, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type EmailWebhookPayload, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type LovableAuthEmailActionType, type LovableAuthEmailDefinition, type LovableAuthEmailDefinitions, type LovableAuthEmailHandlerOptions, type LovableAuthEmailHookData, type LovableAuthEmailWebhookPayload, type LovableCloudAuthEmailHandlerOptions, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, formatEmailFrom, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
217
+ export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailFrom, type EmailFromParts, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type EmailWebhookPayload, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type LovableAuthCodeEmailActionType, type LovableAuthCodeEmailHookData, type LovableAuthEmailActionType, type LovableAuthEmailDefinition, type LovableAuthEmailDefinitionFor, type LovableAuthEmailDefinitions, type LovableAuthEmailHandlerOptions, type LovableAuthEmailHookData, type LovableAuthEmailWebhookPayload, type LovableAuthNoticeEmailActionType, type LovableAuthNoticeEmailHookData, type LovableCloudAuthEmailHandlerOptions, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, formatEmailFrom, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
package/dist/index.d.ts CHANGED
@@ -132,22 +132,36 @@ type AuthEmailDefinition = {
132
132
  render: (data: AuthEmailHookData) => ReactElement | Promise<ReactElement>;
133
133
  } | ((data: AuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
134
134
  type AuthEmailDefinitions = Record<AuthEmailActionType, AuthEmailDefinition>;
135
- type LovableAuthEmailActionType = "signup_confirmation" | "sign_in_otp" | "recovery_otp";
136
- interface LovableAuthEmailHookData {
137
- action_type: LovableAuthEmailActionType;
135
+ type LovableAuthCodeEmailActionType = "signup_confirmation" | "sign_in_otp" | "recovery_otp" | "email_change_otp";
136
+ type LovableAuthNoticeEmailActionType = "email_changed_notice";
137
+ type LovableAuthEmailActionType = LovableAuthCodeEmailActionType | LovableAuthNoticeEmailActionType;
138
+ interface LovableAuthEmailHookDataBase {
138
139
  email: string;
139
- code: string;
140
- expires_at: string;
140
+ locale: string;
141
141
  url: string | null;
142
142
  site_url: string | null;
143
143
  callback_url?: string;
144
144
  }
145
+ interface LovableAuthCodeEmailHookData extends LovableAuthEmailHookDataBase {
146
+ action_type: LovableAuthCodeEmailActionType;
147
+ code: string;
148
+ expires_at: string;
149
+ }
150
+ interface LovableAuthNoticeEmailHookData extends LovableAuthEmailHookDataBase {
151
+ action_type: LovableAuthNoticeEmailActionType;
152
+ new_email: string;
153
+ }
154
+ type LovableAuthEmailHookData = LovableAuthCodeEmailHookData | LovableAuthNoticeEmailHookData;
145
155
  type LovableAuthEmailWebhookPayload = WebhookEnvelope<"auth", LovableAuthEmailHookData>;
146
- type LovableAuthEmailDefinition = {
156
+ type LovableAuthEmailDefinitionFor<Data extends LovableAuthEmailHookData> = {
147
157
  subject: string;
148
- render: (data: LovableAuthEmailHookData) => ReactElement | Promise<ReactElement>;
149
- } | ((data: LovableAuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
150
- type LovableAuthEmailDefinitions = Record<LovableAuthEmailActionType, LovableAuthEmailDefinition>;
158
+ render: (data: Data) => ReactElement | Promise<ReactElement>;
159
+ } | ((data: Data) => AuthEmailContent | Promise<AuthEmailContent>);
160
+ type LovableAuthEmailDefinition = LovableAuthEmailDefinitionFor<LovableAuthEmailHookData>;
161
+ type LovableAuthEmailDefinitions = Record<"signup_confirmation" | "sign_in_otp" | "recovery_otp", LovableAuthEmailDefinitionFor<LovableAuthCodeEmailHookData>> & {
162
+ email_change_otp?: LovableAuthEmailDefinitionFor<LovableAuthCodeEmailHookData>;
163
+ email_changed_notice?: LovableAuthEmailDefinitionFor<LovableAuthNoticeEmailHookData>;
164
+ };
151
165
  interface AuthEmailHandlerBaseOptions {
152
166
  apiKey: string;
153
167
  from: EmailFrom;
@@ -200,4 +214,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload$1;
200
214
  //#region src/webhook-handler.d.ts
201
215
  declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
202
216
  //#endregion
203
- export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailFrom, type EmailFromParts, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type EmailWebhookPayload, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type LovableAuthEmailActionType, type LovableAuthEmailDefinition, type LovableAuthEmailDefinitions, type LovableAuthEmailHandlerOptions, type LovableAuthEmailHookData, type LovableAuthEmailWebhookPayload, type LovableCloudAuthEmailHandlerOptions, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, formatEmailFrom, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
217
+ export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailFrom, type EmailFromParts, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type EmailWebhookPayload, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type LovableAuthCodeEmailActionType, type LovableAuthCodeEmailHookData, type LovableAuthEmailActionType, type LovableAuthEmailDefinition, type LovableAuthEmailDefinitionFor, type LovableAuthEmailDefinitions, type LovableAuthEmailHandlerOptions, type LovableAuthEmailHookData, type LovableAuthEmailWebhookPayload, type LovableAuthNoticeEmailActionType, type LovableAuthNoticeEmailHookData, type LovableCloudAuthEmailHandlerOptions, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, formatEmailFrom, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
package/dist/index.js CHANGED
@@ -1,6 +1,4 @@
1
1
  import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
2
- const SDK_HEADER = "X-Lovable-SDK";
3
- const SDK_HEADER_VALUE = `email-js/0.5.1-rc.0`;
4
2
  function resolveApiBaseUrl(apiBaseUrl) {
5
3
  return (apiBaseUrl ?? "https://api.lovable.dev").replace(/\/$/, "");
6
4
  }
@@ -51,10 +49,7 @@ async function throwIfNotOk(response) {
51
49
  }
52
50
  async function emailApiRequest(options, path, init = { method: "GET" }) {
53
51
  if (!options.apiKey) throw new Error("Missing Lovable API key");
54
- const headers = {
55
- [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey),
56
- [SDK_HEADER]: SDK_HEADER_VALUE
57
- };
52
+ const headers = { [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey) };
58
53
  if (init.body !== void 0) headers["Content-Type"] = "application/json";
59
54
  const response = await fetch(`${resolveApiBaseUrl(options.apiBaseUrl)}${path}`, {
60
55
  method: init.method,
@@ -67,11 +62,6 @@ async function emailApiRequest(options, path, init = { method: "GET" }) {
67
62
  //#endregion
68
63
  //#region src/email.ts
69
64
  const DEFAULT_SEND_PATH = "/v1/messaging/email/send";
70
- const PREPARE_UPLOADS_PATH = "/v1/messaging/email/prepare-uploads";
71
- const DEFAULT_UPLOAD_BUDGET = {
72
- prepareTimeoutMs: 3e3,
73
- putTimeoutMs: 1e4
74
- };
75
65
  const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
76
66
  const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
77
67
  const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
@@ -91,109 +81,27 @@ function formatEmailFrom(from) {
91
81
  return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
92
82
  }
93
83
  async function sendLovableEmail(payload, options) {
94
- return sendLovableEmailWithUploadBudget(payload, options, DEFAULT_UPLOAD_BUDGET);
95
- }
96
- async function sendLovableEmailWithUploadBudget(payload, options, budget) {
97
84
  const apiKey = options.apiKey;
98
85
  if (!apiKey) throw new Error("Missing Lovable API key");
99
86
  const authHeader = options.authHeader ?? "Authorization";
100
87
  const url = options.sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
101
88
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
102
- const apiHeaders = {
89
+ const headers = {
103
90
  [authHeader]: buildAuthHeaderValue(apiKey),
104
- "Content-Type": "application/json",
105
- [SDK_HEADER]: SDK_HEADER_VALUE
106
- };
107
- const headers = idempotencyKey ? {
108
- ...apiHeaders,
109
- "Idempotency-Key": idempotencyKey
110
- } : apiHeaders;
111
- const request = {
112
- ...payload,
113
- from: formatEmailFrom(payload.from)
91
+ "Content-Type": "application/json"
114
92
  };
115
- const bodyPayloadId = await uploadBody(options, apiHeaders, bodyPayloadDocument(request), budget);
116
- if (bodyPayloadId) request.body_payload_id = bodyPayloadId;
93
+ if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
117
94
  const response = await fetch(url, {
118
95
  method: "POST",
119
96
  headers,
120
- body: JSON.stringify(request)
97
+ body: JSON.stringify({
98
+ ...payload,
99
+ from: formatEmailFrom(payload.from)
100
+ })
121
101
  });
122
102
  await throwIfNotOk(response);
123
103
  return await response.json();
124
104
  }
125
- function bodyPayloadDocument(request) {
126
- const document = {
127
- v: 1,
128
- from: request.from,
129
- to: request.to,
130
- subject: request.subject,
131
- html: request.html,
132
- text: request.text
133
- };
134
- if (request.cc?.length) document.cc = request.cc;
135
- if (request.bcc?.length) document.bcc = request.bcc;
136
- if (request.reply_to) document.reply_to = request.reply_to;
137
- if (request.label) document.label = request.label;
138
- if (request.test_mode) document.test_mode = true;
139
- if (request.message_id) document.message_id = request.message_id;
140
- return document;
141
- }
142
- async function uploadBody(options, apiHeaders, document, budget) {
143
- const bytes = new TextEncoder().encode(JSON.stringify(document));
144
- let file;
145
- try {
146
- const prepareUrl = options.sendUrl ? `${new URL(options.sendUrl).origin}${PREPARE_UPLOADS_PATH}` : `${resolveApiBaseUrl(options.apiBaseUrl)}${PREPARE_UPLOADS_PATH}`;
147
- const response = await fetch(prepareUrl, {
148
- method: "POST",
149
- headers: apiHeaders,
150
- body: JSON.stringify({ files: [{ type: "body" }] }),
151
- signal: AbortSignal.timeout(budget.prepareTimeoutMs)
152
- });
153
- if (response.status === 204) return;
154
- if (!response.ok) {
155
- discardBody(response);
156
- return uploadSkipped(`prepare ${response.status}`);
157
- }
158
- file = preparedFile(await response.json());
159
- } catch (error) {
160
- return uploadSkipped(`prepare ${errorClass(error)}`);
161
- }
162
- if (!file) return uploadSkipped("prepare malformed");
163
- if (bytes.byteLength > file.size_limit_bytes) return uploadSkipped("payload above limit");
164
- try {
165
- const response = await fetch(file.upload_url, {
166
- method: "PUT",
167
- headers: {
168
- ...file.headers,
169
- "Content-Type": "application/json"
170
- },
171
- body: bytes,
172
- signal: AbortSignal.timeout(budget.putTimeoutMs)
173
- });
174
- if (!response.ok) {
175
- discardBody(response);
176
- return uploadSkipped(`put ${response.status}`);
177
- }
178
- } catch (error) {
179
- return uploadSkipped(`put ${errorClass(error)}`);
180
- }
181
- return file.payload_id;
182
- }
183
- function preparedFile(prepared) {
184
- const file = prepared?.files?.length === 1 ? prepared.files[0] : void 0;
185
- if (!file || typeof file.payload_id !== "string" || typeof file.upload_url !== "string" || typeof file.size_limit_bytes !== "number" || typeof file.headers !== "object" || file.headers === null) return;
186
- return file;
187
- }
188
- function discardBody(response) {
189
- response.body?.cancel().catch(() => void 0);
190
- }
191
- function uploadSkipped(reason) {
192
- console.warn(`[email-js] upload skipped: ${reason}`);
193
- }
194
- function errorClass(error) {
195
- return error instanceof Error ? error.name : typeof error;
196
- }
197
105
  //#endregion
198
106
  //#region src/webhook.ts
199
107
  function parseEmailWebhookPayload(body) {
@@ -251,10 +159,6 @@ function createEmailWebhookHandler(options) {
251
159
  }
252
160
  //#endregion
253
161
  //#region src/auth-email-handler.ts
254
- const AUTH_EMAIL_UPLOAD_BUDGET = {
255
- prepareTimeoutMs: 1e3,
256
- putTimeoutMs: 2e3
257
- };
258
162
  function parseAuthEmailWebhookPayload(body) {
259
163
  const parsed = JSON.parse(body);
260
164
  const payload = parsed;
@@ -265,10 +169,13 @@ function domainOfAddress(from) {
265
169
  return /@([^@\s<>]+)>?\s*$/.exec(from.trim())?.[1];
266
170
  }
267
171
  function createAuthEmailHandler(options) {
268
- if (options.provider === "lovable_auth") return createHandler(options, options.emails, (data) => typeof data.code === "string" && data.code !== "" ? void 0 : "Missing code");
269
- return createHandler(options, options.emails, () => void 0);
172
+ if (options.provider === "lovable_auth") return createHandler(options, options.emails, (data) => data.action_type === "email_changed_notice" ? typeof data.new_email === "string" && data.new_email !== "" ? void 0 : "Missing new_email" : typeof data.code === "string" && data.code !== "" ? void 0 : "Missing code", (data) => ({
173
+ ...data,
174
+ locale: typeof data.locale === "string" && data.locale !== "" ? data.locale : "en"
175
+ }));
176
+ return createHandler(options, options.emails, () => void 0, (data) => data);
270
177
  }
271
- function createHandler(options, emails, rejectReason) {
178
+ function createHandler(options, emails, rejectReason, normalize) {
272
179
  const { apiKey } = options;
273
180
  if (!apiKey) throw new Error("Missing Lovable API key");
274
181
  const from = formatEmailFrom(options.from);
@@ -301,19 +208,20 @@ function createHandler(options, emails, rejectReason) {
301
208
  action_type: actionType,
302
209
  supported_action_types: Object.keys(emails)
303
210
  }, { status: 400 });
304
- const reason = rejectReason(event.data);
211
+ const data = normalize(event.data);
212
+ const reason = rejectReason(data);
305
213
  if (reason) return Response.json({ error: reason }, { status: 400 });
306
214
  try {
307
215
  const { render } = await import("@react-email/render");
308
- const { subject, element } = typeof definition === "function" ? await definition(event.data) : {
216
+ const { subject, element } = typeof definition === "function" ? await definition(data) : {
309
217
  subject: definition.subject,
310
- element: await definition.render(event.data)
218
+ element: await definition.render(data)
311
219
  };
312
220
  const html = await render(element);
313
221
  const text = await render(element, { plainText: true });
314
- await sendLovableEmailWithUploadBudget({
222
+ await sendLovableEmail({
315
223
  run_id: event.run_id,
316
- to: event.data.email,
224
+ to: data.email,
317
225
  from,
318
226
  sender_domain: senderDomain,
319
227
  reply_to: replyTo,
@@ -325,7 +233,7 @@ function createHandler(options, emails, rejectReason) {
325
233
  }, {
326
234
  apiKey,
327
235
  sendUrl: options.sendUrl
328
- }, AUTH_EMAIL_UPLOAD_BUDGET);
236
+ });
329
237
  } catch (error) {
330
238
  console.error("[email-js] auth email send failed:", error);
331
239
  if (error instanceof EmailAPIError && !error.retryable) return Response.json({ error: "Email send rejected" }, { status: 400 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/email-js",
3
- "version": "0.5.1-rc.0",
3
+ "version": "0.7.0",
4
4
  "description": "Lovable Email JS",
5
5
  "repository": {
6
6
  "type": "git",