@lovable.dev/email-js 0.1.2 → 0.3.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
@@ -44,7 +44,7 @@ export async function handleWebhook(req: Request) {
44
44
  {
45
45
  run_id: payload.run_id,
46
46
  to: payload.data?.email ?? "",
47
- from: "My App <noreply@example.com>",
47
+ from: { name: "My App", address: "noreply@example.com" },
48
48
  subject: "Welcome",
49
49
  html: "<p>Hello</p>",
50
50
  text: "Hello",
@@ -55,6 +55,15 @@ export async function handleWebhook(req: Request) {
55
55
  }
56
56
  ```
57
57
 
58
+ ### The `from` field
59
+
60
+ `from` takes either a raw RFC 5322 header string
61
+ (`"My App <noreply@example.com>"`) or a parts object
62
+ (`{ name: "My App", address: "noreply@example.com" }`). Prefer the parts
63
+ form: the SDK (`formatEmailFrom`, also exported) quotes and escapes the
64
+ display name, so brand names containing `,` `:` `;` or non-ASCII characters
65
+ cannot produce an unparseable header the send API would reject.
66
+
58
67
  ### Sending without a `run_id` (runtime-triggered emails)
59
68
 
60
69
  For transactional emails sent outside a build context (e.g., webhook handlers,
@@ -82,6 +91,32 @@ await sendLovableEmail(
82
91
  All clients take the client options (`{ apiKey, apiBaseUrl?, authHeader? }`)
83
92
  as their last argument.
84
93
 
94
+ ### Cc and bcc
95
+
96
+ `cc` and `bcc` take arrays of addresses (`"a@b.com"` or `"Name <a@b.com>"`).
97
+ Cc recipients appear in the message's Cc header; bcc recipients receive the
98
+ message without appearing in any header. A send is limited to 5 recipients
99
+ across `to`, `cc`, and `bcc`, and the addresses must be distinct.
100
+
101
+ ```ts
102
+ await sendLovableEmail(
103
+ {
104
+ to: "user@example.com",
105
+ cc: ["manager@example.com"],
106
+ bcc: ["records@example.com"],
107
+ // ... as above
108
+ },
109
+ { apiKey },
110
+ );
111
+ ```
112
+
113
+ Two things to know: a cc/bcc recipient who previously unsubscribed or bounced
114
+ is silently dropped from the send (the primary recipient still gets it), and
115
+ unsubscribing is scoped to the primary `to` recipient — the link in the
116
+ message body and the mail client's native unsubscribe button both carry the
117
+ primary's token, so a cc'd reader using either one unsubscribes the primary
118
+ recipient.
119
+
85
120
  ### Listing email logs
86
121
 
87
122
  `listEmailLogs` returns recent delivery events for the calling project.
@@ -168,7 +203,7 @@ import { createAuthEmailHandler } from "@lovable.dev/email-js";
168
203
 
169
204
  const handler = createAuthEmailHandler({
170
205
  apiKey: process.env.LOVABLE_API_KEY!,
171
- from: "My App <noreply@notify.example.com>", // sender domain derived from the address
206
+ from: { name: "My App", address: "noreply@notify.example.com" }, // sender domain derived from the address
172
207
  sendUrl: process.env.LOVABLE_SEND_URL,
173
208
  emails: {
174
209
  signup: { subject: "Confirm your email", render: (data) => <SignupEmail confirmationUrl={data.url} /> },
package/dist/index.cjs CHANGED
@@ -63,6 +63,24 @@ async function emailApiRequest(options, path, init = { method: "GET" }) {
63
63
  //#endregion
64
64
  //#region src/email.ts
65
65
  const DEFAULT_SEND_PATH = "/v1/messaging/email/send";
66
+ const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
67
+ const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
68
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
69
+ /**
70
+ * Builds an RFC 5322 From header from parts, quoting and escaping the display
71
+ * name so punctuation like ":" cannot yield an unparseable header. Strings pass through.
72
+ */
73
+ function formatEmailFrom(from) {
74
+ if (typeof from !== "object" || from === null) return from;
75
+ const name = (from.name ?? "").trim();
76
+ const address = (from.address ?? "").trim();
77
+ if (CONTROL_CHARS.test(name + address)) throw new Error("from name and address must not contain control characters");
78
+ if (!ADDRESS_SHAPE.test(address)) throw new Error(`Invalid from address: "${address}"`);
79
+ if (new TextEncoder().encode(name).length > 200) throw new Error("from name must be at most 200 bytes");
80
+ if (!name) return address;
81
+ if (UNQUOTED_NAME_SAFE.test(name)) return `${name} <${address}>`;
82
+ return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
83
+ }
66
84
  async function sendLovableEmail(payload, options) {
67
85
  const apiKey = options.apiKey;
68
86
  if (!apiKey) throw new Error("Missing Lovable API key");
@@ -77,7 +95,10 @@ async function sendLovableEmail(payload, options) {
77
95
  const response = await fetch(url, {
78
96
  method: "POST",
79
97
  headers,
80
- body: JSON.stringify(payload)
98
+ body: JSON.stringify({
99
+ ...payload,
100
+ from: formatEmailFrom(payload.from)
101
+ })
81
102
  });
82
103
  await throwIfNotOk(response);
83
104
  return await response.json();
@@ -149,8 +170,9 @@ function domainOfAddress(from) {
149
170
  return /@([^@\s<>]+)>?\s*$/.exec(from.trim())?.[1];
150
171
  }
151
172
  function createAuthEmailHandler(options) {
152
- const { apiKey, from, emails } = options;
173
+ const { apiKey, emails } = options;
153
174
  if (!apiKey) throw new Error("Missing Lovable API key");
175
+ const from = formatEmailFrom(options.from);
154
176
  const senderDomain = options.senderDomain ?? domainOfAddress(from);
155
177
  if (!senderDomain) throw new Error(`Cannot derive a sender domain from "${from}"; pass senderDomain`);
156
178
  return async (req) => {
@@ -252,6 +274,7 @@ async function setEmailUnsubscribe(request, options) {
252
274
  exports.EmailAPIError = EmailAPIError;
253
275
  exports.createAuthEmailHandler = createAuthEmailHandler;
254
276
  exports.createEmailWebhookHandler = createEmailWebhookHandler;
277
+ exports.formatEmailFrom = formatEmailFrom;
255
278
  exports.getEmailUnsubscribe = getEmailUnsubscribe;
256
279
  exports.listEmailLogs = listEmailLogs;
257
280
  exports.parseEmailWebhookPayload = parseEmailWebhookPayload;
package/dist/index.d.cts CHANGED
@@ -1,16 +1,26 @@
1
1
  import { ReactElement } from "react";
2
2
  import { EmailWebhookPayload, EmailWebhookPayload as EmailWebhookPayload$1 } from "@lovable.dev/webhooks-js";
3
3
  //#region src/types.d.ts
4
+ interface EmailFromParts {
5
+ name: string;
6
+ address: string;
7
+ }
8
+ /** Prefer the parts form: the SDK quotes/escapes the name, so any brand name yields a valid header. */
9
+ type EmailFrom = string | EmailFromParts;
4
10
  interface EmailSendRequest {
5
11
  run_id?: string;
6
12
  to: string;
7
- from: string;
13
+ from: EmailFrom;
8
14
  sender_domain?: string;
9
15
  subject: string;
10
16
  html: string;
11
17
  text: string;
12
18
  purpose?: string;
13
19
  reply_to?: string;
20
+ /** Visible in the Cc header. Max 5 recipients per send across to, cc, and bcc. */
21
+ cc?: string[];
22
+ /** Hidden — delivered via the envelope only, never in a header. Counts toward the 5-recipient cap. */
23
+ bcc?: string[];
14
24
  identity_id?: string;
15
25
  test_mode?: boolean;
16
26
  label?: string;
@@ -124,7 +134,7 @@ type AuthEmailDefinition = {
124
134
  type AuthEmailDefinitions = Record<AuthEmailActionType, AuthEmailDefinition>;
125
135
  interface AuthEmailHandlerOptions {
126
136
  apiKey: string;
127
- from: string;
137
+ from: EmailFrom;
128
138
  /** Defaults to the domain of `from`. */
129
139
  senderDomain?: string;
130
140
  sendUrl?: string | undefined;
@@ -135,6 +145,11 @@ interface AuthEmailHandlerOptions {
135
145
  declare function createAuthEmailHandler(options: AuthEmailHandlerOptions): (req: Request) => Promise<Response>;
136
146
  //#endregion
137
147
  //#region src/email.d.ts
148
+ /**
149
+ * Builds an RFC 5322 From header from parts, quoting and escaping the display
150
+ * name so punctuation like ":" cannot yield an unparseable header. Strings pass through.
151
+ */
152
+ declare function formatEmailFrom(from: EmailFrom): string;
138
153
  declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
139
154
  //#endregion
140
155
  //#region src/http.d.ts
@@ -159,4 +174,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload$1;
159
174
  //#region src/webhook-handler.d.ts
160
175
  declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
161
176
  //#endregion
162
- export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type EmailWebhookPayload, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
177
+ 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 SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, formatEmailFrom, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
package/dist/index.d.ts CHANGED
@@ -1,16 +1,26 @@
1
1
  import { EmailWebhookPayload, EmailWebhookPayload as EmailWebhookPayload$1 } from "@lovable.dev/webhooks-js";
2
2
  import { ReactElement } from "react";
3
3
  //#region src/types.d.ts
4
+ interface EmailFromParts {
5
+ name: string;
6
+ address: string;
7
+ }
8
+ /** Prefer the parts form: the SDK quotes/escapes the name, so any brand name yields a valid header. */
9
+ type EmailFrom = string | EmailFromParts;
4
10
  interface EmailSendRequest {
5
11
  run_id?: string;
6
12
  to: string;
7
- from: string;
13
+ from: EmailFrom;
8
14
  sender_domain?: string;
9
15
  subject: string;
10
16
  html: string;
11
17
  text: string;
12
18
  purpose?: string;
13
19
  reply_to?: string;
20
+ /** Visible in the Cc header. Max 5 recipients per send across to, cc, and bcc. */
21
+ cc?: string[];
22
+ /** Hidden — delivered via the envelope only, never in a header. Counts toward the 5-recipient cap. */
23
+ bcc?: string[];
14
24
  identity_id?: string;
15
25
  test_mode?: boolean;
16
26
  label?: string;
@@ -124,7 +134,7 @@ type AuthEmailDefinition = {
124
134
  type AuthEmailDefinitions = Record<AuthEmailActionType, AuthEmailDefinition>;
125
135
  interface AuthEmailHandlerOptions {
126
136
  apiKey: string;
127
- from: string;
137
+ from: EmailFrom;
128
138
  /** Defaults to the domain of `from`. */
129
139
  senderDomain?: string;
130
140
  sendUrl?: string | undefined;
@@ -135,6 +145,11 @@ interface AuthEmailHandlerOptions {
135
145
  declare function createAuthEmailHandler(options: AuthEmailHandlerOptions): (req: Request) => Promise<Response>;
136
146
  //#endregion
137
147
  //#region src/email.d.ts
148
+ /**
149
+ * Builds an RFC 5322 From header from parts, quoting and escaping the display
150
+ * name so punctuation like ":" cannot yield an unparseable header. Strings pass through.
151
+ */
152
+ declare function formatEmailFrom(from: EmailFrom): string;
138
153
  declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
139
154
  //#endregion
140
155
  //#region src/http.d.ts
@@ -159,4 +174,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload$1;
159
174
  //#region src/webhook-handler.d.ts
160
175
  declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
161
176
  //#endregion
162
- export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type EmailWebhookPayload, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
177
+ 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 SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, formatEmailFrom, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
package/dist/index.js CHANGED
@@ -62,6 +62,24 @@ async function emailApiRequest(options, path, init = { method: "GET" }) {
62
62
  //#endregion
63
63
  //#region src/email.ts
64
64
  const DEFAULT_SEND_PATH = "/v1/messaging/email/send";
65
+ const UNQUOTED_NAME_SAFE = /^[A-Za-z0-9 !#$%&'*+\-/^_`{|}~]*$/;
66
+ const ADDRESS_SHAPE = /^[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*@[^\s@<>"(),;:\\[\].]+(\.[^\s@<>"(),;:\\[\].]+)*$/;
67
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F]/;
68
+ /**
69
+ * Builds an RFC 5322 From header from parts, quoting and escaping the display
70
+ * name so punctuation like ":" cannot yield an unparseable header. Strings pass through.
71
+ */
72
+ function formatEmailFrom(from) {
73
+ if (typeof from !== "object" || from === null) return from;
74
+ const name = (from.name ?? "").trim();
75
+ const address = (from.address ?? "").trim();
76
+ if (CONTROL_CHARS.test(name + address)) throw new Error("from name and address must not contain control characters");
77
+ if (!ADDRESS_SHAPE.test(address)) throw new Error(`Invalid from address: "${address}"`);
78
+ if (new TextEncoder().encode(name).length > 200) throw new Error("from name must be at most 200 bytes");
79
+ if (!name) return address;
80
+ if (UNQUOTED_NAME_SAFE.test(name)) return `${name} <${address}>`;
81
+ return `"${name.replace(/[\\"]/g, "\\$&")}" <${address}>`;
82
+ }
65
83
  async function sendLovableEmail(payload, options) {
66
84
  const apiKey = options.apiKey;
67
85
  if (!apiKey) throw new Error("Missing Lovable API key");
@@ -76,7 +94,10 @@ async function sendLovableEmail(payload, options) {
76
94
  const response = await fetch(url, {
77
95
  method: "POST",
78
96
  headers,
79
- body: JSON.stringify(payload)
97
+ body: JSON.stringify({
98
+ ...payload,
99
+ from: formatEmailFrom(payload.from)
100
+ })
80
101
  });
81
102
  await throwIfNotOk(response);
82
103
  return await response.json();
@@ -148,8 +169,9 @@ function domainOfAddress(from) {
148
169
  return /@([^@\s<>]+)>?\s*$/.exec(from.trim())?.[1];
149
170
  }
150
171
  function createAuthEmailHandler(options) {
151
- const { apiKey, from, emails } = options;
172
+ const { apiKey, emails } = options;
152
173
  if (!apiKey) throw new Error("Missing Lovable API key");
174
+ const from = formatEmailFrom(options.from);
153
175
  const senderDomain = options.senderDomain ?? domainOfAddress(from);
154
176
  if (!senderDomain) throw new Error(`Cannot derive a sender domain from "${from}"; pass senderDomain`);
155
177
  return async (req) => {
@@ -248,4 +270,4 @@ async function setEmailUnsubscribe(request, options) {
248
270
  });
249
271
  }
250
272
  //#endregion
251
- export { EmailAPIError, createAuthEmailHandler, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
273
+ export { EmailAPIError, createAuthEmailHandler, createEmailWebhookHandler, formatEmailFrom, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/email-js",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "description": "Lovable Email JS",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,7 +47,7 @@
47
47
  "react-dom": "^19.0.0",
48
48
  "rimraf": "^5.0.0",
49
49
  "tsdown": "^0.22.5",
50
- "typescript": "^5",
50
+ "typescript": "7.0.2",
51
51
  "vitest": "^4.1.5",
52
52
  "@lovable/api-utils": "1.0.0"
53
53
  },