posthog-node 5.68.2 → 5.70.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.
@@ -45,16 +45,36 @@ interface CodeEmailFields {
45
45
  captureEngagement?: boolean;
46
46
  }
47
47
  /**
48
- * Email content your code rendered, such as React Email output, named by a key. PostHog sends it
49
- * as is and never stores it. Needs `html`, `text` or both. PostHog derives a missing `text` from
50
- * the `html`.
48
+ * A React element, such as `<WelcomeEmail firstName="Ada" />`. Typed by its shape, so
49
+ * posthog-node needs no React types.
50
+ */
51
+ export interface EmailReactElement {
52
+ type: unknown;
53
+ props: unknown;
54
+ }
55
+ /**
56
+ * Email content from your code, named by a key: `html`, `text` or both, or a `react` element
57
+ * the client renders. PostHog sends it as is and never stores it. PostHog derives a missing
58
+ * `text` from the `html`.
51
59
  */
52
60
  export type CodeEmailForm = CodeEmailFields & ({
53
61
  html: string;
54
62
  text?: string;
63
+ react?: never;
55
64
  } | {
56
65
  html?: string;
57
66
  text: string;
67
+ react?: never;
68
+ } | {
69
+ /**
70
+ * A React Email element. The client renders it into `html`, and into `text` when the
71
+ * send has none. Needs the `@react-email/render` package installed next to posthog-node.
72
+ * The client renders the element after `send()` returns, so give each send its own
73
+ * element and props, and don't change them while the send is pending.
74
+ */
75
+ react: EmailReactElement;
76
+ text?: string;
77
+ html?: never;
58
78
  });
