posthog-node 5.71.0 → 5.72.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/dist/client.d.ts +3 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/emails/attachments.d.ts +23 -0
- package/dist/emails/attachments.d.ts.map +1 -0
- package/dist/emails/attachments.js +170 -0
- package/dist/emails/attachments.mjs +123 -0
- package/dist/emails/emails.d.ts +7 -2
- package/dist/emails/emails.d.ts.map +1 -1
- package/dist/emails/emails.js +193 -37
- package/dist/emails/emails.mjs +193 -37
- package/dist/emails/errors.d.ts +1 -1
- package/dist/emails/errors.d.ts.map +1 -1
- package/dist/emails/errors.js +6 -1
- package/dist/emails/errors.mjs +6 -1
- package/dist/emails/types.d.ts +23 -0
- package/dist/emails/types.d.ts.map +1 -1
- package/dist/exports.d.ts +1 -1
- package/dist/exports.d.ts.map +1 -1
- package/dist/types.d.ts +2 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +3 -3
- package/src/client.ts +3 -2
- package/src/emails/attachments.ts +209 -0
- package/src/emails/emails.ts +243 -35
- package/src/emails/errors.ts +7 -2
- package/src/emails/types.ts +24 -0
- package/src/exports.ts +1 -0
- package/src/types.ts +2 -1
- package/src/version.ts +1 -1
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { EmailError } from './errors'
|
|
2
|
+
import type { EmailAttachment } from './types'
|
|
3
|
+
|
|
4
|
+
const MAX_ATTACHMENTS = 10
|
|
5
|
+
const MAX_MESSAGE_BYTES = 40_000_000
|
|
6
|
+
const MESSAGE_HEADERS_BYTES = 64 * 1024
|
|
7
|
+
const SUBJECT_BYTES_PER_ENCODED_WORD = 42
|
|
8
|
+
const ENCODED_WORD_BYTES = 75
|
|
9
|
+
const MESSAGE_LIMIT = '40 MB after Base64 encoding, about 29 MB of files'
|
|
10
|
+
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/
|
|
11
|
+
|
|
12
|
+
export interface AttachmentFile {
|
|
13
|
+
filename: string
|
|
14
|
+
bytes: Uint8Array<ArrayBuffer>
|
|
15
|
+
contentType?: string
|
|
16
|
+
contentId?: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface HashedFile extends AttachmentFile {
|
|
20
|
+
sha256: string
|
|
21
|
+
field: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface CheckedAttachment {
|
|
25
|
+
filename: string
|
|
26
|
+
content: string | Uint8Array
|
|
27
|
+
size: number
|
|
28
|
+
contentType?: string
|
|
29
|
+
contentId?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function attachmentFiles(
|
|
33
|
+
attachments: unknown,
|
|
34
|
+
{ html, text, subject }: { html?: string; text?: string; subject: string }
|
|
35
|
+
): AttachmentFile[] {
|
|
36
|
+
if (!Array.isArray(attachments)) {
|
|
37
|
+
throw invalid('attachments must be a list of files.', 'attachments')
|
|
38
|
+
}
|
|
39
|
+
if (attachments.length > MAX_ATTACHMENTS) {
|
|
40
|
+
throw new EmailError({
|
|
41
|
+
code: 'too_many_attachments',
|
|
42
|
+
message: `An email carries at most ${MAX_ATTACHMENTS} files, so no email was sent.`,
|
|
43
|
+
field: 'attachments',
|
|
44
|
+
fix: `Attach at most ${MAX_ATTACHMENTS} files, and link to any others from the email body.`,
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
const checked = Array.from(attachments, checkedAttachment)
|
|
48
|
+
refuseMessageOverLimit(
|
|
49
|
+
checked.map(({ size }) => size),
|
|
50
|
+
[html ?? '', text || html || ''],
|
|
51
|
+
subject
|
|
52
|
+
)
|
|
53
|
+
return checked.map(({ content, size, ...file }) => ({
|
|
54
|
+
...file,
|
|
55
|
+
bytes: typeof content === 'string' ? bytesOfBase64(content) : new Uint8Array(content),
|
|
56
|
+
}))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Checks the email's size once a react element is rendered, since its html and the text derived
|
|
61
|
+
* from it were unknown when the files were checked.
|
|
62
|
+
*/
|
|
63
|
+
export function refuseRenderedMessageOverLimit(files: AttachmentFile[], content: Record<string, unknown>): void {
|
|
64
|
+
const html = typeof content.html === 'string' ? content.html : ''
|
|
65
|
+
const text = typeof content.text === 'string' ? content.text : ''
|
|
66
|
+
refuseMessageOverLimit(
|
|
67
|
+
files.map(({ bytes }) => bytes.byteLength),
|
|
68
|
+
[html, text || html],
|
|
69
|
+
typeof content.subject === 'string' ? content.subject : ''
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function hashedFiles(files: AttachmentFile[]): Promise<HashedFile[]> {
|
|
74
|
+
return Promise.all(
|
|
75
|
+
files.map(async (file, index) => ({
|
|
76
|
+
...file,
|
|
77
|
+
sha256: await sha256Hex(file.bytes),
|
|
78
|
+
field: `attachments__${index}`,
|
|
79
|
+
}))
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function attachmentReference({ sha256, filename, contentType, contentId }: HashedFile): Record<string, unknown> {
|
|
84
|
+
return {
|
|
85
|
+
sha256,
|
|
86
|
+
filename,
|
|
87
|
+
...(contentType !== undefined && { content_type: contentType }),
|
|
88
|
+
...(contentId !== undefined && { content_id: contentId }),
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function checkedAttachment(attachment: unknown, index: number): CheckedAttachment {
|
|
93
|
+
if (
|
|
94
|
+
typeof attachment !== 'object' ||
|
|
95
|
+
attachment === null ||
|
|
96
|
+
Array.isArray(attachment) ||
|
|
97
|
+
ArrayBuffer.isView(attachment)
|
|
98
|
+
) {
|
|
99
|
+
throw invalid(
|
|
100
|
+
"An attachment is an object with filename and content. Pass the file's bytes as its content.",
|
|
101
|
+
`attachments__${index}`
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
const { filename, content, contentType, contentId, path, ...unsupported } = attachment as Partial<
|
|
105
|
+
Record<keyof EmailAttachment, unknown>
|
|
106
|
+
>
|
|
107
|
+
if (path !== undefined) {
|
|
108
|
+
throw invalid(
|
|
109
|
+
"PostHog can't fetch an attachment from a path or URL. Read the file and pass its content instead.",
|
|
110
|
+
`attachments__${index}__path`
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
const unsupportedKey = Object.entries(unsupported).find(([, value]) => value !== undefined)?.[0]
|
|
114
|
+
if (unsupportedKey !== undefined) {
|
|
115
|
+
throw invalid(
|
|
116
|
+
`An attachment takes filename, content, contentType and contentId, not ${unsupportedKey}.`,
|
|
117
|
+
`attachments__${index}__${unsupportedKey}`
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
if (typeof filename !== 'string' || filename === '') {
|
|
121
|
+
throw invalid("An attachment needs a filename, such as 'invoice.pdf'.", `attachments__${index}__filename`)
|
|
122
|
+
}
|
|
123
|
+
if (typeof content !== 'string' && !(content instanceof Uint8Array)) {
|
|
124
|
+
throw invalid(
|
|
125
|
+
'An attachment needs content: a Buffer, a Uint8Array or a Base64 string.',
|
|
126
|
+
`attachments__${index}__content`
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
if (typeof content === 'string' && !isBase64(content)) {
|
|
130
|
+
throw invalid(
|
|
131
|
+
"An attachment's content string must be Base64. Pass text as a Buffer or a Uint8Array.",
|
|
132
|
+
`attachments__${index}__content`
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
if (contentType !== undefined && typeof contentType !== 'string') {
|
|
136
|
+
throw invalid(
|
|
137
|
+
"An attachment's contentType must be a string, such as 'application/pdf'.",
|
|
138
|
+
`attachments__${index}__contentType`
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
if (contentId !== undefined && typeof contentId !== 'string') {
|
|
142
|
+
throw invalid("An attachment's contentId must be a string.", `attachments__${index}__contentId`)
|
|
143
|
+
}
|
|
144
|
+
const size = typeof content === 'string' ? base64DecodedBytes(content) : content.byteLength
|
|
145
|
+
if (size === 0) {
|
|
146
|
+
throw invalid('An attachment needs at least one byte.', `attachments__${index}__content`)
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
filename,
|
|
150
|
+
content,
|
|
151
|
+
size,
|
|
152
|
+
...(contentType !== undefined && { contentType }),
|
|
153
|
+
...(contentId !== undefined && { contentId }),
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function isBase64(text: string): boolean {
|
|
158
|
+
return text.length % 4 === 0 && BASE64_PATTERN.test(text)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function base64DecodedBytes(text: string): number {
|
|
162
|
+
const padding = text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0
|
|
163
|
+
return (text.length / 4) * 3 - padding
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function bytesOfBase64(text: string): Uint8Array<ArrayBuffer> {
|
|
167
|
+
if (typeof Buffer !== 'undefined') {
|
|
168
|
+
return Buffer.from(text, 'base64')
|
|
169
|
+
}
|
|
170
|
+
const binary = atob(text)
|
|
171
|
+
const bytes = new Uint8Array(binary.length)
|
|
172
|
+
for (let index = 0; index < binary.length; index++) {
|
|
173
|
+
bytes[index] = binary.charCodeAt(index)
|
|
174
|
+
}
|
|
175
|
+
return bytes
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function refuseMessageOverLimit(fileSizes: number[], bodies: string[], subject: string): void {
|
|
179
|
+
if (fileSizes.length === 0) {
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
const encoder = new TextEncoder()
|
|
183
|
+
const sizes = [...fileSizes, ...bodies.map((body) => encoder.encode(body).byteLength)]
|
|
184
|
+
const headersBytes =
|
|
185
|
+
MESSAGE_HEADERS_BYTES +
|
|
186
|
+
Math.ceil(encoder.encode(subject).byteLength / SUBJECT_BYTES_PER_ENCODED_WORD) * ENCODED_WORD_BYTES
|
|
187
|
+
if (sizes.reduce((total, size) => total + base64LinesBytes(size), headersBytes) > MAX_MESSAGE_BYTES) {
|
|
188
|
+
throw new EmailError({
|
|
189
|
+
code: 'message_too_large',
|
|
190
|
+
message: `These files make the email larger than ${MESSAGE_LIMIT}, so no email was sent.`,
|
|
191
|
+
field: 'attachments',
|
|
192
|
+
why: "PostHog's email provider takes emails up to 40 MB, and Base64 encoding makes each file about a third larger.",
|
|
193
|
+
fix: 'Send fewer or smaller files, or link to large files from the email body.',
|
|
194
|
+
})
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function base64LinesBytes(size: number): number {
|
|
199
|
+
return Math.ceil((Math.ceil(size / 3) * 4 * 78) / 76)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function sha256Hex(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
|
|
203
|
+
const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes))
|
|
204
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('')
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function invalid(message: string, field: string): EmailError {
|
|
208
|
+
return new EmailError({ code: 'invalid_attachment', message, field })
|
|
209
|
+
}
|
package/src/emails/emails.ts
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
|
-
type FetchLike,
|
|
3
2
|
type Logger,
|
|
3
|
+
type PostHogFetchOptions,
|
|
4
4
|
type PostHogFetchResponse,
|
|
5
5
|
parseRetryAfterMs,
|
|
6
6
|
removeTrailingSlash,
|
|
7
7
|
safeJsonStringify,
|
|
8
8
|
} from '@posthog/core'
|
|
9
9
|
|
|
10
|
+
import {
|
|
11
|
+
type AttachmentFile,
|
|
12
|
+
type HashedFile,
|
|
13
|
+
attachmentFiles,
|
|
14
|
+
attachmentReference,
|
|
15
|
+
hashedFiles,
|
|
16
|
+
refuseRenderedMessageOverLimit,
|
|
17
|
+
} from './attachments'
|
|
10
18
|
import { EmailError } from './errors'
|
|
11
19
|
import type {
|
|
12
20
|
CodeEmailForm,
|
|
@@ -27,6 +35,7 @@ import type {
|
|
|
27
35
|
} from './types'
|
|
28
36
|
|
|
29
37
|
const SEND_PATH = '/api/projects/@current/messaging/send/email/'
|
|
38
|
+
const UPLOADS_PATH = '/api/projects/@current/messaging/attachments/uploads/'
|
|
30
39
|
const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/'
|
|
31
40
|
const PREFERENCES_PATH = '/api/projects/@current/messaging/preferences/'
|
|
32
41
|
const US_APP_HOST = 'https://us.posthog.com'
|
|
@@ -70,6 +79,9 @@ const CODE_FIELDS: EveryField<CodeEmailForm> = {
|
|
|
70
79
|
from: true,
|
|
71
80
|
replyTo: true,
|
|
72
81
|
captureEngagement: true,
|
|
82
|
+
cc: true,
|
|
83
|
+
bcc: true,
|
|
84
|
+
attachments: true,
|
|
73
85
|
sensitive: true,
|
|
74
86
|
tracking: true,
|
|
75
87
|
html: true,
|
|
@@ -102,8 +114,12 @@ export interface EmailSenderConfig {
|
|
|
102
114
|
migratedFrom?: string
|
|
103
115
|
}
|
|
104
116
|
|
|
117
|
+
export interface EmailFetchOptions extends PostHogFetchOptions {
|
|
118
|
+
redirect?: 'manual'
|
|
119
|
+
}
|
|
120
|
+
|
|
105
121
|
export interface EmailSenderHooks {
|
|
106
|
-
fetch:
|
|
122
|
+
fetch: (url: string, options: EmailFetchOptions) => Promise<PostHogFetchResponse>
|
|
107
123
|
isDisabled: () => boolean
|
|
108
124
|
isClosed: () => boolean
|
|
109
125
|
logger: Logger
|
|
@@ -111,15 +127,23 @@ export interface EmailSenderHooks {
|
|
|
111
127
|
}
|
|
112
128
|
|
|
113
129
|
interface PreparedSend {
|
|
114
|
-
|
|
130
|
+
content: Record<string, unknown>
|
|
131
|
+
files: AttachmentFile[]
|
|
115
132
|
react?: EmailReactElement
|
|
116
133
|
idempotencyKey: string
|
|
117
134
|
maxRetries: number
|
|
118
135
|
}
|
|
119
136
|
|
|
137
|
+
interface Upload {
|
|
138
|
+
url: string
|
|
139
|
+
headers: Record<string, string>
|
|
140
|
+
bytes: Uint8Array<ArrayBuffer>
|
|
141
|
+
field: string
|
|
142
|
+
}
|
|
143
|
+
|
|
120
144
|
interface Reply {
|
|
121
145
|
status: number
|
|
122
|
-
|
|
146
|
+
text: string
|
|
123
147
|
retryAfterMs?: number
|
|
124
148
|
}
|
|
125
149
|
|
|
@@ -174,10 +198,15 @@ export class EmailSender implements Emails {
|
|
|
174
198
|
'no email was sent',
|
|
175
199
|
'Sending email needs secretKey, a project secret API key with the transactional_email:write scope.'
|
|
176
200
|
)
|
|
177
|
-
const
|
|
201
|
+
const content =
|
|
178
202
|
prepared.react === undefined
|
|
179
|
-
? prepared.
|
|
180
|
-
: await withRenderedReact(prepared.
|
|
203
|
+
? prepared.content
|
|
204
|
+
: await withRenderedReact(prepared.content, prepared.react, this.config.requestTimeoutMs)
|
|
205
|
+
if (prepared.react !== undefined) {
|
|
206
|
+
refuseRenderedMessageOverLimit(prepared.files, content)
|
|
207
|
+
}
|
|
208
|
+
const attachments = await this.uploadAttachments(prepared, appHost, secretKey)
|
|
209
|
+
const body = safeJsonStringify({ ...content, ...unlessEmpty('attachments', attachments) })
|
|
181
210
|
const headers = this.headers(secretKey, {
|
|
182
211
|
'Content-Type': 'application/json',
|
|
183
212
|
'Idempotency-Key': prepared.idempotencyKey,
|
|
@@ -214,6 +243,86 @@ export class EmailSender implements Emails {
|
|
|
214
243
|
}
|
|
215
244
|
}
|
|
216
245
|
|
|
246
|
+
private async uploadAttachments(
|
|
247
|
+
{ files, maxRetries }: PreparedSend,
|
|
248
|
+
appHost: string,
|
|
249
|
+
secretKey: string
|
|
250
|
+
): Promise<Record<string, unknown>[]> {
|
|
251
|
+
if (files.length === 0) {
|
|
252
|
+
return []
|
|
253
|
+
}
|
|
254
|
+
const hashed = await hashedFiles(files)
|
|
255
|
+
const distinct = new Map<string, HashedFile>()
|
|
256
|
+
for (const file of hashed) {
|
|
257
|
+
if (!distinct.has(file.sha256)) {
|
|
258
|
+
distinct.set(file.sha256, file)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const requested = [...distinct.values()]
|
|
262
|
+
const body = safeJsonStringify({
|
|
263
|
+
files: requested.map(({ sha256, bytes }) => ({ sha256, size: bytes.byteLength })),
|
|
264
|
+
})
|
|
265
|
+
const headers = this.headers(secretKey, { 'Content-Type': 'application/json' })
|
|
266
|
+
const uploads = await this.withRetries(maxRetries, async () =>
|
|
267
|
+
parseUploadsReply(await this.request(appHost + UPLOADS_PATH, 'POST', headers, body), requested)
|
|
268
|
+
)
|
|
269
|
+
const unencrypted = isPlainHttp(appHost) ? undefined : uploads.find(({ url }) => !isHttps(url))
|
|
270
|
+
if (unencrypted) {
|
|
271
|
+
throw new EmailError({
|
|
272
|
+
code: 'api_error',
|
|
273
|
+
message: `PostHog named an upload URL for ${unencrypted.field} that isn't https, so the file would travel unencrypted. No email was sent.`,
|
|
274
|
+
field: unencrypted.field,
|
|
275
|
+
fix: "Make your PostHog's file storage URL use https. For local development over plain HTTP, set appHost to your http app host.",
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
for (const upload of uploads) {
|
|
279
|
+
await this.withRetries(maxRetries, () => this.uploadFile(upload))
|
|
280
|
+
}
|
|
281
|
+
return hashed.map(attachmentReference)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private async uploadFile({ url, headers, bytes, field }: Upload): Promise<void> {
|
|
285
|
+
let reply: Reply
|
|
286
|
+
try {
|
|
287
|
+
reply = await this.request(url, 'PUT', headers, bytes, 'manual')
|
|
288
|
+
} catch (cause) {
|
|
289
|
+
if (cause instanceof Error && cause.name === 'AbortError') {
|
|
290
|
+
throw new EmailError({
|
|
291
|
+
code: 'network_error',
|
|
292
|
+
message: `The upload of ${field} timed out after ${this.config.requestTimeoutMs}ms, so no email was sent.`,
|
|
293
|
+
fix: 'Raise emailRequestTimeoutMs on the client, or send smaller files.',
|
|
294
|
+
field,
|
|
295
|
+
cause,
|
|
296
|
+
})
|
|
297
|
+
}
|
|
298
|
+
throw new EmailError({
|
|
299
|
+
code: 'network_error',
|
|
300
|
+
message: `The upload of ${field} didn't reach PostHog's file storage, so no email was sent.`,
|
|
301
|
+
field,
|
|
302
|
+
cause,
|
|
303
|
+
})
|
|
304
|
+
}
|
|
305
|
+
if (reply.status >= 300 && reply.status < 400) {
|
|
306
|
+
throw new EmailError({
|
|
307
|
+
code: 'attachment_upload_failed',
|
|
308
|
+
message: `PostHog's file storage redirected the upload of ${field} elsewhere. The SDK uploads only to the URL PostHog signed, so no email was sent.`,
|
|
309
|
+
statusCode: reply.status,
|
|
310
|
+
fix: "Make your PostHog's file storage URL point straight at the storage, over https.",
|
|
311
|
+
field,
|
|
312
|
+
})
|
|
313
|
+
}
|
|
314
|
+
if (reply.status < 200 || reply.status >= 300) {
|
|
315
|
+
throw new EmailError({
|
|
316
|
+
code: 'attachment_upload_failed',
|
|
317
|
+
message: `PostHog's file storage refused the upload of ${field}, so no email was sent. ${storageAnswer(reply)}`,
|
|
318
|
+
statusCode: reply.status,
|
|
319
|
+
fix: 'Send the email again. Each send asks for new upload URLs.',
|
|
320
|
+
field,
|
|
321
|
+
retryAfterMs: reply.retryAfterMs,
|
|
322
|
+
})
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
217
326
|
private async setPreferencesUntracked(options: SetEmailPreferencesOptions): Promise<SetEmailPreferencesResponse> {
|
|
218
327
|
try {
|
|
219
328
|
const body = preparePreferences(options)
|
|
@@ -301,9 +410,10 @@ export class EmailSender implements Emails {
|
|
|
301
410
|
|
|
302
411
|
private async request(
|
|
303
412
|
url: string,
|
|
304
|
-
method: 'GET' | 'POST',
|
|
413
|
+
method: 'GET' | 'POST' | 'PUT',
|
|
305
414
|
headers: Record<string, string>,
|
|
306
|
-
body?: string
|
|
415
|
+
body?: string | Uint8Array<ArrayBuffer>,
|
|
416
|
+
redirect?: 'manual'
|
|
307
417
|
): Promise<Reply> {
|
|
308
418
|
const controller = new AbortController()
|
|
309
419
|
const timeoutMs = this.config.requestTimeoutMs
|
|
@@ -324,6 +434,7 @@ export class EmailSender implements Emails {
|
|
|
324
434
|
method,
|
|
325
435
|
headers,
|
|
326
436
|
...(body === undefined ? {} : { body }),
|
|
437
|
+
...(redirect ? { redirect } : {}),
|
|
327
438
|
signal: controller.signal,
|
|
328
439
|
})
|
|
329
440
|
)
|
|
@@ -347,9 +458,9 @@ export class EmailSender implements Emails {
|
|
|
347
458
|
throw error
|
|
348
459
|
}
|
|
349
460
|
// The status and Retry-After still decide the retry when an error body can't be read.
|
|
350
|
-
return { status: response.status,
|
|
461
|
+
return { status: response.status, text: '', retryAfterMs: readRetryAfter(response) }
|
|
351
462
|
}
|
|
352
|
-
return { status: response.status,
|
|
463
|
+
return { status: response.status, text, retryAfterMs: readRetryAfter(response) }
|
|
353
464
|
} finally {
|
|
354
465
|
clearTimeout(timer!)
|
|
355
466
|
if (controller.signal.aborted && response) {
|
|
@@ -378,7 +489,7 @@ function prepareSend(options: SendEmailOptions, defaultMaxRetries: number): Prep
|
|
|
378
489
|
if (distinctId !== undefined && (typeof distinctId !== 'string' || !distinctId)) {
|
|
379
490
|
throw invalid('invalid_distinct_id', 'distinctId must be a nonempty string.', 'distinctId')
|
|
380
491
|
}
|
|
381
|
-
const content = contentOf(send, distinctId)
|
|
492
|
+
const { content, files } = contentOf(send, distinctId)
|
|
382
493
|
if (
|
|
383
494
|
idempotencyKey !== undefined &&
|
|
384
495
|
(typeof idempotencyKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey))
|
|
@@ -394,13 +505,18 @@ function prepareSend(options: SendEmailOptions, defaultMaxRetries: number): Prep
|
|
|
394
505
|
}
|
|
395
506
|
|
|
396
507
|
return {
|
|
397
|
-
|
|
508
|
+
content: snapshotOf({ ...content, to }),
|
|
509
|
+
files,
|
|
398
510
|
react: isReactElement(send.react) ? send.react : undefined,
|
|
399
511
|
idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
|
|
400
512
|
maxRetries: isRetryCount(maxRetries) ? maxRetries : defaultMaxRetries,
|
|
401
513
|
}
|
|
402
514
|
}
|
|
403
515
|
|
|
516
|
+
function snapshotOf(content: Record<string, unknown>): Record<string, unknown> {
|
|
517
|
+
return JSON.parse(safeJsonStringify(content))
|
|
518
|
+
}
|
|
519
|
+
|
|
404
520
|
function preparePreferences(options: SetEmailPreferencesOptions): string {
|
|
405
521
|
const fallback: Partial<SetEmailPreferencesOptions> = {}
|
|
406
522
|
const { to, allMarketing, topics } = options ?? fallback
|
|
@@ -434,14 +550,21 @@ function isRetryCount(value: unknown): value is number {
|
|
|
434
550
|
return typeof value === 'number' && Number.isInteger(value) && value >= 0
|
|
435
551
|
}
|
|
436
552
|
|
|
437
|
-
|
|
553
|
+
interface SendContent {
|
|
554
|
+
content: Record<string, unknown>
|
|
555
|
+
files: AttachmentFile[]
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function contentOf(send: UncheckedSend, distinctId: string | undefined): SendContent {
|
|
438
559
|
if ((send.templateId === undefined) === (send.templateKey === undefined)) {
|
|
439
560
|
throw new EmailError({
|
|
440
561
|
code: 'invalid_form',
|
|
441
562
|
message: 'Send either templateId, or templateKey with subject and html, text or react.',
|
|
442
563
|
})
|
|
443
564
|
}
|
|
444
|
-
return send.templateKey === undefined
|
|
565
|
+
return send.templateKey === undefined
|
|
566
|
+
? { content: templateContent(send, distinctId), files: [] }
|
|
567
|
+
: codeContent(send, distinctId)
|
|
445
568
|
}
|
|
446
569
|
|
|
447
570
|
function templateContent(send: UncheckedSend, distinctId: string | undefined): Record<string, unknown> {
|
|
@@ -463,8 +586,8 @@ function templateContent(send: UncheckedSend, distinctId: string | undefined): R
|
|
|
463
586
|
}
|
|
464
587
|
}
|
|
465
588
|
|
|
466
|
-
function codeContent(send: UncheckedSend, distinctId: string | undefined):
|
|
467
|
-
const { templateKey, subject, html, text, react
|
|
589
|
+
function codeContent(send: UncheckedSend, distinctId: string | undefined): SendContent {
|
|
590
|
+
const { templateKey, subject, html, text, react } = send
|
|
468
591
|
if (typeof templateKey !== 'string' || !TEMPLATE_KEY_PATTERN.test(templateKey)) {
|
|
469
592
|
throw invalid(
|
|
470
593
|
'invalid_template_key',
|
|
@@ -487,21 +610,41 @@ function codeContent(send: UncheckedSend, distinctId: string | undefined): Recor
|
|
|
487
610
|
} else if (html === undefined && text === undefined) {
|
|
488
611
|
throw invalid('invalid_form', 'A send with templateKey needs html, text or react.', 'html')
|
|
489
612
|
}
|
|
490
|
-
const
|
|
613
|
+
const files = send.attachments === undefined ? [] : attachmentFiles(send.attachments, { html, text, subject })
|
|
614
|
+
return {
|
|
615
|
+
content: {
|
|
616
|
+
template_key: templateKey,
|
|
617
|
+
subject,
|
|
618
|
+
...(html !== undefined && { html }),
|
|
619
|
+
...(text !== undefined && { text }),
|
|
620
|
+
...codeFormFields(send),
|
|
621
|
+
...(distinctId !== undefined && { distinct_id: distinctId }),
|
|
622
|
+
},
|
|
623
|
+
files,
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function codeFormFields(send: UncheckedSend): Record<string, unknown> {
|
|
628
|
+
const { from, replyTo, cc, bcc, captureEngagement, sensitive, tracking } = send
|
|
491
629
|
return {
|
|
492
|
-
template_key: templateKey,
|
|
493
|
-
subject,
|
|
494
|
-
...(html !== undefined && { html }),
|
|
495
|
-
...(text !== undefined && { text }),
|
|
496
630
|
...(from !== undefined && { from }),
|
|
497
|
-
...(
|
|
631
|
+
...(replyTo !== undefined && unlessEmpty('reply_to', addressList(replyTo))),
|
|
632
|
+
...(cc !== undefined && unlessEmpty('cc', addressList(cc))),
|
|
633
|
+
...(bcc !== undefined && unlessEmpty('bcc', addressList(bcc))),
|
|
498
634
|
...(captureEngagement !== undefined && { capture_engagement: captureEngagement }),
|
|
499
635
|
...(sensitive !== undefined && { sensitive }),
|
|
500
636
|
...(tracking !== undefined && { tracking }),
|
|
501
|
-
...(distinctId !== undefined && { distinct_id: distinctId }),
|
|
502
637
|
}
|
|
503
638
|
}
|
|
504
639
|
|
|
640
|
+
function unlessEmpty(field: string, list: unknown): Record<string, unknown> {
|
|
641
|
+
return Array.isArray(list) && list.length === 0 ? {} : { [field]: list }
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function addressList(addresses: unknown): unknown {
|
|
645
|
+
return typeof addresses === 'string' ? [addresses] : addresses
|
|
646
|
+
}
|
|
647
|
+
|
|
505
648
|
function checkReactContent(react: unknown, html: unknown): void {
|
|
506
649
|
if (!isReactElement(react)) {
|
|
507
650
|
throw invalid('invalid_form', 'react must be a React element, such as <WelcomeEmail />.', 'react')
|
|
@@ -532,12 +675,15 @@ function isReactElement(value: unknown): value is EmailReactElement {
|
|
|
532
675
|
)
|
|
533
676
|
}
|
|
534
677
|
|
|
535
|
-
async function withRenderedReact(
|
|
678
|
+
async function withRenderedReact(
|
|
679
|
+
content: Record<string, unknown>,
|
|
680
|
+
react: EmailReactElement,
|
|
681
|
+
timeoutMs: number
|
|
682
|
+
): Promise<Record<string, unknown>> {
|
|
536
683
|
const { render, toPlainText } = await loadReactRenderer()
|
|
537
|
-
const fields: Record<string, unknown> = JSON.parse(body)
|
|
538
684
|
try {
|
|
539
685
|
const html = await settleWithin(render(react), timeoutMs, 'Rendering the react element')
|
|
540
|
-
return
|
|
686
|
+
return { ...content, html, ...(content.text === undefined && { text: toPlainText(html) }) }
|
|
541
687
|
} catch (cause) {
|
|
542
688
|
throw new EmailError({
|
|
543
689
|
code: 'react_render_failed',
|
|
@@ -599,6 +745,14 @@ function invalid(code: string, message: string, field: string): EmailError {
|
|
|
599
745
|
return new EmailError({ code, message, field })
|
|
600
746
|
}
|
|
601
747
|
|
|
748
|
+
function isHttps(url: string): boolean {
|
|
749
|
+
return url.toLowerCase().startsWith('https://')
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function isPlainHttp(url: string): boolean {
|
|
753
|
+
return url.toLowerCase().startsWith('http://')
|
|
754
|
+
}
|
|
755
|
+
|
|
602
756
|
/**
|
|
603
757
|
* The app host for a send, or undefined when the client can't tell it.
|
|
604
758
|
* PostHog Cloud ingestion hosts don't serve the app API, so they map to their region's app host.
|
|
@@ -640,8 +794,8 @@ function replyFields(payload: unknown): Record<string, unknown> {
|
|
|
640
794
|
>
|
|
641
795
|
}
|
|
642
796
|
|
|
643
|
-
function parseSendReply({ status,
|
|
644
|
-
const fields = replyFields(
|
|
797
|
+
function parseSendReply({ status, text: body, retryAfterMs }: Reply): SendEmailResult {
|
|
798
|
+
const fields = replyFields(parseJson(body))
|
|
645
799
|
if (status >= 200 && status < 300) {
|
|
646
800
|
const id = text(fields.message_id)
|
|
647
801
|
if (!id) {
|
|
@@ -668,8 +822,8 @@ function parseSendReply({ status, payload, retryAfterMs }: Reply): SendEmailResu
|
|
|
668
822
|
throw replyError(fields, status, retryAfterMs)
|
|
669
823
|
}
|
|
670
824
|
|
|
671
|
-
function parseStatusReply({ status,
|
|
672
|
-
const fields = replyFields(
|
|
825
|
+
function parseStatusReply({ status, text: body, retryAfterMs }: Reply): EmailStatus {
|
|
826
|
+
const fields = replyFields(parseJson(body))
|
|
673
827
|
if (status < 200 || status >= 300) {
|
|
674
828
|
throw replyError(fields, status, retryAfterMs)
|
|
675
829
|
}
|
|
@@ -687,8 +841,60 @@ function parseStatusReply({ status, payload, retryAfterMs }: Reply): EmailStatus
|
|
|
687
841
|
return { id, status: deliveryStatus, createdAt, statusAt, reason: text(fields.reason) ?? null }
|
|
688
842
|
}
|
|
689
843
|
|
|
690
|
-
function
|
|
691
|
-
const fields = replyFields(
|
|
844
|
+
function parseUploadsReply({ status, text: body, retryAfterMs }: Reply, requested: HashedFile[]): Upload[] {
|
|
845
|
+
const fields = replyFields(parseJson(body))
|
|
846
|
+
if (status === 404) {
|
|
847
|
+
throw replyError({ code: 'not_found', ...fields, attr: text(fields.attr) ?? 'attachments' }, status, retryAfterMs)
|
|
848
|
+
}
|
|
849
|
+
if (status < 200 || status >= 300) {
|
|
850
|
+
throw replyError({ ...fields, attr: callerField(text(fields.attr), requested) }, status, retryAfterMs)
|
|
851
|
+
}
|
|
852
|
+
const answers = Array.isArray(fields.files) ? fields.files.map(replyFields) : []
|
|
853
|
+
const uploads: Upload[] = []
|
|
854
|
+
for (const { sha256, bytes, field } of requested) {
|
|
855
|
+
const answer = answers.find((file) => file.sha256 === sha256)
|
|
856
|
+
if (answer?.status === 'present') {
|
|
857
|
+
continue
|
|
858
|
+
}
|
|
859
|
+
const url = text(answer?.url)
|
|
860
|
+
if (answer?.status !== 'upload' || !url || !isStringRecord(answer.headers)) {
|
|
861
|
+
throw new EmailError({
|
|
862
|
+
code: 'api_error',
|
|
863
|
+
message: 'PostHog answered without telling where to upload every file.',
|
|
864
|
+
statusCode: status,
|
|
865
|
+
})
|
|
866
|
+
}
|
|
867
|
+
uploads.push({ url, headers: answer.headers, bytes, field })
|
|
868
|
+
}
|
|
869
|
+
return uploads
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function callerField(attr: string | undefined, requested: HashedFile[]): string | undefined {
|
|
873
|
+
const file = attr === undefined ? null : /^files(?:__(\d+))?(?:__|$)/.exec(attr)
|
|
874
|
+
if (!file) {
|
|
875
|
+
return attr
|
|
876
|
+
}
|
|
877
|
+
return file[1] === undefined ? 'attachments' : (requested[Number(file[1])]?.field ?? 'attachments')
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
function isStringRecord(value: unknown): value is Record<string, string> {
|
|
881
|
+
return (
|
|
882
|
+
value !== null &&
|
|
883
|
+
typeof value === 'object' &&
|
|
884
|
+
!Array.isArray(value) &&
|
|
885
|
+
Object.values(value).every((item) => typeof item === 'string')
|
|
886
|
+
)
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
function storageAnswer({ status, text: body }: Reply): string {
|
|
890
|
+
const code = /<Code>([^<]{1,100})<\/Code>/.exec(body)?.[1]
|
|
891
|
+
const message = /<Message>([^<]{1,300})<\/Message>/.exec(body)?.[1]
|
|
892
|
+
const answer = `It answered HTTP ${status}${code ? ` ${code}` : ''}${message ? `: ${message}` : ''}`
|
|
893
|
+
return answer.endsWith('.') ? answer : `${answer}.`
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function parsePreferencesReply({ status, text: body, retryAfterMs }: Reply): EmailPreferences {
|
|
897
|
+
const fields = replyFields(parseJson(body))
|
|
692
898
|
if (status < 200 || status >= 300) {
|
|
693
899
|
throw replyError(fields, status, retryAfterMs)
|
|
694
900
|
}
|
|
@@ -735,12 +941,14 @@ function isRetryable(error: EmailError): boolean {
|
|
|
735
941
|
if (error.statusCode === undefined) {
|
|
736
942
|
return error.code === 'network_error'
|
|
737
943
|
}
|
|
944
|
+
if (error.code === 'attachment_upload_failed') {
|
|
945
|
+
return error.statusCode === 429 || error.statusCode >= 500
|
|
946
|
+
}
|
|
738
947
|
if (error.statusCode === 409) {
|
|
739
948
|
return error.code === 'idempotency_key_in_flight'
|
|
740
949
|
}
|
|
741
950
|
if (error.statusCode === 429) {
|
|
742
|
-
|
|
743
|
-
return error.code !== 'quota_limited'
|
|
951
|
+
return error.code !== 'quota_limited' && error.code !== 'upload_quota_exceeded'
|
|
744
952
|
}
|
|
745
953
|
return error.statusCode === 503
|
|
746
954
|
}
|