@lovable.dev/email-js 0.7.0 → 0.9.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,22 @@ 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
+
105
+ The slot request names the send (`run_id` or `idempotency_key`) and its
106
+ recipient. When Lovable already accepted that send, a retry gets it back
107
+ (`send_id`, `status`) with no new upload or send request. A send with `cc` or
108
+ `bcc` is not named and takes every step again.
109
+
94
110
  ### Cc and bcc
95
111
 
96
112
  `cc` and `bcc` take arrays of addresses (`"a@b.com"` or `"Name <a@b.com>"`).
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.9.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,12 @@ 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 HEADER_EXACT = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/;
74
+ const DEFAULT_UPLOAD_BUDGET = {
75
+ prepareTimeoutMs: 1e4,
76
+ putTimeoutMs: 1e4
77
+ };
66
78
  const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
67
79
  const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
68
80
  const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
@@ -82,27 +94,130 @@ function formatEmailFrom(from) {
82
94
  return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
83
95
  }
84
96
  async function sendLovableEmail(payload, options) {
97
+ return sendLovableEmailWithUploadBudget(payload, options, DEFAULT_UPLOAD_BUDGET);
98
+ }
99
+ async function sendLovableEmailWithUploadBudget(payload, options, budget) {
85
100
  const apiKey = options.apiKey;
86
101
  if (!apiKey) throw new Error("Missing Lovable API key");
87
102
  const authHeader = options.authHeader ?? "Authorization";
88
103
  const url = options.sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
89
104
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
90
- const headers = {
105
+ const apiHeaders = {
91
106
  [authHeader]: buildAuthHeaderValue(apiKey),
92
- "Content-Type": "application/json"
107
+ "Content-Type": "application/json",
108
+ [SDK_HEADER]: SDK_HEADER_VALUE
109
+ };
110
+ const headers = idempotencyKey ? {
111
+ ...apiHeaders,
112
+ "Idempotency-Key": idempotencyKey
113
+ } : apiHeaders;
114
+ const request = {
115
+ ...payload,
116
+ from: formatEmailFrom(payload.from)
93
117
  };
94
- if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
118
+ const upload = await uploadBody(options, {
119
+ ...apiHeaders,
120
+ ...sendIdentityHeaders(payload)
121
+ }, bodyPayloadDocument(request), budget);
122
+ if (typeof upload === "object") return upload;
123
+ if (upload) request.body_payload_id = upload;
95
124
  const response = await fetch(url, {
96
125
  method: "POST",
97
126
  headers,
98
- body: JSON.stringify({
99
- ...payload,
100
- from: formatEmailFrom(payload.from)
101
- })
127
+ body: JSON.stringify(request)
102
128
  });
103
129
  await throwIfNotOk(response);
104
130
  return await response.json();
105
131
  }
132
+ function bodyPayloadDocument(request) {
133
+ const document = {
134
+ v: 1,
135
+ from: request.from,
136
+ to: request.to,
137
+ subject: request.subject,
138
+ html: request.html,
139
+ text: request.text
140
+ };
141
+ if (request.cc?.length) document.cc = request.cc;
142
+ if (request.bcc?.length) document.bcc = request.bcc;
143
+ if (request.reply_to) document.reply_to = request.reply_to;
144
+ if (request.label) document.label = request.label;
145
+ if (request.test_mode) document.test_mode = true;
146
+ if (request.message_id) document.message_id = request.message_id;
147
+ return document;
148
+ }
149
+ function sendIdentityHeaders(payload) {
150
+ if (payload.cc?.length || payload.bcc?.length || !headerExact(payload.to)) return {};
151
+ const recipient = { "X-Lovable-Recipient": payload.to };
152
+ if (typeof payload.run_id === "string" && payload.run_id.trim()) return headerExact(payload.run_id) ? {
153
+ ...recipient,
154
+ "X-Lovable-Run-Id": payload.run_id
155
+ } : {};
156
+ return headerExact(payload.idempotency_key) ? {
157
+ ...recipient,
158
+ "Idempotency-Key": payload.idempotency_key
159
+ } : {};
160
+ }
161
+ function headerExact(value) {
162
+ return typeof value === "string" && HEADER_EXACT.test(value);
163
+ }
164
+ async function uploadBody(options, apiHeaders, document, budget) {
165
+ const bytes = new TextEncoder().encode(JSON.stringify(document));
166
+ let file;
167
+ try {
168
+ const prepareUrl = options.sendUrl ? `${new URL(options.sendUrl).origin}${PREPARE_UPLOADS_PATH}` : `${resolveApiBaseUrl(options.apiBaseUrl)}${PREPARE_UPLOADS_PATH}`;
169
+ const response = await fetch(prepareUrl, {
170
+ method: "POST",
171
+ headers: apiHeaders,
172
+ body: JSON.stringify({ files: [{ type: "body" }] }),
173
+ signal: AbortSignal.timeout(budget.prepareTimeoutMs)
174
+ });
175
+ if (response.status === 204) return;
176
+ if (!response.ok) {
177
+ discardBody(response);
178
+ return uploadSkipped(`prepare ${response.status}`);
179
+ }
180
+ const prepared = await response.json();
181
+ if (prepared?.send?.success === true) return prepared.send;
182
+ file = preparedFile(prepared);
183
+ } catch (error) {
184
+ return uploadSkipped(`prepare ${errorClass(error)}`);
185
+ }
186
+ if (!file) return uploadSkipped("prepare malformed");
187
+ if (bytes.byteLength > file.size_limit_bytes) return uploadSkipped("payload above limit");
188
+ try {
189
+ const response = await fetch(file.upload_url, {
190
+ method: "PUT",
191
+ headers: {
192
+ ...file.headers,
193
+ "Content-Type": "application/json"
194
+ },
195
+ body: bytes,
196
+ signal: AbortSignal.timeout(budget.putTimeoutMs)
197
+ });
198
+ if (!response.ok) {
199
+ discardBody(response);
200
+ return uploadSkipped(`put ${response.status}`);
201
+ }
202
+ } catch (error) {
203
+ return uploadSkipped(`put ${errorClass(error)}`);
204
+ }
205
+ return file.payload_id;
206
+ }
207
+ function preparedFile(prepared) {
208
+ const file = prepared?.files?.length === 1 ? prepared.files[0] : void 0;
209
+ 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;
210
+ return file;
211
+ }
212
+ function discardBody(response) {
213
+ response.body?.cancel().catch(() => void 0);
214
+ }
215
+ function uploadSkipped(reason) {
216
+ console.warn(`[email-js] upload skipped: ${reason}`);
217
+ }
218
+ function errorClass(error) {
219
+ return error instanceof Error ? error.name : typeof error;
220
+ }
106
221
  //#endregion
107
222
  //#region src/webhook.ts
108
223
  function parseEmailWebhookPayload(body) {
package/dist/index.d.cts CHANGED
@@ -32,6 +32,8 @@ interface EmailSendResponse {
32
32
  success: boolean;
33
33
  message_id?: string;
34
34
  workflow_id?: string;
35
+ /** Set when the send was accepted into the email queue; a retry of the same send returns the same ID. */
36
+ send_id?: string;
35
37
  status?: string;
36
38
  }
37
39
  interface SendEmailOptions {
package/dist/index.d.ts CHANGED
@@ -32,6 +32,8 @@ interface EmailSendResponse {
32
32
  success: boolean;
33
33
  message_id?: string;
34
34
  workflow_id?: string;
35
+ /** Set when the send was accepted into the email queue; a retry of the same send returns the same ID. */
36
+ send_id?: string;
35
37
  status?: string;
36
38
  }
37
39
  interface SendEmailOptions {
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
2
+ const SDK_VERSION = "0.9.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,12 @@ 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 HEADER_EXACT = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/;
73
+ const DEFAULT_UPLOAD_BUDGET = {
74
+ prepareTimeoutMs: 1e4,
75
+ putTimeoutMs: 1e4
76
+ };
65
77
  const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
66
78
  const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
67
79
  const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
@@ -81,27 +93,130 @@ function formatEmailFrom(from) {
81
93
  return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
82
94
  }
83
95
  async function sendLovableEmail(payload, options) {
96
+ return sendLovableEmailWithUploadBudget(payload, options, DEFAULT_UPLOAD_BUDGET);
97
+ }
98
+ async function sendLovableEmailWithUploadBudget(payload, options, budget) {
84
99
  const apiKey = options.apiKey;
85
100
  if (!apiKey) throw new Error("Missing Lovable API key");
86
101
  const authHeader = options.authHeader ?? "Authorization";
87
102
  const url = options.sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
88
103
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
89
- const headers = {
104
+ const apiHeaders = {
90
105
  [authHeader]: buildAuthHeaderValue(apiKey),
91
- "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)
92
116
  };
93
- if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
117
+ const upload = await uploadBody(options, {
118
+ ...apiHeaders,
119
+ ...sendIdentityHeaders(payload)
120
+ }, bodyPayloadDocument(request), budget);
121
+ if (typeof upload === "object") return upload;
122
+ if (upload) request.body_payload_id = upload;
94
123
  const response = await fetch(url, {
95
124
  method: "POST",
96
125
  headers,
97
- body: JSON.stringify({
98
- ...payload,
99
- from: formatEmailFrom(payload.from)
100
- })
126
+ body: JSON.stringify(request)
101
127
  });
102
128
  await throwIfNotOk(response);
103
129
  return await response.json();
104
130
  }
131
+ function bodyPayloadDocument(request) {
132
+ const document = {
133
+ v: 1,
134
+ from: request.from,
135
+ to: request.to,
136
+ subject: request.subject,
137
+ html: request.html,
138
+ text: request.text
139
+ };
140
+ if (request.cc?.length) document.cc = request.cc;
141
+ if (request.bcc?.length) document.bcc = request.bcc;
142
+ if (request.reply_to) document.reply_to = request.reply_to;
143
+ if (request.label) document.label = request.label;
144
+ if (request.test_mode) document.test_mode = true;
145
+ if (request.message_id) document.message_id = request.message_id;
146
+ return document;
147
+ }
148
+ function sendIdentityHeaders(payload) {
149
+ if (payload.cc?.length || payload.bcc?.length || !headerExact(payload.to)) return {};
150
+ const recipient = { "X-Lovable-Recipient": payload.to };
151
+ if (typeof payload.run_id === "string" && payload.run_id.trim()) return headerExact(payload.run_id) ? {
152
+ ...recipient,
153
+ "X-Lovable-Run-Id": payload.run_id
154
+ } : {};
155
+ return headerExact(payload.idempotency_key) ? {
156
+ ...recipient,
157
+ "Idempotency-Key": payload.idempotency_key
158
+ } : {};
159
+ }
160
+ function headerExact(value) {
161
+ return typeof value === "string" && HEADER_EXACT.test(value);
162
+ }
163
+ async function uploadBody(options, apiHeaders, document, budget) {
164
+ const bytes = new TextEncoder().encode(JSON.stringify(document));
165
+ let file;
166
+ try {
167
+ const prepareUrl = options.sendUrl ? `${new URL(options.sendUrl).origin}${PREPARE_UPLOADS_PATH}` : `${resolveApiBaseUrl(options.apiBaseUrl)}${PREPARE_UPLOADS_PATH}`;
168
+ const response = await fetch(prepareUrl, {
169
+ method: "POST",
170
+ headers: apiHeaders,
171
+ body: JSON.stringify({ files: [{ type: "body" }] }),
172
+ signal: AbortSignal.timeout(budget.prepareTimeoutMs)
173
+ });
174
+ if (response.status === 204) return;
175
+ if (!response.ok) {
176
+ discardBody(response);
177
+ return uploadSkipped(`prepare ${response.status}`);
178
+ }
179
+ const prepared = await response.json();
180
+ if (prepared?.send?.success === true) return prepared.send;
181
+ file = preparedFile(prepared);
182
+ } catch (error) {
183
+ return uploadSkipped(`prepare ${errorClass(error)}`);
184
+ }
185
+ if (!file) return uploadSkipped("prepare malformed");
186
+ if (bytes.byteLength > file.size_limit_bytes) return uploadSkipped("payload above limit");
187
+ try {
188
+ const response = await fetch(file.upload_url, {
189
+ method: "PUT",
190
+ headers: {
191
+ ...file.headers,
192
+ "Content-Type": "application/json"
193
+ },
194
+ body: bytes,
195
+ signal: AbortSignal.timeout(budget.putTimeoutMs)
196
+ });
197
+ if (!response.ok) {
198
+ discardBody(response);
199
+ return uploadSkipped(`put ${response.status}`);
200
+ }
201
+ } catch (error) {
202
+ return uploadSkipped(`put ${errorClass(error)}`);
203
+ }
204
+ return file.payload_id;
205
+ }
206
+ function preparedFile(prepared) {
207
+ const file = prepared?.files?.length === 1 ? prepared.files[0] : void 0;
208
+ 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;
209
+ return file;
210
+ }
211
+ function discardBody(response) {
212
+ response.body?.cancel().catch(() => void 0);
213
+ }
214
+ function uploadSkipped(reason) {
215
+ console.warn(`[email-js] upload skipped: ${reason}`);
216
+ }
217
+ function errorClass(error) {
218
+ return error instanceof Error ? error.name : typeof error;
219
+ }
105
220
  //#endregion
106
221
  //#region src/webhook.ts
107
222
  function parseEmailWebhookPayload(body) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/email-js",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Lovable Email JS",
5
5
  "repository": {
6
6
  "type": "git",