59
79
  type Without<T> = {
60
80
  [K in keyof T]?: never;
@@ -62,6 +82,7 @@ type Without<T> = {
62
82
  export type SendTemplateEmailOptions = SendEmailBase & TemplateEmailForm & Without<CodeEmailFields & {
63
83
  html: string;
64
84
  text: string;
85
+ react: EmailReactElement;
65
86
  }>;
66
87
  export type SendCodeEmailOptions = SendEmailBase & CodeEmailForm & Without<TemplateEmailForm>;
67
88
  /** Options for `posthog.emails.send()`: a template made in PostHog, or content from your code. */
@@ -129,9 +150,48 @@ export type GetEmailResponse = {
129
150
  data: null;
130
151
  error: EmailError;
131
152
  };
153
+ /**
154
+ * Options for `posthog.emails.setPreferences()`. Set `allMarketing`, `topics`, or both.
155
+ */
156
+ export interface SetEmailPreferencesOptions {
157
+ /**
158
+ * The recipient's email address, exactly as Workflows sends to it. Matching is exact, so `Jane@example.com` and
159
+ * `jane@example.com` are two recipients.
160
+ */
161
+ to: string;
162
+ /** `false` opts the recipient out of every marketing topic. `true` lifts that opt-out. Applied before `topics`. */
163
+ allMarketing?: boolean;
164
+ /**
165
+ * Topic key to `false` to opt the recipient out of that topic, or `true` to opt them back in. Topic keys are the
166
+ * ones you set under Workflows opt-outs. Opting back in to one marketing topic after an all-marketing opt-out lifts
167
+ * that opt-out, so `allMarketing` becomes `true`, and keeps the other marketing topics opted out. Topics you leave out
168
+ * keep their current choice.
169
+ */
170
+ topics?: Record<string, boolean>;
171
+ }
172
+ /** A recipient's preferences after the change. */
173
+ export interface EmailPreferences {
174
+ to: string;
175
+ /** `false` when the recipient opted out of all marketing, `true` when they opted back in, `null` when they never chose. */
176
+ allMarketing: boolean | null;
177
+ /** Topic key to `false` (opted out) or `true` (opted in), for every topic the recipient chose. */
178
+ topics: Record<string, boolean>;
179
+ }
180
+ /**
181
+ * What `posthog.emails.setPreferences()` resolves to. Exactly one of `data` and `error` is set.
182
+ * The promise does not reject.
183
+ */
184
+ export type SetEmailPreferencesResponse = {
185
+ data: EmailPreferences;
186
+ error: null;
187
+ } | {
188
+ data: null;
189
+ error: EmailError;
190
+ };
132
191
  /**
133
192
  * The `posthog.emails` API: sends transactional email from PostHog email templates or from
134
- * content your code rendered, and reads the status of each email it sent.
193
+ * content your code rendered, reads the status of each email it sent, and sets a recipient's
194
+ * topic preferences.
135
195
  */
136
196
  export interface Emails {
137
197
  /**
@@ -150,6 +210,17 @@ export interface Emails {
150
210
  * seconds after the send. Network errors, rate limits and an unavailable service are retried.
151
211
  */
152
212
  get(id: string): Promise<GetEmailResponse>;
213
+ /**
214
+ * Opt one recipient out of topics, or back in, in one request. PostHog saves the whole change at once. The same
215
+ * change twice ends the same, but a retry that lands after a newer change for the same recipient undoes that
216
+ * change. A failed call may still have saved the change. Workflows sends skip a marketing topic the recipient
217
+ * opted out of.
218
+ *
219
+ * Resolves to `{ data, error }` and does not reject. The error code is `unknown_topic` when a topic key names no
220
+ * topic of the project, and nothing is saved. A plain `not_found` means the PostHog instance has no preferences
221
+ * API yet. Network errors, rate limits and an unavailable service are retried.
222
+ */
223
+ setPreferences(options: SetEmailPreferencesOptions): Promise<SetEmailPreferencesResponse>;
153
224
  }
154
225
  export {};
155
226
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/emails/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAE1C,gDAAgD;AAChD,MAAM,WAAW,aAAa;IAC5B,mCAAmC;IACnC,EAAE,EAAE,MAAM,CAAA;IACV;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,4FAA4F;IAC5F,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,gEAAgE;AAChE,MAAM,WAAW,iBAAiB;IAChC,mEAAmE;IACnE,UAAU,EAAE,MAAM,CAAA;IAClB,0FAA0F;IAC1F,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACvC;AAED,UAAU,eAAe;IACvB;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAA;IACnB,OAAO,EAAE,MAAM,CAAA;IACf,4GAA4G;IAC5G,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAC3B;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAA;CAC5B;AAED;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,eAAe,GAAG,CAAC;IAAE,IAAI,EAAE,MA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V,mHAAmH;IACnH,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACjC;AAED,kDAAkD;AAClD,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAA;IACV,2HAA2H;IAC3H,YAAY,EAAE,OAAO,GAAG,IAAI,CAAA;IAC5B,kGAAkG;IAClG,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAChC;AAED;;;GAGG;AACH,MAAM,MAAM,2BAA2B,GAAG;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,KAAK,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,UAAU,CAAA;CAAE,CAAA;AAErH;;;;GAIG;AACH,MAAM,WAAW,MAAM;IACrB;;;;;;OAMG;IACH,IAAI,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAA;IAE3D;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;IAE1C;;;;;;;;;OASG;IACH,cAAc,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAA;CAC1F"}
package/dist/exports.d.ts CHANGED
@@ -6,7 +6,7 @@ export { enrichCurrentSpan } from './extensions/context/listeners';
6
6
  export { FeatureFlagEvaluations } from './feature-flag-evaluations';
7
7
  export { EmailError } from './emails/errors';
8
8
  export type { EmailErrorName } from './emails/errors';
9
- export type { CodeEmailForm, EmailDeliveryStatus, Emails, EmailStatus, EmailWarning, GetEmailResponse, SendCodeEmailOptions, SendEmailBase, SendEmailOptions, SendEmailResponse, SendEmailResult, SendTemplateEmailOptions, TemplateEmailForm, } from './emails/types';
9
+ export type { CodeEmailForm, EmailDeliveryStatus, EmailPreferences, EmailReactElement, Emails, EmailStatus, EmailWarning, GetEmailResponse, SendCodeEmailOptions, SendEmailBase, SendEmailOptions, SendEmailResponse, SendEmailResult, SendTemplateEmailOptions, SetEmailPreferencesOptions, SetEmailPreferencesResponse, TemplateEmailForm, } from './emails/types';
10
10
  export type { FlagDefinitionCacheData, FlagDefinitionCacheInput, FlagDefinitionCacheProvider, } from './extensions/feature-flags/cache';
11
11
  export { FeatureFlagError } from '@posthog/core';
12
12
  export type { FeatureFlagErrorType, UnresolvedFlagReason } from '@posthog/core';
@@ -1 +1 @@
1
- {"version":3,"file":"exports.d.ts","sourceRoot":"","sources":["../src/exports.ts"],"names":[],"mappings":"AAAA,cAAc,iCAAiC,CAAA;AAC/C,cAAc,sBAAsB,CAAA;AACpC,cAAc,4BAA4B,CAAA;AAC1C,cAAc,SAAS,CAAA;AACvB,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAA;AAElE,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAA;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AACrD,YAAY,EACV,aAAa,EACb,mBAAmB,EACnB,MAAM,EACN,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,EACpB,aAAa,EACb,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,wBAAwB,EACxB,iBAAiB,GAClB,MAAM,gBAAgB,CAAA;AACvB,YAAY,EACV,uBAAuB,EACvB,wBAAwB,EACxB,2BAA2B,GAC5B,MAAM,kCAAkC,CAAA;AAIzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAChD,YAAY,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AAI/E,YAAY,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAInG,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gB,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAInG,YAAY,EACV,IAAI,EACJ,cAAc,EACd,kBAAkB,EAClB,QAAQ,EACR,cAAc,EACd,aAAa,EACb,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAChB,YAAY,GACb,MAAM,eAAe,CAAA;AAKtB,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EAClB,iBAAiB,EACjB,sBAAsB,EACtB,MAAM,GACP,MAAM,eAAe,CAAA;AACtB,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA"}
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const version = "5.68.2";
1
+ export declare const version = "5.70.0";
2
2
  //# sourceMappingURL=version.d.ts.map
package/dist/version.js CHANGED
@@ -27,7 +27,7 @@ var __webpack_require__ = {};
27
27
  })();
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
- const version = "5.68.2";
30
+ const version = "5.70.0";
31
31
  __webpack_require__.d(__webpack_exports__, {}, {
32
32
  version: version
33
33
  });
