@lovable.dev/email-js 0.6.0 → 0.8.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,6 +91,17 @@ 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 asks Lovable for an upload slot. When Lovable hands one out,
97
+ the SDK uploads the message body (sender, recipients, subject, HTML and text)
98
+ to Lovable's storage and sends the request as before with a reference to that
99
+ upload. When Lovable hands out none for the workspace, the SDK sends inline as
100
+ before, with no upload and no warning. When the slot request or the upload
101
+ fails or times out, or the body is over the size limit, the SDK logs one
102
+ `[email-js] upload skipped: …` warning and sends the body inline, so sends keep
103
+ working without any change on your side. There is no option to turn it off.
104
+
94
105
  ### Cc and bcc
95
106
 
96
107
  `cc` and `bcc` take arrays of addresses (`"a@b.com"` or `"Name <a@b.com>"`).
@@ -224,6 +235,16 @@ one-time codes rather than links, so the `emails` map is total over
224
235
  user saw on the hosted sign-in page, `en` when unknown) instead of `url` and
225
236
  `token`. The default provider is `"lovable_cloud"`, the handler shown above.
226
237
 
238
+ Two more actions are optional. `email_change_otp` is the code sent to the
239
+ address a signed-in user wants as their new sign-in email, with the same
240
+ `code` and `expires_at` as the other codes. `email_changed_notice` goes to the
241
+ previous address once the change has landed; its `render` receives
242
+ `LovableAuthNoticeEmailHookData`, which has `new_email`, the address the
243
+ account now signs in with, and no `code`. An action the map leaves out is sent
244
+ by Lovable with its built-in copy. A hook that was already active when an
245
+ optional action is added keeps the built-in copy for it until custom auth
246
+ emails are turned on again, which records the new keys.
247
+
227
248
  ```tsx
228
249
  const handler = createAuthEmailHandler({
229
250
  provider: "lovable_auth",
@@ -234,6 +255,8 @@ const handler = createAuthEmailHandler({
234
255
  signup_confirmation: { subject: "Confirm your email", render: (data) => <CodeEmail code={data.code} expiresAt={data.expires_at} /> },
235
256
  sign_in_otp: { subject: "Your sign-in code", render: (data) => <CodeEmail code={data.code} expiresAt={data.expires_at} /> },
236
257
  recovery_otp: { subject: "Reset your password", render: (data) => <CodeEmail code={data.code} expiresAt={data.expires_at} /> },
258
+ email_change_otp: { subject: "Confirm your new email", render: (data) => <CodeEmail code={data.code} expiresAt={data.expires_at} /> },
259
+ email_changed_notice: { subject: "Security alert: your email address was changed", render: (data) => <EmailChangedEmail oldEmail={data.email} newEmail={data.new_email} /> },
237
260
  },
238
261
  });
239
262
  ```
package/dist/index.cjs CHANGED
@@ -1,5 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _lovable_dev_webhooks_js = require("@lovable.dev/webhooks-js");
3
+ const SDK_VERSION = "0.8.0";
4
+ const SDK_HEADER = "X-Lovable-SDK";
5
+ const SDK_HEADER_VALUE = `email-js/${SDK_VERSION}`;
3
6
  function resolveApiBaseUrl(apiBaseUrl) {
4
7
  return (apiBaseUrl ?? "https://api.lovable.dev").replace(/\/$/, "");
5
8
  }
@@ -50,7 +53,10 @@ async function throwIfNotOk(response) {
50
53
  }
