@lovable.dev/email-js 0.4.0 → 0.5.1-rc.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,15 @@ 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
+
94
103
  ### Cc and bcc
95
104
 
96
105
  `cc` and `bcc` take arrays of addresses (`"a@b.com"` or `"Name <a@b.com>"`).
@@ -253,4 +262,7 @@ run) instead of being acked, and a render failure or retryable send failure
253
262
  returns 500 so the delivery is retried — the payload's `run_id` doubles as
254
263
  the send idempotency key, so retries cannot double-send. Permanent send
255
264
  rejections (for example an expired run) also return 400 rather than burning
256
- retries on a deterministic failure.
265
+ retries on a deterministic failure. The 400 for an unknown action type carries
266
+ `{ "error": "unsupported_action_type", "action_type": "<type>", "supported_action_types": [...] }`,
267
+ the keys of your `emails` map, so the caller can tell a missing template from
268
+ any other rejection.
package/dist/index.cjs CHANGED
@@ -1,5 +1,7 @@
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`;
3
5
  function resolveApiBaseUrl(apiBaseUrl) {
4
6
  return (apiBaseUrl ?? "https://api.lovable.dev").replace(/\/$/, "");
5
7
  }
@@ -50,7 +52,10 @@ async function throwIfNotOk(response) {
50
52
  }
51
53
  async function emailApiRequest(options, path, init = { method: "GET" }) {
52
54
  if (!options.apiKey) throw new Error("Missing Lovable API key");
53
- 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
+ };
54
59
  if (init.body !== void 0) headers["Content-Type"] = "application/json";
55
60
  const response = await fetch(`${resolveApiBaseUrl(options.apiBaseUrl)}${path}`, {
56
61
  method: init.method,
@@ -63,6 +68,11 @@ async function emailApiRequest(options, path, init = { method: "GET" }) {
63
68
  //#endregion
64
69
  //#region src/email.ts
65
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: 3e3,
74
+ putTimeoutMs: 1e4
75
+ };
66
76
  const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
67
77
  const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
68
78
  const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
@@ -82,27 +92,109 @@ function formatEmailFrom(from) {
82
92
  return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
83
93
  }
84
94
  async function sendLovableEmail(payload, options) {
95
+ return sendLovableEmailWithUploadBudget(payload, options, DEFAULT_UPLOAD_BUDGET);
96
+ }
97
+ async function sendLovableEmailWithUploadBudget(payload, options, budget) {
85
98
  const apiKey = options.apiKey;
86
99
  if (!apiKey) throw new Error("Missing Lovable API key");
87
100
  const authHeader = options.authHeader ?? "Authorization";
88
101
  const url = options.sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
89
102
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
90
- const headers = {
103
+ const apiHeaders = {
91
104
  [authHeader]: buildAuthHeaderValue(apiKey),
92
- "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)
93
115
  };
94
- if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
116
+ const bodyPayloadId = await uploadBody(options, apiHeaders, bodyPayloadDocument(request), budget);
117
+ if (bodyPayloadId) request.body_payload_id = bodyPayloadId;
95
118
  const response = await fetch(url, {
96
119
  method: "POST",
97
120
  headers,
98
- body: JSON.stringify({
99
- ...payload,
100
- from: formatEmailFrom(payload.from)
101
- })
121
+ body: JSON.stringify(request)
102
122
  });
103
123
  await throwIfNotOk(response);
104
124
  return await response.json();
105
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
+ }
106
198
  //#endregion
107
199
  //#region src/webhook.ts
108
200
  function parseEmailWebhookPayload(body) {
@@ -160,6 +252,10 @@ function createEmailWebhookHandler(options) {
160
252
  }
161
253
  //#endregion
162
254
  //#region src/auth-email-handler.ts
255
+ const AUTH_EMAIL_UPLOAD_BUDGET = {
256
+ prepareTimeoutMs: 1e3,
257
+ putTimeoutMs: 2e3
258
+ };
163
259
  function parseAuthEmailWebhookPayload(body) {
164
260
  const parsed = JSON.parse(body);
165
261
  const payload = parsed;
@@ -201,7 +297,11 @@ function createHandler(options, emails, rejectReason) {
201
297
  if (event.version !== "1") return Response.json({ error: `Unsupported payload version: ${event.version}` }, { status: 400 });
202
298
  const actionType = event.data.action_type;
203
299
  const definition = Object.prototype.hasOwnProperty.call(emails, actionType) ? emails[actionType] : void 0;
204
- if (!definition) return Response.json({ error: `Unknown auth email action type: ${actionType}` }, { status: 400 });
300
+ if (!definition) return Response.json({
301
+ error: "unsupported_action_type",
302
+ action_type: actionType,
303
+ supported_action_types: Object.keys(emails)
304
+ }, { status: 400 });
205
305
  const reason = rejectReason(event.data);
206
306
  if (reason) return Response.json({ error: reason }, { status: 400 });
207
307
  try {
@@ -212,7 +312,7 @@ function createHandler(options, emails, rejectReason) {
212
312
  };
213
313
  const html = await render(element);
214
314
  const text = await render(element, { plainText: true });
215
- await sendLovableEmail({
315
+ await sendLovableEmailWithUploadBudget({
216
316
  run_id: event.run_id,
217
317
  to: event.data.email,
218
318
  from,
@@ -226,7 +326,7 @@ function createHandler(options, emails, rejectReason) {
226
326
  }, {
227
327
  apiKey,
228
328
  sendUrl: options.sendUrl
229
- });
329
+ }, AUTH_EMAIL_UPLOAD_BUDGET);
230
330
  } catch (error) {
231
331
  console.error("[email-js] auth email send failed:", error);
232
332
  if (error instanceof EmailAPIError && !error.retryable) return Response.json({ error: "Email send rejected" }, { status: 400 });
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
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`;
2
4
  function resolveApiBaseUrl(apiBaseUrl) {
3
5
  return (apiBaseUrl ?? "https://api.lovable.dev").replace(/\/$/, "");
4
6
  }