package/dist/version.mjs CHANGED
@@ -1,2 +1,2 @@
1
- const version = "5.68.2";
1
+ const version = "5.70.0";
2
2
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-node",
3
- "version": "5.68.2",
3
+ "version": "5.70.0",
4
4
  "bugs": {
5
5
  "url": "https://github.com/PostHog/posthog-js/issues"
6
6
  },
@@ -36,25 +36,33 @@
36
36
  "@opentelemetry/api": "^1.9.0",
37
37
  "@opentelemetry/context-async-hooks": "^2.2.0",
38
38
  "@opentelemetry/sdk-trace-base": "^2.10.0",
39
+ "@react-email/render": "^2.1.1",
39
40
  "@rslib/core": "0.23.2",
40
41
  "@types/express": "^5.0.6",
41
42
  "@types/node": "^20.0.0",
43
+ "@types/react": "^19.2.7",
42
44
  "esbuild": "^0.25.0",
43
45
  "@vitest/coverage-v8": "^1.6.1",
46
+ "react": "^19.2.1",
47
+ "react-dom": "^19.2.1",
44
48
  "rxjs": "^7.8.0",
45
49
  "typescript": "7.0.2",
46
50
  "vitest": "^1.6.1",
47
- "@posthog/types": "^1.423.0",
48
- "@posthog-tooling/tsconfig-base": "1.1.1"
51
+ "@posthog-tooling/tsconfig-base": "1.1.1",
52
+ "@posthog/types": "^1.424.1"
49
53
  },