51
54
  async function emailApiRequest(options, path, init = { method: "GET" }) {
52
55
  if (!options.apiKey) throw new Error("Missing Lovable API key");
53
- const headers = { [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey) };
56
+ const headers = {
57
+ [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey),
58
+ [SDK_HEADER]: SDK_HEADER_VALUE
59
+ };
54
60
  if (init.body !== void 0) headers["Content-Type"] = "application/json";
55
61
  const response = await fetch(`${resolveApiBaseUrl(options.apiBaseUrl)}${path}`, {
56
62
  method: init.method,
@@ -63,6 +69,11 @@ async function emailApiRequest(options, path, init = { method: "GET" }) {
63
69
  //#endregion
64
70
  //#region src/email.ts
65
71
  const DEFAULT_SEND_PATH = "/v1/messaging/email/send";
72
+ const PREPARE_UPLOADS_PATH = "/v1/messaging/email/prepare-uploads";
73
+ const DEFAULT_UPLOAD_BUDGET = {
74
+ prepareTimeoutMs: 1e4,
75
+ putTimeoutMs: 1e4
76
+ };
66
77
  const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
67
78
  const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
68
79
  const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
@@ -82,27 +93,109 @@ function formatEmailFrom(from) {
82
93
  return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
83
94
  }
84
95
  async function sendLovableEmail(payload, options) {
96
+ return sendLovableEmailWithUploadBudget(payload, options, DEFAULT_UPLOAD_BUDGET);
97
+ }
98
+ async function sendLovableEmailWithUploadBudget(payload, options, budget) {
85
99
  const apiKey = options.apiKey;
86
100
  if (!apiKey) throw new Error("Missing Lovable API key");
87
101
  const authHeader = options.authHeader ?? "Authorization";
88
102
  const url = options.sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
89
103
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
90
- const headers = {
104
+ const apiHeaders = {
91
105
  [authHeader]: buildAuthHeaderValue(apiKey),
92
- "Content-Type": "application/json"
106
+ "Content-Type": "application/json",
107
+ [SDK_HEADER]: SDK_HEADER_VALUE
108
+ };
109
+ const headers = idempotencyKey ? {
110
+ ...apiHeaders,
111
+ "Idempotency-Key": idempotencyKey
112
+ } : apiHeaders;
113
+ const request = {
114
+ ...payload,
115
+ from: formatEmailFrom(payload.from)
93
116
  };
94
- if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
117
+ const bodyPayloadId = await uploadBody(options, apiHeaders, bodyPayloadDocument(request), budget);
118
+ if (bodyPayloadId) request.body_payload_id = bodyPayloadId;
95
119
  const response = await fetch(url, {
96
120
  method: "POST",
97
121
  headers,
98
- body: JSON.stringify({
99
- ...payload,
100
- from: formatEmailFrom(payload.from)
101
- })
122
+ body: JSON.stringify(request)
102
123
  });
103
124
  await throwIfNotOk(response);
104
125
  return await response.json();
105
126
  }
127
+ function bodyPayloadDocument(request) {
128
+ const document = {
129
+ v: 1,
130
+ from: request.from,
131
+ to: request.to,
132
+ subject: request.subject,
133
+ html: request.html,
134
+ text: request.text
135
+ };
136
+ if (request.cc?.length) document.cc = request.cc;
137
+ if (request.bcc?.length) document.bcc = request.bcc;
138
+ if (request.reply_to) document.reply_to = request.reply_to;
139
+ if (request.label) document.label = request.label;
140
+ if (request.test_mode) document.test_mode = true;
141
+ if (request.message_id) document.message_id = request.message_id;
142
+ return document;
143
+ }
144
+ async function uploadBody(options, apiHeaders, document, budget) {
145
+ const bytes = new TextEncoder().encode(JSON.stringify(document));
146
+ let file;
147
+ try {
148
+ const prepareUrl = options.sendUrl ? `${new URL(options.sendUrl).origin}${PREPARE_UPLOADS_PATH}` : `${resolveApiBaseUrl(options.apiBaseUrl)}${PREPARE_UPLOADS_PATH}`;
149
+ const response = await fetch(prepareUrl, {
150
+ method: "POST",
151
+ headers: apiHeaders,
152
+ body: JSON.stringify({ files: [{ type: "body" }] }),
153
+ signal: AbortSignal.timeout(budget.prepareTimeoutMs)
154
+ });
155
+ if (response.status === 204) return;
156
+ if (!response.ok) {
157
+ discardBody(response);
158
+ return uploadSkipped(`prepare ${response.status}`);
159
+ }
160
+ file = preparedFile(await response.json());
161
+ } catch (error) {
162
+ return uploadSkipped(`prepare ${errorClass(error)}`);
163
+ }
164
+ if (!file) return uploadSkipped("prepare malformed");
165
+ if (bytes.byteLength > file.size_limit_bytes) return uploadSkipped("payload above limit");
166
+ try {
167
+ const response = await fetch(file.upload_url, {
168
+ method: "PUT",
169
+ headers: {
170
+ ...file.headers,
171
+ "Content-Type": "application/json"
172
+ },
173
+ body: bytes,
174
+ signal: AbortSignal.timeout(budget.putTimeoutMs)
175
+ });
176
+ if (!response.ok) {
177
+ discardBody(response);
178
+ return uploadSkipped(`put ${response.status}`);
179
+ }
180
+ } catch (error) {
181
+ return uploadSkipped(`put ${errorClass(error)}`);
182
+ }
183
+ return file.payload_id;
184
+ }
185
+ function preparedFile(prepared) {
186
+ const file = prepared?.files?.length === 1 ? prepared.files[0] : void 0;
187
+ 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;
188
+ return file;
189
+ }
190
+ function discardBody(response) {
191
+ response.body?.cancel().catch(() => void 0);
192
+ }
193
+ function uploadSkipped(reason) {
194
+ console.warn(`[email-js] upload skipped: ${reason}`);
195
+ }
196
+ function errorClass(error) {
197
+ return error instanceof Error ? error.name : typeof error;
198
+ }
106
199
  //#endregion
107
200
  //#region src/webhook.ts
108
201
  function parseEmailWebhookPayload(body) {
@@ -170,7 +263,7 @@ function domainOfAddress(from) {
170
263
  return /@([^@\s<>]+)>?\s*$/.exec(from.trim())?.[1];
171
264
  }
172
265
  function createAuthEmailHandler(options) {
173
- if (options.provider === "lovable_auth") return createHandler(options, options.emails, (data) => typeof data.code === "string" && data.code !== "" ? void 0 : "Missing code", (data) => ({
266
+ 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
267
  ...data,
175
268
  locale: typeof data.locale === "string" && data.locale !== "" ? data.locale : "en"
176
269
  }));
package/dist/index.d.cts CHANGED
@@ -132,23 +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;
141
140
  locale: string;
142
141
  url: string | null;
143
142
  site_url: string | null;
144
143
  callback_url?: string;
145
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;
146
155
  type LovableAuthEmailWebhookPayload = WebhookEnvelope<"auth", LovableAuthEmailHookData>;
147
- type LovableAuthEmailDefinition = {
156
+ type LovableAuthEmailDefinitionFor<Data extends LovableAuthEmailHookData> = {
148
157
  subject: string;
149
- render: (data: LovableAuthEmailHookData) => ReactElement | Promise<ReactElement>;
150
- } | ((data: LovableAuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
151
- 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
+ };
152
165
  interface AuthEmailHandlerBaseOptions {
153
166
  apiKey: string;
154
167
  from: EmailFrom;
@@ -201,4 +214,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload$1;
201
214
  //#region src/webhook-handler.d.ts
202
215
  declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
203
216
  //#endregion
204
- 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,23 +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;
141
140
  locale: string;
142
141
  url: string | null;
143
142
  site_url: string | null;
144
143
  callback_url?: string;
145
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;
146
155
  type LovableAuthEmailWebhookPayload = WebhookEnvelope<"auth", LovableAuthEmailHookData>;
147
- type LovableAuthEmailDefinition = {
156
+ type LovableAuthEmailDefinitionFor<Data extends LovableAuthEmailHookData> = {
148
157
  subject: string;
149
- render: (data: LovableAuthEmailHookData) => ReactElement | Promise<ReactElement>;
150
- } | ((data: LovableAuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
151
- 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
+ };
152
165
  interface AuthEmailHandlerBaseOptions {
153
166
  apiKey: string;
154
167
  from: EmailFrom;
@@ -201,4 +214,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload$1;
201
214
  //#region src/webhook-handler.d.ts
202
215
  declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
203
216
  //#endregion
204
- 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,4 +1,7 @@
1
1
  import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
2
+ const SDK_VERSION = "0.8.0";
3
+ const SDK_HEADER = "X-Lovable-SDK";
4
+ const SDK_HEADER_VALUE = `email-js/${SDK_VERSION}`;
2
5
  function resolveApiBaseUrl(apiBaseUrl) {
3
6
  return (apiBaseUrl ?? "https://api.lovable.dev").replace(/\/$/, "");
4
7
  }
@@ -49,7 +52,10 @@ async function throwIfNotOk(response) {
49
52
  }
50
53
  async function emailApiRequest(options, path, init = { method: "GET" }) {
51
54
  if (!options.apiKey) throw new Error("Missing Lovable API key");
52
- const headers = { [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey) };
55
+ const headers = {
56
+ [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey),
57
+ [SDK_HEADER]: SDK_HEADER_VALUE
58
+ };
53
59
  if (init.body !== void 0) headers["Content-Type"] = "application/json";
54
60
  const response = await fetch(`${resolveApiBaseUrl(options.apiBaseUrl)}${path}`, {
55
61
  method: init.method,
@@ -62,6 +68,11 @@ async function emailApiRequest(options, path, init = { method: "GET" }) {
62
68
  //#endregion
63
69
  //#region src/email.ts
64
70
  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: 1e4,
74
+ putTimeoutMs: 1e4
75
+ };
65
76
  const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
66
77
  const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
67
78
  const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
@@ -81,27 +92,109 @@ function formatEmailFrom(from) {
81
92
  return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
82
93
  }
83
94
  async function sendLovableEmail(payload, options) {
95
+ return sendLovableEmailWithUploadBudget(payload, options, DEFAULT_UPLOAD_BUDGET);
96
+ }
97
+ async function sendLovableEmailWithUploadBudget(payload, options, budget) {
84
98
  const apiKey = options.apiKey;
85
99
  if (!apiKey) throw new Error("Missing Lovable API key");
86
100
  const authHeader = options.authHeader ?? "Authorization";
87
101
  const url = options.sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
88
102
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
89
- const headers = {
103
+ const apiHeaders = {
90
104
  [authHeader]: buildAuthHeaderValue(apiKey),
91
- "Content-Type": "application/json"
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
115
  };
93
- if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
116
+ const bodyPayloadId = await uploadBody(options, apiHeaders, bodyPayloadDocument(request), budget);
117
+ if (bodyPayloadId) request.body_payload_id = bodyPayloadId;
94
118
  const response = await fetch(url, {
95
119
  method: "POST",
96
120
  headers,
97
- body: JSON.stringify({
98
- ...payload,
99
- from: formatEmailFrom(payload.from)
100
- })
121
+ body: JSON.stringify(request)
101
122
  });
102
123
  await throwIfNotOk(response);
103
124
  return await response.json();
104
125
  }
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
+ }
105
198
  //#endregion
106
199
  //#region src/webhook.ts
107
200
  function parseEmailWebhookPayload(body) {
@@ -169,7 +262,7 @@ function domainOfAddress(from) {
169
262
  return /@([^@\s<>]+)>?\s*$/.exec(from.trim())?.[1];
170
263
  }
171
264
  function createAuthEmailHandler(options) {
172
- if (options.provider === "lovable_auth") return createHandler(options, options.emails, (data) => typeof data.code === "string" && data.code !== "" ? void 0 : "Missing code", (data) => ({
265
+ 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
266
  ...data,
174
267
  locale: typeof data.locale === "string" && data.locale !== "" ? data.locale : "en"
175
268
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/email-js",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Lovable Email JS",
5
5
  "repository": {
6
6
  "type": "git",