posthog-node 5.71.0 → 5.73.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 +53 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +94 -19
- package/dist/client.mjs +94 -19
- 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/feature-flag-evaluations.d.ts +14 -0
- package/dist/feature-flag-evaluations.d.ts.map +1 -1
- package/dist/feature-flag-evaluations.js +2 -1
- package/dist/feature-flag-evaluations.mjs +2 -1
- package/dist/flag-events.d.ts +112 -0
- package/dist/flag-events.d.ts.map +1 -0
- package/dist/flag-events.js +230 -0
- package/dist/flag-events.mjs +174 -0
- package/dist/flags-response.d.ts +83 -0
- package/dist/flags-response.d.ts.map +1 -0
- package/dist/flags-response.js +255 -0
- package/dist/flags-response.mjs +208 -0
- 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 +4 -3
- package/src/client.ts +238 -45
- 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/feature-flag-evaluations.ts +17 -0
- package/src/flag-events.ts +280 -0
- package/src/flags-response.ts +340 -0
- package/src/types.ts +2 -1
- package/src/version.ts +1 -1
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
|
}
|
package/src/emails/errors.ts
CHANGED
|
@@ -35,7 +35,7 @@ export class EmailError extends Error {
|
|
|
35
35
|
override name: EmailErrorName
|
|
36
36
|
/** PostHog's error code, such as `quota_limited`, or an SDK code such as `network_error`. */
|
|
37
37
|
readonly code: string
|
|
38
|
-
/** The HTTP status, when PostHog answered. */
|
|
38
|
+
/** The HTTP status, when PostHog or its file storage answered. */
|
|
39
39
|
readonly statusCode?: number
|
|
40
40
|
readonly why?: string
|
|
41
41
|
readonly fix?: string
|
|
@@ -58,6 +58,8 @@ export class EmailError extends Error {
|
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
const ATTACHMENT_LIMIT_CODES: ReadonlySet<string> = new Set(['too_many_attachments', 'message_too_large'])
|
|
62
|
+
|
|
61
63
|
function emailErrorName(status: number | undefined, code: string): EmailErrorName {
|
|
62
64
|
if (code === 'missing_secret_key' || status === 401) {
|
|
63
65
|
return 'missing_api_key'
|
|
@@ -66,7 +68,10 @@ function emailErrorName(status: number | undefined, code: string): EmailErrorNam
|
|
|
66
68
|
if (code === 'network_error') {
|
|
67
69
|
return 'service_unavailable'
|
|
68
70
|
}
|
|
69
|
-
return code.startsWith('invalid_') ? 'validation_error' : 'application_error'
|
|
71
|
+
return code.startsWith('invalid_') || ATTACHMENT_LIMIT_CODES.has(code) ? 'validation_error' : 'application_error'
|
|
72
|
+
}
|
|
73
|
+
if (code === 'attachment_upload_failed') {
|
|
74
|
+
return status >= 500 ? 'service_unavailable' : 'application_error'
|
|
70
75
|
}
|
|
71
76
|
switch (status) {
|
|
72
77
|
case 400:
|
package/src/emails/types.ts
CHANGED
|
@@ -39,6 +39,16 @@ interface CodeEmailFields {
|
|
|
39
39
|
/** A verified sender, such as `'Acme <security@example.com>'`. Without it, the project's default sender. */
|
|
40
40
|
from?: string
|
|
41
41
|
replyTo?: string | string[]
|
|
42
|
+
/** Bare addresses, such as `'finance@example.com'`, that get a copy. */
|
|
43
|
+
cc?: string | string[]
|
|
44
|
+
/** Bare addresses that get a copy the other recipients never see. */
|
|
45
|
+
bcc?: string | string[]
|
|
46
|
+
/**
|
|
47
|
+
* Files sent with the email: at most 10, and at most 40 MB for the whole email after Base64
|
|
48
|
+
* encoding, about 29 MB of files. The SDK checks both before any request. It uploads each file
|
|
49
|
+
* PostHog doesn't have yet, then sends the email. When an upload fails, it sends nothing.
|
|
50
|
+
*/
|
|
51
|
+
attachments?: EmailAttachment[]
|
|
42
52
|
/**
|
|
43
53
|
* Whether PostHog captures the email's engagement events (sent, delivered, opened, clicked,
|
|
44
54
|
* bounced) as events of the recipient. Defaults to `true`. A project whose admin turned
|
|
@@ -92,6 +102,20 @@ export interface EmailTracking {
|
|
|
92
102
|
engagement?: boolean
|
|
93
103
|
}
|
|
94
104
|
|
|
105
|
+
/** A file sent with the email. */
|
|
106
|
+
export interface EmailAttachment {
|
|
107
|
+
/** The name the recipient sees, such as `'invoice.pdf'`. */
|
|
108
|
+
filename: string
|
|
109
|
+
/** The file's bytes, or its content already Base64 encoded. At least one byte. */
|
|
110
|
+
content: Uint8Array | string
|
|
111
|
+
/** A MIME type, such as `'application/pdf'`. */
|
|
112
|
+
contentType?: string
|
|
113
|
+
/** Shows the file inline where the HTML has `<img src="cid:...">` with this id. */
|
|
114
|
+
contentId?: string
|
|
115
|
+
/** PostHog can't fetch a file from a path or URL: read the file and pass its `content`. */
|
|
116
|
+
path?: never
|
|
117
|
+
}
|
|
118
|
+
|
|
95
119
|
/**
|
|
96
120
|
* A React element, such as `<WelcomeEmail firstName="Ada" />`. Typed by its shape, so
|
|
97
121
|
* posthog-node needs no React types.
|
package/src/exports.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { FeatureFlagValue, JsonType, UnresolvedFlagReason } from '@posthog/core'
|
|
2
2
|
|
|
3
|
+
import type { ParsedFlagRecord } from './flags-response'
|
|
3
4
|
import { FeatureFlagError } from './types'
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -19,6 +20,12 @@ export type EvaluatedFlagRecord = {
|
|
|
19
20
|
locallyEvaluated: boolean
|
|
20
21
|
/** Whether the flag is linked to an experiment; undefined when the server did not report it. */
|
|
21
22
|
hasExperiment: boolean | undefined
|
|
23
|
+
/**
|
|
24
|
+
* The parsed `/flags` record of a remotely evaluated flag, with its typed value, failure
|
|
25
|
+
* state, reason and rule metadata, for the typed flag API and flag events. Absent for locally
|
|
26
|
+
* evaluated flags and flags with a value override.
|
|
27
|
+
*/
|
|
28
|
+
parsed?: ParsedFlagRecord
|
|
22
29
|
}
|
|
23
30
|
|
|
24
31
|
/**
|
|
@@ -33,6 +40,13 @@ export type FlagCalledEventParams = {
|
|
|
33
40
|
groups: Record<string, string | number> | undefined
|
|
34
41
|
disableGeoip: boolean | undefined
|
|
35
42
|
properties: Record<string, any>
|
|
43
|
+
/**
|
|
44
|
+
* The parsed `/flags` record that supplied the read's value. Absent when the value came from
|
|
45
|
+
* local evaluation or an override, or the flag is missing. A config version 2 record adds its
|
|
46
|
+
* attribution to `$feature_flag_called`, and a complete experiment split also sends
|
|
47
|
+
* `$experiment_exposure`.
|
|
48
|
+
*/
|
|
49
|
+
record?: ParsedFlagRecord
|
|
36
50
|
}
|
|
37
51
|
|
|
38
52
|
/**
|
|
@@ -375,6 +389,9 @@ export class FeatureFlagEvaluations {
|
|
|
375
389
|
groups: this._groups,
|
|
376
390
|
disableGeoip: this._disableGeoip,
|
|
377
391
|
properties,
|
|
392
|
+
// The record that supplied the value. A remotely evaluated experiment split also sends
|
|
393
|
+
// $experiment_exposure.
|
|
394
|
+
record: flag?.parsed,
|
|
378
395
|
})
|
|
379
396
|
}
|
|
380
397
|
}
|