50
54
  "peerDependencies": {
51
55
  "@opentelemetry/api": "^1.2.0",
56
+ "@react-email/render": "^2.1.0",
52
57
  "rxjs": "^7.0.0"
53
58
  },
54
59
  "peerDependenciesMeta": {
55
60
  "@opentelemetry/api": {
56
61
  "optional": true
57
62
  },
63
+ "@react-email/render": {
64
+ "optional": true
65
+ },
58
66
  "rxjs": {
59
67
  "optional": true
60
68
  }
@@ -131,7 +139,6 @@
131
139
  "prebuild": "node ../../tooling/write-version.mjs",
132
140
  "build": "rslib build",
133
141
  "dev": "rslib build -w",
134
- "package": "pnpm pack --out $PACKAGE_DEST/%s.tgz",
135
- "generate-references": "pnpm exec api-extractor run --config ./api-extractor.jsonc --local && node scripts/generate-docs.mjs"
142
+ "package": "pnpm pack --out $PACKAGE_DEST/%s.tgz"
136
143
  }
137
144
  }
package/src/client.ts CHANGED
@@ -814,14 +814,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
814
814
  }
815
815
 
816
816
  /**
817
- * The `posthog.emails` API: sends transactional email from PostHog email templates, and reads
818
- * the status of each email it sent.
819
- *
820
- * Needs `secretKey`, a project secret API key with the `transactional_email:write` scope (the
821
- * "Send transactional email" preset). A key with only `transactional_email:read` can read
822
- * statuses but not send. Keys made with `hog_flow:write` still work. Requests go to `appHost`,
823
- * or to the PostHog Cloud app host of `host`. `send` and `get` resolve to `{ data, error }` and
824
- * do not reject.
817
+ * The `posthog.emails` API: sends transactional email from PostHog email templates, reads
818
+ * the status of each email it sent, and sets a recipient's topic preferences.
819
+ *
820
+ * Needs `secretKey`, a project secret API key. `send` needs the `transactional_email:write` scope
821
+ * (the "Send transactional email" preset), and `get` needs `transactional_email:read` or
822
+ * `transactional_email:write`. `setPreferences` needs the
823
+ * `messaging_preference:write` scope, which cannot send email. Keys made with `hog_flow:write` still
824
+ * work for all three. Requests go to `appHost`, or to the PostHog Cloud app host of `host`. `send`,
825
+ * `get` and `setPreferences` resolve to `{ data, error }` and do not reject.
825
826
  * `data.id` is the queued email's message ID, which `get` takes. A disabled client sends nothing
826
827
  * and returns the error `client_disabled`. After `shutdown()`, the client sends nothing and
827
828
  * returns the error `client_closed`.
@@ -841,6 +842,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
841
842
  * }
842
843
  *
843
844
  * const status = await client.emails.get(data.id) // later, for example from a job
845
+ *
846
+ * // From a preference center: opt out of one topic, keep the rest
847
+ * await client.emails.setPreferences({ to: 'user@example.com', topics: { newsletter: false } })
844
848
  * ```
845
849
  *
846
850
  * {@label Emails}
@@ -10,6 +10,8 @@ import {
10
10
  import { EmailError } from './errors'
11
11
  import type {
12
12
  CodeEmailForm,
13
+ EmailPreferences,
14
+ EmailReactElement,
13
15
  EmailStatus,
14
16
  EmailWarning,
15
17
  Emails,
@@ -19,11 +21,14 @@ import type {
19
21
  SendEmailResponse,
20
22
  SendEmailResult,
21
23
  SendTemplateEmailOptions,
24
+ SetEmailPreferencesOptions,
25
+ SetEmailPreferencesResponse,
22
26
  TemplateEmailForm,
23
27
  } from './types'
24
28
 
25
29
  const SEND_PATH = '/api/projects/@current/messaging/send/email/'
26
30
  const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/'
31
+ const PREFERENCES_PATH = '/api/projects/@current/messaging/preferences/'
27
32
  const US_APP_HOST = 'https://us.posthog.com'
28
33
  const EU_APP_HOST = 'https://eu.posthog.com'
29
34
  const CLOUD_APP_HOSTS: Record<string, string> = {
@@ -39,6 +44,10 @@ const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7e]{1,255}$/
39
44
  const TEMPLATE_KEY_PATTERN = /^[a-zA-Z0-9_-]{1,400}$/
40
45
 
41
46
  type EveryField<Form> = Record<keyof Form, true>
47
+ interface ReactRenderer {
48
+ render(element: EmailReactElement): Promise<string>
49
+ toPlainText(html: string): string
50
+ }
42
51
  type UncheckedSend = { [Field in keyof SendTemplateEmailOptions]?: unknown }
43
52
 
44
53
  interface SendForm {
@@ -63,6 +72,7 @@ const CODE_FIELDS: EveryField<CodeEmailForm> = {
63
72
  captureEngagement: true,
64
73
  html: true,
65
74
  text: true,
75
+ react: true,
66
76
  }
67
77
  const TEMPLATE_FORM: SendForm = {
68
78
  name: 'templateId',
@@ -99,8 +109,8 @@ export interface EmailSenderHooks {
99
109
  }
100
110
 
101
111
  interface PreparedSend {
102
- path: string
103
112
  body: string
113
+ react?: EmailReactElement
104
114
  idempotencyKey: string
105
115
  maxRetries: number
106
116
  }
@@ -112,9 +122,9 @@ interface Reply {
112
122
  }
113
123
 
114
124
  /**
115
- * Sends one transactional email per call to the messaging send API on the app host, and reads
116
- * the status of a sent email. Owns the attempt loop, so every attempt of a send carries the same
117
- * idempotency key.
125
+ * Sends one transactional email per call to the messaging send API on the app host, reads the
126
+ * status of a sent email, and sets a recipient's topic preferences. Owns the attempt loop, so every
127
+ * attempt of a send carries the same idempotency key.
118
128
  */