@@ -49,7 +51,10 @@ async function throwIfNotOk(response) {
49
51
  }
50
52
  async function emailApiRequest(options, path, init = { method: "GET" }) {
51
53
  if (!options.apiKey) throw new Error("Missing Lovable API key");
52
- const headers = { [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey) };
54
+ const headers = {
55
+ [options.authHeader ?? "Authorization"]: buildAuthHeaderValue(options.apiKey),
56
+ [SDK_HEADER]: SDK_HEADER_VALUE
57
+ };
53
58
  if (init.body !== void 0) headers["Content-Type"] = "application/json";
54
59
  const response = await fetch(`${resolveApiBaseUrl(options.apiBaseUrl)}${path}`, {
55
60
  method: init.method,
@@ -62,6 +67,11 @@ async function emailApiRequest(options, path, init = { method: "GET" }) {
62
67
  //#endregion
63
68
  //#region src/email.ts
64
69
  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
+ };
65
75
  const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
66
76
  const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
67
77
  const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
@@ -81,27 +91,109 @@ function formatEmailFrom(from) {
81
91
  return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
82
92
  }
83
93
  async function sendLovableEmail(payload, options) {
94
+ return sendLovableEmailWithUploadBudget(payload, options, DEFAULT_UPLOAD_BUDGET);
95
+ }
96
+ async function sendLovableEmailWithUploadBudget(payload, options, budget) {
84
97
  const apiKey = options.apiKey;
85
98
  if (!apiKey) throw new Error("Missing Lovable API key");
86
99
  const authHeader = options.authHeader ?? "Authorization";
87
100
  const url = options.sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
88
101
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
89
- const headers = {
102
+ const apiHeaders = {
90
103
  [authHeader]: buildAuthHeaderValue(apiKey),
91
- "Content-Type": "application/json"
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)
92
114
  };
93
- if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
115
+ const bodyPayloadId = await uploadBody(options, apiHeaders, bodyPayloadDocument(request), budget);
116
+ if (bodyPayloadId) request.body_payload_id = bodyPayloadId;
94
117
  const response = await fetch(url, {
95
118
  method: "POST",
96
119
  headers,
97
- body: JSON.stringify({
98
- ...payload,
99
- from: formatEmailFrom(payload.from)
100
- })
120
+ body: JSON.stringify(request)
101
121
  });
102
122
  await throwIfNotOk(response);
103
123
  return await response.json();
104
124
  }
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
+ }
105
197
  //#endregion
106
198
  //#region src/webhook.ts
107
199
  function parseEmailWebhookPayload(body) {
@@ -159,6 +251,10 @@ function createEmailWebhookHandler(options) {
159
251
  }
160
252
  //#endregion
161
253
  //#region src/auth-email-handler.ts
254
+ const AUTH_EMAIL_UPLOAD_BUDGET = {
255
+ prepareTimeoutMs: 1e3,
256
+ putTimeoutMs: 2e3
257
+ };
162
258
  function parseAuthEmailWebhookPayload(body) {
163
259
  const parsed = JSON.parse(body);
164
260
  const payload = parsed;
@@ -200,7 +296,11 @@ function createHandler(options, emails, rejectReason) {
200
296
  if (event.version !== "1") return Response.json({ error: `Unsupported payload version: ${event.version}` }, { status: 400 });
201
297
  const actionType = event.data.action_type;
202
298
  const definition = Object.prototype.hasOwnProperty.call(emails, actionType) ? emails[actionType] : void 0;
203
- if (!definition) return Response.json({ error: `Unknown auth email action type: ${actionType}` }, { status: 400 });
299
+ if (!definition) return Response.json({
300
+ error: "unsupported_action_type",
301
+ action_type: actionType,
302
+ supported_action_types: Object.keys(emails)
303
+ }, { status: 400 });
204
304
  const reason = rejectReason(event.data);
205
305
  if (reason) return Response.json({ error: reason }, { status: 400 });
206
306
  try {
@@ -211,7 +311,7 @@ function createHandler(options, emails, rejectReason) {
211
311
  };
212
312
  const html = await render(element);
213
313
  const text = await render(element, { plainText: true });
214
- await sendLovableEmail({
314
+ await sendLovableEmailWithUploadBudget({
215
315
  run_id: event.run_id,
216
316
  to: event.data.email,
217
317
  from,
@@ -225,7 +325,7 @@ function createHandler(options, emails, rejectReason) {
225
325
  }, {
226
326
  apiKey,
227
327
  sendUrl: options.sendUrl
228
- });
328
+ }, AUTH_EMAIL_UPLOAD_BUDGET);
229
329
  } catch (error) {
230
330
  console.error("[email-js] auth email send failed:", error);
231
331
  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.4.0",
3
+ "version": "0.5.1-rc.0",
4
4
  "description": "Lovable Email JS",
5
5
  "repository": {
6
6
  "type": "git",