posthog-node 5.60.0 → 5.61.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.
@@ -0,0 +1,459 @@
1
+ import {
2
+ type FetchLike,
3
+ type Logger,
4
+ type PostHogFetchResponse,
5
+ parseRetryAfterMs,
6
+ removeTrailingSlash,
7
+ safeJsonStringify,
8
+ } from '@posthog/core'
9
+
10
+ import { EmailError } from './errors'
11
+ import type {
12
+ EmailStatus,
13
+ EmailWarning,
14
+ Emails,
15
+ GetEmailResponse,
16
+ SendEmailOptions,
17
+ SendEmailResponse,
18
+ SendEmailResult,
19
+ } from './types'
20
+
21
+ const SEND_PATH = '/api/projects/@current/messaging/send/email/'
22
+ const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/'
23
+ const US_APP_HOST = 'https://us.posthog.com'
24
+ const EU_APP_HOST = 'https://eu.posthog.com'
25
+ const CLOUD_APP_HOSTS: Record<string, string> = {
26
+ 'https://us.i.posthog.com': US_APP_HOST,
27
+ 'https://us.posthog.com': US_APP_HOST,
28
+ 'https://app.posthog.com': US_APP_HOST,
29
+ 'https://eu.i.posthog.com': EU_APP_HOST,
30
+ 'https://eu.posthog.com': EU_APP_HOST,
31
+ }
32
+ const MAX_RETRY_DELAY_MS = 30_000
33
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
34
+ const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7e]{1,255}$/
35
+
36
+ export const DEFAULT_EMAIL_REQUEST_TIMEOUT_MS = 15_000
37
+ export const DEFAULT_EMAIL_REQUEST_MAX_RETRIES = 2
38
+
39
+ export interface EmailSenderConfig {
40
+ secretKey?: string
41
+ /** The client's `host`. Used only when it is PostHog Cloud. */
42
+ host: string
43
+ appHost?: string
44
+ requestTimeoutMs: number
45
+ maxRetries: number
46
+ }
47
+
48
+ export interface EmailSenderHooks {
49
+ fetch: FetchLike
50
+ isDisabled: () => boolean
51
+ isClosed: () => boolean
52
+ logger: Logger
53
+ userAgent?: string
54
+ }
55
+
56
+ interface PreparedSend {
57
+ path: string
58
+ body: string
59
+ idempotencyKey: string
60
+ maxRetries: number
61
+ }
62
+
63
+ interface Reply {
64
+ status: number
65
+ payload: unknown
66
+ retryAfterMs?: number
67
+ }
68
+
69
+ /**
70
+ * Sends one transactional email per call to the messaging send API on the app host, and reads
71
+ * the status of a sent email. Owns the attempt loop, so every attempt of a send carries the same
72
+ * idempotency key.
73
+ */
74
+ export class EmailSender implements Emails {
75
+ private readonly config: EmailSenderConfig
76
+ private readonly hooks: EmailSenderHooks
77
+ private readonly inFlight = new Set<Promise<unknown>>()
78
+
79
+ constructor(config: EmailSenderConfig, hooks: EmailSenderHooks) {
80
+ this.config = config
81
+ this.hooks = hooks
82
+ }
83
+
84
+ send(options: SendEmailOptions): Promise<SendEmailResponse> {
85
+ return this.track(this.sendUntracked(options))
86
+ }
87
+
88
+ get(id: string): Promise<GetEmailResponse> {
89
+ return this.track(this.getUntracked(id))
90
+ }
91
+
92
+ private track<T>(pending: Promise<T>): Promise<T> {
93
+ this.inFlight.add(pending)
94
+ void pending.finally(() => this.inFlight.delete(pending))
95
+ return pending
96
+ }
97
+
98
+ /**
99
+ * Resolves when every send and status read in flight, retries included, has settled.
100
+ * Kept apart from the client's pending-promise queue, so a send in its retry backoff does not hold back `flush()`.
101
+ */
102
+ async drain(): Promise<void> {
103
+ while (this.inFlight.size > 0) {
104
+ await Promise.all(this.inFlight)
105
+ }
106
+ }
107
+
108
+ private async sendUntracked(options: SendEmailOptions): Promise<SendEmailResponse> {
109
+ try {
110
+ const prepared = prepareSend(options, this.config.maxRetries)
111
+ const { appHost, secretKey } = this.connect(
112
+ 'no email was sent',
113
+ 'Sending email needs secretKey, a project secret API key with the hog_flow:write scope.'
114
+ )
115
+ const headers = this.headers(secretKey, {
116
+ 'Content-Type': 'application/json',
117
+ 'Idempotency-Key': prepared.idempotencyKey,
118
+ })
119
+ const result = await this.withRetries(prepared.maxRetries, async () =>
120
+ parseSendReply(await this.request(appHost + prepared.path, 'POST', headers, prepared.body))
121
+ )
122
+ for (const warning of result.warnings) {
123
+ this.hooks.logger.warn(`PostHog email warning ${warning.code}: ${warning.message}`)
124
+ }
125
+ return { data: result, error: null }
126
+ } catch (error) {
127
+ return { data: null, error: asEmailError(error, 'Sending the email failed unexpectedly.') }
128
+ }
129
+ }
130
+
131
+ private async getUntracked(id: string): Promise<GetEmailResponse> {
132
+ try {
133
+ if (typeof id !== 'string' || !UUID_PATTERN.test(id)) {
134
+ throw invalid('invalid_message_id', 'id must be the message ID that send() returned.', 'id')
135
+ }
136
+ const { appHost, secretKey } = this.connect(
137
+ 'no email status was read',
138
+ 'Reading an email status needs secretKey, a project secret API key with the hog_flow:read or hog_flow:write scope.'
139
+ )
140
+ const url = appHost + STATUS_PATH.replace('{messageId}', id.toLowerCase())
141
+ const headers = this.headers(secretKey, {})
142
+ const status = await this.withRetries(this.config.maxRetries, async () =>
143
+ parseStatusReply(await this.request(url, 'GET', headers))
144
+ )
145
+ return { data: status, error: null }
146
+ } catch (error) {
147
+ return { data: null, error: asEmailError(error, 'Reading the email status failed unexpectedly.') }
148
+ }
149
+ }
150
+
151
+ private connect(nothingDone: string, missingSecretKey: string): { appHost: string; secretKey: string } {
152
+ if (this.hooks.isDisabled()) {
153
+ throw new EmailError({
154
+ code: 'client_disabled',
155
+ message: `The PostHog client is disabled, so ${nothingDone}.`,
156
+ })
157
+ }
158
+ if (this.hooks.isClosed()) {
159
+ throw new EmailError({
160
+ code: 'client_closed',
161
+ message: `The PostHog client is shut down, so ${nothingDone}.`,
162
+ })
163
+ }
164
+ const appHost = resolveAppHost(this.config.host, this.config.appHost)
165
+ if (!appHost) {
166
+ // A custom host is often an ingestion proxy, which must not receive the secret key.
167
+ throw new EmailError({
168
+ code: 'missing_app_host',
169
+ message:
170
+ "The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client.",
171
+ })
172
+ }
173
+ const secretKey = this.config.secretKey?.trim()
174
+ if (!secretKey) {
175
+ throw new EmailError({ code: 'missing_secret_key', message: missingSecretKey })
176
+ }
177
+ return { appHost, secretKey }
178
+ }
179
+
180
+ private headers(secretKey: string, extra: Record<string, string>): Record<string, string> {
181
+ const headers: Record<string, string> = {
182
+ Authorization: `Bearer ${secretKey}`,
183
+ Accept: 'application/json',
184
+ ...extra,
185
+ }
186
+ if (this.hooks.userAgent) {
187
+ headers['User-Agent'] = this.hooks.userAgent
188
+ }
189
+ return headers
190
+ }
191
+
192
+ private async withRetries<T>(maxRetries: number, attemptOnce: () => Promise<T>): Promise<T> {
193
+ for (let attempt = 0; ; attempt++) {
194
+ let error: EmailError
195
+ try {
196
+ return await attemptOnce()
197
+ } catch (caught) {
198
+ error =
199
+ caught instanceof EmailError
200
+ ? caught
201
+ : new EmailError({
202
+ code: 'network_error',
203
+ message: 'The request to PostHog failed.',
204
+ cause: caught,
205
+ })
206
+ }
207
+ const delayMs = retryDelayMs(error, attempt, maxRetries)
208
+ if (delayMs === undefined) {
209
+ throw error
210
+ }
211
+ // A plain timer, not an unref'd one: the caller awaits the request, so the process must stay up for the retry.
212
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
213
+ }
214
+ }
215
+
216
+ private async request(
217
+ url: string,
218
+ method: 'GET' | 'POST',
219
+ headers: Record<string, string>,
220
+ body?: string
221
+ ): Promise<Reply> {
222
+ const controller = new AbortController()
223
+ const timeoutMs = this.config.requestTimeoutMs
224
+ let timer: ReturnType<typeof setTimeout>
225
+ // `fetch` is injectable and may ignore the abort signal, so both phases race the deadline.
226
+ // A plain timer, not an unref'd one: an injected fetch may hold no handle, and the process must stay up until
227
+ // the deadline settles the send.
228
+ const deadline = new Promise<never>((_resolve, reject) => {
229
+ timer = setTimeout(() => {
230
+ const timeoutError = new Error(`Email request timed out after ${timeoutMs}ms`)
231
+ timeoutError.name = 'AbortError'
232
+ reject(timeoutError)
233
+ controller.abort(timeoutError)
234
+ }, timeoutMs)
235
+ })
236
+ const fetchPromise = Promise.resolve().then(() =>
237
+ this.hooks.fetch(url, {
238
+ method,
239
+ headers,
240
+ ...(body === undefined ? {} : { body }),
241
+ signal: controller.signal,
242
+ })
243
+ )
244
+ void fetchPromise
245
+ .then((lateResponse) => {
246
+ if (controller.signal.aborted) {
247
+ // Release a late response from an injected fetch that ignored the deadline, so it frees its connection.
248
+ void Promise.resolve(lateResponse.body?.cancel()).catch(() => {})
249
+ }
250
+ })
251
+ .catch(() => {})
252
+ let response: PostHogFetchResponse | undefined
253
+ try {
254
+ response = await Promise.race([fetchPromise, deadline])
255
+ let text: string
256
+ try {
257
+ text = await Promise.race([response.text(), deadline])
258
+ } catch (error) {
259
+ // An accepted send may already be queued, so a failed read stays a retryable network error.
260
+ if (response.status >= 200 && response.status < 300) {
261
+ throw error
262
+ }
263
+ // The status and Retry-After still decide the retry when an error body can't be read.
264
+ return { status: response.status, payload: null, retryAfterMs: readRetryAfter(response) }
265
+ }
266
+ return { status: response.status, payload: parseJson(text), retryAfterMs: readRetryAfter(response) }
267
+ } finally {
268
+ clearTimeout(timer!)
269
+ if (controller.signal.aborted && response) {
270
+ // Release a body whose read passed the deadline. Do not await: an injected cancel may never settle.
271
+ void Promise.resolve(response.body?.cancel()).catch(() => {})
272
+ }
273
+ }
274
+ }
275
+ }
276
+
277
+ function prepareSend(options: SendEmailOptions, defaultMaxRetries: number): PreparedSend {
278
+ const fallback: Partial<SendEmailOptions> = {}
279
+ const { to, templateId, templateData, distinctId, idempotencyKey, maxRetries } = options ?? fallback
280
+ if (typeof to !== 'string' || !to.trim()) {
281
+ throw invalid('invalid_recipient', 'to must be one email address as a nonempty string.', 'to')
282
+ }
283
+ if (typeof templateId !== 'string' || !UUID_PATTERN.test(templateId)) {
284
+ throw invalid('invalid_template_id', "templateId must be the template's UUID.", 'templateId')
285
+ }
286
+ if (
287
+ templateData !== undefined &&
288
+ (typeof templateData !== 'object' || templateData === null || Array.isArray(templateData))
289
+ ) {
290
+ throw invalid('invalid_template_data', 'templateData must be an object.', 'templateData')
291
+ }
292
+ if (distinctId !== undefined && (typeof distinctId !== 'string' || !distinctId)) {
293
+ throw invalid('invalid_distinct_id', 'distinctId must be a nonempty string.', 'distinctId')
294
+ }
295
+ if (
296
+ idempotencyKey !== undefined &&
297
+ (typeof idempotencyKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey))
298
+ ) {
299
+ throw invalid(
300
+ 'invalid_idempotency_key',
301
+ 'idempotencyKey must be 1 to 255 visible ASCII characters without spaces.',
302
+ 'idempotencyKey'
303
+ )
304
+ }
305
+ if (maxRetries !== undefined && !(Number.isInteger(maxRetries) && maxRetries >= 0)) {
306
+ throw invalid('invalid_max_retries', 'maxRetries must be a nonnegative integer.', 'maxRetries')
307
+ }
308
+
309
+ const payload: Record<string, unknown> = {
310
+ template: { id: templateId.toLowerCase() },
311
+ to,
312
+ message_data: templateData ?? {},
313
+ }
314
+ if (distinctId !== undefined) {
315
+ payload.identifiers = { distinct_id: distinctId }
316
+ }
317
+ return {
318
+ path: SEND_PATH,
319
+ body: safeJsonStringify(payload),
320
+ idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
321
+ maxRetries: maxRetries ?? defaultMaxRetries,
322
+ }
323
+ }
324
+
325
+ function invalid(code: string, message: string, field: string): EmailError {
326
+ return new EmailError({ code, message, field })
327
+ }
328
+
329
+ /**
330
+ * The app host for a send, or undefined when the client can't tell it.
331
+ * PostHog Cloud ingestion hosts don't serve the app API, so they map to their region's app host.
332
+ */
333
+ function resolveAppHost(host: string, appHost: string | undefined): string | undefined {
334
+ const explicit = typeof appHost === 'string' ? removeTrailingSlash(appHost.trim()) : ''
335
+ if (explicit) {
336
+ return CLOUD_APP_HOSTS[explicit] ?? explicit
337
+ }
338
+ return CLOUD_APP_HOSTS[removeTrailingSlash(host)]
339
+ }
340
+
341
+ function parseJson(text: string): unknown {
342
+ try {
343
+ return JSON.parse(text)
344
+ } catch {
345
+ return null
346
+ }
347
+ }
348
+
349
+ function readRetryAfter(response: PostHogFetchResponse): number | undefined {
350
+ try {
351
+ // The full wait, not the shared five minute cap: callers schedule their own retry from it, and the retry ceiling
352
+ // here applies separately in retryDelayMs.
353
+ return parseRetryAfterMs(response.headers?.get('retry-after'), Date.now(), Number.MAX_SAFE_INTEGER)
354
+ } catch {
355
+ return undefined
356
+ }
357
+ }
358
+
359
+ function text(value: unknown): string | undefined {
360
+ return typeof value === 'string' && value ? value : undefined
361
+ }
362
+
363
+ function replyFields(payload: unknown): Record<string, unknown> {
364
+ return (payload !== null && typeof payload === 'object' && !Array.isArray(payload) ? payload : {}) as Record<
365
+ string,
366
+ unknown
367
+ >
368
+ }
369
+
370
+ function parseSendReply({ status, payload, retryAfterMs }: Reply): SendEmailResult {
371
+ const fields = replyFields(payload)
372
+ if (status >= 200 && status < 300) {
373
+ const id = text(fields.message_id)
374
+ if (!id) {
375
+ throw new EmailError({
376
+ code: 'api_error',
377
+ message: 'PostHog answered without a message ID.',
378
+ statusCode: status,
379
+ })
380
+ }
381
+ const warnings: EmailWarning[] = []
382
+ if (Array.isArray(fields.warnings)) {
383
+ for (const warning of fields.warnings) {
384
+ if (warning !== null && typeof warning === 'object') {
385
+ warnings.push({
386
+ code: text(warning.code) ?? 'warning',
387
+ message: text(warning.detail) ?? text(warning.message) ?? '',
388
+ fix: text(warning.fix),
389
+ })
390
+ }
391
+ }
392
+ }
393
+ return { id, replayed: fields.replayed === true, warnings }
394
+ }
395
+ throw replyError(fields, status, retryAfterMs)
396
+ }
397
+
398
+ function parseStatusReply({ status, payload, retryAfterMs }: Reply): EmailStatus {
399
+ const fields = replyFields(payload)
400
+ if (status < 200 || status >= 300) {
401
+ throw replyError(fields, status, retryAfterMs)
402
+ }
403
+ const id = text(fields.id)
404
+ const deliveryStatus = text(fields.status)
405
+ const createdAt = text(fields.created_at)
406
+ const statusAt = text(fields.status_at)
407
+ if (!id || !deliveryStatus || !createdAt || !statusAt) {
408
+ throw new EmailError({
409
+ code: 'api_error',
410
+ message: 'PostHog answered without an email status.',
411
+ statusCode: status,
412
+ })
413
+ }
414
+ return { id, status: deliveryStatus, createdAt, statusAt, reason: text(fields.reason) ?? null }
415
+ }
416
+
417
+ function replyError(fields: Record<string, unknown>, status: number, retryAfterMs: number | undefined): EmailError {
418
+ return new EmailError({
419
+ code: text(fields.code) ?? 'api_error',
420
+ message: text(fields.detail) ?? `PostHog answered HTTP ${status}.`,
421
+ statusCode: status,
422
+ why: text(fields.why),
423
+ fix: text(fields.fix),
424
+ docsUrl: text(fields.docs_url),
425
+ field: text(fields.attr),
426
+ retryAfterMs,
427
+ })
428
+ }
429
+
430
+ function asEmailError(error: unknown, message: string): EmailError {
431
+ return error instanceof EmailError ? error : new EmailError({ code: 'unexpected_error', message, cause: error })
432
+ }
433
+
434
+ function isRetryable(error: EmailError): boolean {
435
+ // A send carries an idempotency key, so a retry can't queue a second email. A status read changes nothing.
436
+ if (error.statusCode === undefined) {
437
+ return error.code === 'network_error'
438
+ }
439
+ if (error.statusCode === 409) {
440
+ return error.code === 'idempotency_key_in_flight'
441
+ }
442
+ if (error.statusCode === 429) {
443
+ // Waiting doesn't fix a monthly quota.
444
+ return error.code !== 'quota_limited'
445
+ }
446
+ return error.statusCode === 503
447
+ }
448
+
449
+ function retryDelayMs(error: EmailError, attempt: number, maxRetries: number): number | undefined {
450
+ if (attempt >= maxRetries || !isRetryable(error)) {
451
+ return undefined
452
+ }
453
+ // Retrying before a longer Retry-After would break the server's rate limit.
454
+ if (error.retryAfterMs !== undefined && error.retryAfterMs > MAX_RETRY_DELAY_MS) {
455
+ return undefined
456
+ }
457
+ const backoffMs = Math.min(MAX_RETRY_DELAY_MS, 1000 * 2 ** attempt * (0.8 + Math.random() * 0.4))
458
+ return Math.max(backoffMs, error.retryAfterMs ?? 0)
459
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * A coarse category of the failure, for code that branches on the kind of failure rather than the exact `code`.
3
+ */
4
+ export type EmailErrorName =
5
+ | 'validation_error'
6
+ | 'missing_api_key'
7
+ | 'invalid_permission'
8
+ | 'not_found'
9
+ | 'concurrent_idempotent_requests'
10
+ | 'invalid_idempotent_request'
11
+ | 'rate_limit_exceeded'
12
+ | 'monthly_quota_exceeded'
13
+ | 'service_unavailable'
14
+ | 'application_error'
15
+
16
+ export interface EmailErrorParams {
17
+ code: string
18
+ message: string
19
+ statusCode?: number
20
+ why?: string
21
+ fix?: string
22
+ docsUrl?: string
23
+ field?: string
24
+ retryAfterMs?: number
25
+ cause?: unknown
26
+ }
27
+
28
+ /**
29
+ * PostHog did not queue the email, or the client could not tell whether it did.
30
+ *
31
+ * Branch on `code`, PostHog's stable error code, or on `name`, a coarse category of the
32
+ * failure. The message never contains the secret key or the request body.
33
+ */
34
+ export class EmailError extends Error {
35
+ override name: EmailErrorName
36
+ /** PostHog's error code, such as `quota_limited`, or an SDK code such as `network_error`. */
37
+ readonly code: string
38
+ /** The HTTP status, when PostHog answered. */
39
+ readonly statusCode?: number
40
+ readonly why?: string
41
+ readonly fix?: string
42
+ readonly docsUrl?: string
43
+ /** The request field the error is about, when PostHog named one. */
44
+ readonly field?: string
45
+ /** How long PostHog asked the client to wait before it sends again, in milliseconds. */
46
+ readonly retryAfterMs?: number
47
+
48
+ constructor(params: EmailErrorParams) {
49
+ super(params.message, params.cause === undefined ? undefined : { cause: params.cause })
50
+ this.name = emailErrorName(params.statusCode, params.code)
51
+ this.code = params.code
52
+ this.statusCode = params.statusCode
53
+ this.why = params.why
54
+ this.fix = params.fix
55
+ this.docsUrl = params.docsUrl
56
+ this.field = params.field
57
+ this.retryAfterMs = params.retryAfterMs
58
+ }
59
+ }
60
+
61
+ function emailErrorName(status: number | undefined, code: string): EmailErrorName {
62
+ if (code === 'missing_secret_key' || status === 401) {
63
+ return 'missing_api_key'
64
+ }
65
+ if (status === undefined) {
66
+ if (code === 'network_error') {
67
+ return 'service_unavailable'
68
+ }
69
+ return code.startsWith('invalid_') ? 'validation_error' : 'application_error'
70
+ }
71
+ switch (status) {
72
+ case 400:
73
+ return 'validation_error'
74
+ case 403:
75
+ return 'invalid_permission'
76
+ case 404:
77
+ return 'not_found'
78
+ case 409:
79
+ return code === 'template_outdated' ? 'validation_error' : 'concurrent_idempotent_requests'
80
+ case 422:
81
+ // The template send route also answers 422 for send checks such as recipient_suppressed.
82
+ return code === 'idempotency_key_reused' ? 'invalid_idempotent_request' : 'validation_error'
83
+ case 429:
84
+ return code === 'quota_limited' ? 'monthly_quota_exceeded' : 'rate_limit_exceeded'
85
+ case 503:
86
+ return 'service_unavailable'
87
+ default:
88
+ return 'application_error'
89
+ }
90
+ }
@@ -0,0 +1,108 @@
1
+ import type { EmailError } from './errors'
2
+
3
+ /**
4
+ * Options for `posthog.emails.send()`.
5
+ */
6
+ export interface SendEmailOptions {
7
+ /** One recipient email address. */
8
+ to: string
9
+ /** The UUID of an email template made transactional in PostHog. */
10
+ templateId: string
11
+ /** Values for the template's `{{ variables.* }}` placeholders. Sent as `message_data`. */
12
+ templateData?: Record<string, unknown>
13
+ /**
14
+ * The recipient's distinct ID in your product. The email's events go to this person.
15
+ * Without it, they go to a person whose distinct ID is the email address.
16
+ */
17
+ distinctId?: string
18
+ /**
19
+ * 1 to 255 visible ASCII characters. A send with a key that PostHog has already accepted
20
+ * queues nothing and returns the first send's result. Without it, the client makes a
21
+ * UUID that covers its own retries. Pass a key derived from what the email is for, such
22
+ * as `welcome:user_123`, to cover retries outside this call too.
23
+ */
24
+ idempotencyKey?: string
25
+ /** Overrides the client's `emailRequestMaxRetries` for this send. `0` turns retries off. */
26
+ maxRetries?: number
27
+ }
28
+
29
+ /** A warning PostHog returned with a queued email. */
30
+ export interface EmailWarning {
31
+ code: string
32
+ message: string
33
+ fix?: string
34
+ }
35
+
36
+ /**
37
+ * The queued email. A result means PostHog queued the email, not that it was delivered.
38
+ */
39
+ export interface SendEmailResult {
40
+ /** The queued email's message ID. */
41
+ id: string
42
+ /** True when PostHog had already accepted this idempotency key and returned the first send's result. */
43
+ replayed: boolean
44
+ warnings: EmailWarning[]
45
+ }
46
+
47
+ /**
48
+ * What `posthog.emails.send()` resolves to. Exactly one of `data` and `error` is set.
49
+ * The promise does not reject.
50
+ */
51
+ export type SendEmailResponse = { data: SendEmailResult; error: null } | { data: null; error: EmailError }
52
+
53
+ /**
54
+ * What happened to an email. Later SDK versions can see values this list does not have yet.
55
+ *
56
+ * - `queued`: the email waits to go out.
57
+ * - `sent`: PostHog handed the email to the email provider.
58
+ * - `failed`: the email was not sent, and `reason` says why.
59
+ * - `delivered`: the recipient's mail server accepted the email.
60
+ * - `bounced` and `complained`: the recipient's mail provider reported them after delivery.
61
+ */
62
+ export type EmailDeliveryStatus = 'queued' | 'sent' | 'failed' | 'delivered' | 'bounced' | 'complained'
63
+
64
+ /** The status of an email that `posthog.emails.send()` queued. */
65
+ export interface EmailStatus {
66
+ /** The message ID that `send()` returned. */
67
+ id: string
68
+ status: EmailDeliveryStatus | (string & {})
69
+ /** When PostHog queued the email, as an ISO 8601 timestamp. */
70
+ createdAt: string
71
+ /** When the email reached its current status, as an ISO 8601 timestamp. */
72
+ statusAt: string
73
+ /**
74
+ * Why a failed email was not sent, such as `provider_error` or `recipient_suppressed`, or the
75
+ * bounce type of a bounced email: `hard`, `soft` or `unknown`. Null otherwise.
76
+ */
77
+ reason: string | null
78
+ }
79
+
80
+ /**
81
+ * What `posthog.emails.get()` resolves to. Exactly one of `data` and `error` is set.
82
+ * The promise does not reject.
83
+ */
84
+ export type GetEmailResponse = { data: EmailStatus; error: null } | { data: null; error: EmailError }
85
+
86
+ /**
87
+ * The `posthog.emails` API: sends transactional email from PostHog email templates, and reads
88
+ * the status of each email it sent.
89
+ */
90
+ export interface Emails {
91
+ /**
92
+ * Queue one email from a transactional email template.
93
+ *
94
+ * Resolves to `{ data, error }` and does not reject. `data` means PostHog queued the email,
95
+ * not that it was delivered. Network errors, rate limits, an in-flight idempotency key and
96
+ * an unavailable service are retried with the same idempotency key.
97
+ */
98
+ send(options: SendEmailOptions): Promise<SendEmailResponse>
99
+
100
+ /**
101
+ * Read the status of an email that `send()` queued, for 30 days after the send.
102
+ *
103
+ * Resolves to `{ data, error }` and does not reject. The error code is `not_found` when no
104
+ * email of this project has the ID, when the email is older than 30 days, or for a few
105
+ * seconds after the send. Network errors, rate limits and an unavailable service are retried.
106
+ */
107
+ get(id: string): Promise<GetEmailResponse>
108
+ }
package/src/exports.ts CHANGED
@@ -4,6 +4,18 @@ export * from './types'
4
4
  export { enrichCurrentSpan } from './extensions/context/listeners'
5
5
 
6
6
  export { FeatureFlagEvaluations } from './feature-flag-evaluations'
7
+ export { EmailError } from './emails/errors'
8
+ export type { EmailErrorName } from './emails/errors'
9
+ export type {
10
+ EmailDeliveryStatus,
11
+ Emails,
12
+ EmailStatus,
13
+ EmailWarning,
14
+ GetEmailResponse,
15
+ SendEmailOptions,
16
+ SendEmailResponse,
17
+ SendEmailResult,
18
+ } from './emails/types'
7
19
  export type {
8
20
  FlagDefinitionCacheData,
9
21
  FlagDefinitionCacheInput,