119
129
  export class EmailSender implements Emails {
120
130
  private readonly config: EmailSenderConfig
@@ -134,6 +144,10 @@ export class EmailSender implements Emails {
134
144
  return this.track(this.getUntracked(id))
135
145
  }
136
146
 
147
+ setPreferences(options: SetEmailPreferencesOptions): Promise<SetEmailPreferencesResponse> {
148
+ return this.track(this.setPreferencesUntracked(options))
149
+ }
150
+
137
151
  private track<T>(pending: Promise<T>): Promise<T> {
138
152
  this.inFlight.add(pending)
139
153
  void pending.finally(() => this.inFlight.delete(pending))
@@ -141,7 +155,7 @@ export class EmailSender implements Emails {
141
155
  }
142
156
 
143
157
  /**
144
- * Resolves when every send and status read in flight, retries included, has settled.
158
+ * Resolves when every send, status read and preferences change in flight, retries included, has settled.
145
159
  * Kept apart from the client's pending-promise queue, so a send in its retry backoff does not hold back `flush()`.
146
160
  */
147
161
  async drain(): Promise<void> {
@@ -158,12 +172,16 @@ export class EmailSender implements Emails {
158
172
  'no email was sent',
159
173
  'Sending email needs secretKey, a project secret API key with the transactional_email:write scope.'
160
174
  )
175
+ const body =
176
+ prepared.react === undefined
177
+ ? prepared.body
178
+ : await withRenderedReact(prepared.body, prepared.react, this.config.requestTimeoutMs)
161
179
  const headers = this.headers(secretKey, {
162
180
  'Content-Type': 'application/json',
163
181
  'Idempotency-Key': prepared.idempotencyKey,
164
182
  })
165
183
  const result = await this.withRetries(prepared.maxRetries, async () =>
166
- parseSendReply(await this.request(appHost + prepared.path, 'POST', headers, prepared.body))
184
+ parseSendReply(await this.request(appHost + SEND_PATH, 'POST', headers, body))
167
185
  )
168
186
  for (const warning of result.warnings) {
169
187
  this.hooks.logger.warn(`PostHog email warning ${warning.code}: ${warning.message}`)
@@ -194,6 +212,23 @@ export class EmailSender implements Emails {
194
212
  }
195
213
  }
196
214
 
215
+ private async setPreferencesUntracked(options: SetEmailPreferencesOptions): Promise<SetEmailPreferencesResponse> {
216
+ try {
217
+ const body = preparePreferences(options)
218
+ const { appHost, secretKey } = this.connect(
219
+ 'no preferences changed',
220
+ 'Setting email preferences needs secretKey, a project secret API key with the messaging_preference:write scope.'
221
+ )
222
+ const headers = this.headers(secretKey, { 'Content-Type': 'application/json' })
223
+ const preferences = await this.withRetries(this.config.maxRetries, async () =>
224
+ parsePreferencesReply(await this.request(appHost + PREFERENCES_PATH, 'POST', headers, body))
225
+ )
226
+ return { data: preferences, error: null }
227
+ } catch (error) {
228
+ return { data: null, error: asEmailError(error, 'Setting the email preferences failed unexpectedly.') }
229
+ }
230
+ }
231
+
197
232
  private connect(nothingDone: string, missingSecretKey: string): { appHost: string; secretKey: string } {
198
233
  if (this.hooks.isDisabled()) {
199
234
  throw new EmailError({
@@ -357,13 +392,42 @@ function prepareSend(options: SendEmailOptions, defaultMaxRetries: number): Prep
357
392
  }
358
393
 
359
394
  return {
360
- path: SEND_PATH,
361
395
  body: safeJsonStringify({ ...content, to }),
396
+ react: isReactElement(send.react) ? send.react : undefined,
362
397
  idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
363
398
  maxRetries: isRetryCount(maxRetries) ? maxRetries : defaultMaxRetries,
364
399
  }
365
400
  }
366
401
 
402
+ function preparePreferences(options: SetEmailPreferencesOptions): string {
403
+ const fallback: Partial<SetEmailPreferencesOptions> = {}
404
+ const { to, allMarketing, topics } = options ?? fallback
405
+ if (typeof to !== 'string' || !to.trim()) {
406
+ throw invalid('invalid_recipient', 'to must be one email address as a nonempty string.', 'to')
407
+ }
408
+ if (allMarketing !== undefined && typeof allMarketing !== 'boolean') {
409
+ throw invalid('invalid_preferences', 'allMarketing must be true or false.', 'allMarketing')
410
+ }
411
+ if (
412
+ topics !== undefined &&
413
+ (typeof topics !== 'object' ||
414
+ topics === null ||
415
+ Array.isArray(topics) ||
416
+ !Object.values(topics).every((value) => typeof value === 'boolean'))
417
+ ) {
418
+ throw invalid('invalid_preferences', 'topics must map each topic key to true or false.', 'topics')
419
+ }
420
+ const hasTopics = topics !== undefined && Object.keys(topics).length > 0
421
+ if (allMarketing === undefined && !hasTopics) {
422
+ throw invalid('invalid_preferences', 'Set allMarketing, topics, or both.', 'topics')
423
+ }
424
+ return safeJsonStringify({
425
+ identifier: to,
426
+ ...(allMarketing === undefined ? {} : { all_marketing: allMarketing }),
427
+ ...(hasTopics ? { topics } : {}),
428
+ })
429
+ }
430
+
367
431
  function isRetryCount(value: unknown): value is number {
368
432
  return typeof value === 'number' && Number.isInteger(value) && value >= 0
369
433
  }
@@ -372,7 +436,7 @@ function contentOf(send: UncheckedSend, distinctId: string | undefined): Record<
372
436
  if ((send.templateId === undefined) === (send.templateKey === undefined)) {
373
437
  throw new EmailError({
374
438
  code: 'invalid_form',
375
- message: 'Send either templateId, or templateKey with subject and html or text.',
439
+ message: 'Send either templateId, or templateKey with subject and html, text or react.',
376
440
  })
377
441
  }
378
442
  return send.templateKey === undefined ? templateContent(send, distinctId) : codeContent(send, distinctId)
@@ -398,7 +462,7 @@ function templateContent(send: UncheckedSend, distinctId: string | undefined): R
398
462
  }
399
463
 
400
464
  function codeContent(send: UncheckedSend, distinctId: string | undefined): Record<string, unknown> {
401
- const { templateKey, subject, html, text, from, replyTo, captureEngagement } = send
465
+ const { templateKey, subject, html, text, react, from, replyTo, captureEngagement } = send
402
466
  if (typeof templateKey !== 'string' || !TEMPLATE_KEY_PATTERN.test(templateKey)) {
403
467
  throw invalid(
404
468
  'invalid_template_key',
@@ -416,8 +480,10 @@ function codeContent(send: UncheckedSend, distinctId: string | undefined): Recor
416
480
  if (text !== undefined && typeof text !== 'string') {
417
481
  throw invalid('invalid_form', 'text must be a string.', 'text')
418
482
  }
419
- if (html === undefined && text === undefined) {
420
- throw invalid('invalid_form', 'A send with templateKey needs html, text or both.', 'html')
483
+ if (react !== undefined) {
484
+ checkReactContent(react, html)
485
+ } else if (html === undefined && text === undefined) {
486
+ throw invalid('invalid_form', 'A send with templateKey needs html, text or react.', 'html')
421
487
  }
422
488
  const sendsReplyTo = replyTo !== undefined && !(Array.isArray(replyTo) && replyTo.length === 0)
423
489
  return {
@@ -432,6 +498,77 @@ function codeContent(send: UncheckedSend, distinctId: string | undefined): Recor
432
498
  }
433
499
  }
434
500
 
501
+ function checkReactContent(react: unknown, html: unknown): void {
502
+ if (!isReactElement(react)) {
503
+ throw invalid('invalid_form', 'react must be a React element, such as <WelcomeEmail />.', 'react')
504
+ }
505
+ if (html !== undefined) {
506
+ throw new EmailError({
507
+ code: 'invalid_form',
508
+ message: 'A send with react renders its own html, so it takes no html. No email was sent.',
509
+ field: 'html',
510
+ fix: 'Remove html to send the rendered react element, or remove react to send your html.',
511
+ })
512
+ }
513
+ }
514
+
515
+ const REACT_18_AND_19_ELEMENT_MARKERS: unknown[] = [
516
+ Symbol.for('react.element'),
517
+ Symbol.for('react.transitional.element'),
518
+ ]
519
+
520
+ function isReactElement(value: unknown): value is EmailReactElement {
521
+ return (
522
+ typeof value === 'object' &&
523
+ value !== null &&
524
+ '$$typeof' in value &&
525
+ REACT_18_AND_19_ELEMENT_MARKERS.includes(value.$$typeof) &&
526
+ 'type' in value &&
527
+ 'props' in value
528
+ )
529
+ }
530
+
531
+ async function withRenderedReact(body: string, react: EmailReactElement, timeoutMs: number): Promise<string> {
532
+ const { render, toPlainText } = await loadReactRenderer()
533
+ const fields: Record<string, unknown> = JSON.parse(body)
534
+ try {
535
+ const html = await settleWithin(render(react), timeoutMs, 'Rendering the react element')
536
+ return safeJsonStringify({ ...fields, html, ...(fields.text === undefined && { text: toPlainText(html) }) })
537
+ } catch (cause) {
538
+ throw new EmailError({
539
+ code: 'react_render_failed',
540
+ message: 'Rendering the react element failed, so no email was sent.',
541
+ cause,
542
+ })
543
+ }
544
+ }
545
+
546
+ async function settleWithin<T>(work: Promise<T>, timeoutMs: number, what: string): Promise<T> {
547
+ let timer: ReturnType<typeof setTimeout> | undefined
548
+ const deadline = new Promise<never>((_resolve, reject) => {
549
+ timer = setTimeout(() => reject(new Error(`${what} took longer than ${timeoutMs}ms.`)), timeoutMs)
550
+ })
551
+ try {
552
+ return await Promise.race([work, deadline])
553
+ } finally {
554
+ clearTimeout(timer)
555
+ }
556
+ }
557
+
558
+ async function loadReactRenderer(): Promise<ReactRenderer> {
559
+ try {
560
+ return await import('@react-email/render')
561
+ } catch (cause) {
562
+ throw new EmailError({
563
+ code: 'missing_react_renderer',
564
+ message:
565
+ "react needs the @react-email/render package, which isn't installed or failed to load, so no email was sent.",
566
+ fix: 'Install @react-email/render with react and react-dom next to posthog-node, or render the email yourself and send html.',
567
+ cause,
568
+ })
569
+ }
570
+ }
571
+
435
572
  function refuseFieldsOutside(send: UncheckedSend, form: SendForm, otherForm: SendForm): void {
436
573
  const field = Object.entries(send).find(([name, value]) => value !== undefined && !form.fields.has(name))?.[0]
437
574
  if (field === undefined) {
@@ -546,6 +683,31 @@ function parseStatusReply({ status, payload, retryAfterMs }: Reply): EmailStatus
546
683
  return { id, status: deliveryStatus, createdAt, statusAt, reason: text(fields.reason) ?? null }
547
684
  }
548
685
 
686
+ function parsePreferencesReply({ status, payload, retryAfterMs }: Reply): EmailPreferences {
687
+ const fields = replyFields(payload)
688
+ if (status < 200 || status >= 300) {
689
+ throw replyError(fields, status, retryAfterMs)
690
+ }
691
+ const to = text(fields.identifier)
692
+ const allMarketing = fields.all_marketing
693
+ const topics = fields.topics
694
+ if (
695
+ !to ||
696
+ !(allMarketing === null || typeof allMarketing === 'boolean') ||
697
+ topics === null ||
698
+ typeof topics !== 'object' ||
699
+ Array.isArray(topics) ||
700
+ !Object.values(topics).every((value) => typeof value === 'boolean')
701
+ ) {
702
+ throw new EmailError({
703
+ code: 'api_error',
704
+ message: 'PostHog answered without the preferences.',
705
+ statusCode: status,
706
+ })
707
+ }
708
+ return { to, allMarketing, topics: topics as Record<string, boolean> }
709
+ }
710
+
549
711
  function replyError(fields: Record<string, unknown>, status: number, retryAfterMs: number | undefined): EmailError {
550
712
  return new EmailError({
551
713
  code: text(fields.code) ?? 'api_error',
@@ -565,6 +727,7 @@ function asEmailError(error: unknown, message: string): EmailError {
565
727
 
566
728
  function isRetryable(error: EmailError): boolean {
567
729
  // A send carries an idempotency key, so a retry can't queue a second email. A status read changes nothing.
730
+ // A preferences change sets each named choice to a value, so repeating it ends the same.
568
731
  if (error.statusCode === undefined) {
569
732
  return error.code === 'network_error'
570
733
  }
@@ -26,7 +26,7 @@ export interface EmailErrorParams {
26
26
  }
27
27
 
28
28
  /**
29
- * PostHog did not queue the email, or the client could not tell whether it did.
29
+ * PostHog refused an email call, or the client could not tell whether it succeeded.
30
30
  *
31
31
  * Branch on `code`, PostHog's stable error code, or on `name`, a coarse category of the
32
32
  * failure. The message never contains the secret key or the request body.