posthog-node 5.40.0 → 5.42.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.
Files changed (50) hide show
  1. package/LICENSE +2 -2
  2. package/dist/capture-v1/config.d.ts +11 -0
  3. package/dist/capture-v1/config.d.ts.map +1 -0
  4. package/dist/capture-v1/config.js +42 -0
  5. package/dist/capture-v1/config.mjs +8 -0
  6. package/dist/capture-v1/errors.d.ts +32 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +49 -0
  9. package/dist/capture-v1/errors.mjs +15 -0
  10. package/dist/capture-v1/routing.d.ts +21 -0
  11. package/dist/capture-v1/routing.d.ts.map +1 -0
  12. package/dist/capture-v1/routing.js +47 -0
  13. package/dist/capture-v1/routing.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +70 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +222 -0
  17. package/dist/capture-v1/sender.mjs +188 -0
  18. package/dist/capture-v1/transform.d.ts +34 -0
  19. package/dist/capture-v1/transform.d.ts.map +1 -0
  20. package/dist/capture-v1/transform.js +142 -0
  21. package/dist/capture-v1/transform.mjs +99 -0
  22. package/dist/capture-v1/types.d.ts +50 -0
  23. package/dist/capture-v1/types.d.ts.map +1 -0
  24. package/dist/capture-v1/types.js +18 -0
  25. package/dist/capture-v1/types.mjs +0 -0
  26. package/dist/client.d.ts +22 -1
  27. package/dist/client.d.ts.map +1 -1
  28. package/dist/client.js +42 -0
  29. package/dist/client.mjs +43 -1
  30. package/dist/experimental.d.ts.map +1 -1
  31. package/dist/extensions/error-tracking/index.d.ts.map +1 -1
  32. package/dist/extensions/error-tracking/index.js +1 -2
  33. package/dist/extensions/error-tracking/index.mjs +2 -3
  34. package/dist/types.d.ts +2 -2
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/version.d.ts +1 -1
  37. package/dist/version.js +1 -1
  38. package/dist/version.mjs +1 -1
  39. package/package.json +2 -2
  40. package/src/capture-v1/config.ts +18 -0
  41. package/src/capture-v1/errors.ts +52 -0
  42. package/src/capture-v1/routing.ts +28 -0
  43. package/src/capture-v1/sender.ts +298 -0
  44. package/src/capture-v1/transform.ts +159 -0
  45. package/src/capture-v1/types.ts +55 -0
  46. package/src/client.ts +77 -1
  47. package/src/experimental.ts +0 -1
  48. package/src/extensions/error-tracking/index.ts +12 -6
  49. package/src/types.ts +2 -1
  50. package/src/version.ts +1 -1
@@ -0,0 +1,298 @@
1
+ import {
2
+ type FetchLike,
3
+ type PostHogEventProperties,
4
+ type PostHogFetchOptions,
5
+ type PostHogFetchResponse,
6
+ gzipCompress,
7
+ safeJsonStringify,
8
+ safeSetTimeout,
9
+ uuidv7,
10
+ } from '@posthog/core'
11
+
12
+ import { CaptureV1Error, type V1DroppedEvent } from './errors'
13
+ import { buildV1Batch } from './transform'
14
+ import type { V1BatchResponse, V1Event } from './types'
15
+
16
+ const V1_ANALYTICS_PATH = '/i/v1/analytics/events'
17
+ const DEFAULT_MAX_BACKOFF_MS = 30_000
18
+
19
+ /** HTTP statuses the v1 backend wants retried. 429 is intentionally terminal in v1. */
20
+ const RETRYABLE_STATUSES = new Set([408, 500, 502, 503, 504])
21
+
22
+ export interface V1CaptureSenderConfig {
23
+ host: string
24
+ apiKey: string
25
+ /** Canonical `$lib` identity, materialized by the server from `PostHog-Sdk-Info`. */
26
+ libraryId: string
27
+ libraryVersion: string
28
+ /** Value for the `User-Agent` header, if the runtime allows setting it. */
29
+ userAgent?: string
30
+ historicalMigration: boolean
31
+ /** When true, the body is gzip-compressed (falling back to uncompressed on failure). */
32
+ compressionEnabled: boolean
33
+ requestTimeoutMs: number
34
+ /** Total attempts, including the first (1 initial + N retries). */
35
+ maxAttempts: number
36
+ /** Base exponential backoff, doubled each retry and capped at `maxBackoffMs`. */
37
+ initialRetryDelayMs: number
38
+ /** Single ceiling for both the backoff schedule and the `Retry-After` clamp. */
39
+ maxBackoffMs?: number
40
+ isDebug?: boolean
41
+ }
42
+
43
+ export interface V1CaptureSenderHooks {
44
+ fetch: FetchLike
45
+ /** Surfaces partial/terminal delivery failures on the client error channel. */
46
+ onError: (error: Error) => void
47
+ now?: () => number
48
+ sleep?: (ms: number) => Promise<void>
49
+ generateRequestId?: () => string
50
+ compress?: (payload: string, isDebug?: boolean) => Promise<Blob | null>
51
+ }
52
+
53
+ /**
54
+ * Sends already-normalized events to the Capture V1 endpoint
55
+ * (`POST /i/v1/analytics/events`), owning the full attempt loop: per-event
56
+ * partial retry, exponential backoff clamped against `Retry-After`, v1 status
57
+ * classification, and surfacing drops / undelivered events on the error
58
+ * channel. Used by both the batched and immediate send paths.
59
+ *
60
+ * Never throws for a handled outcome: after exhausting its own attempt budget it
61
+ * reports the failure via `onError` and resolves, so the caller's queue treats
62
+ * the batch as consumed (the internal budget replaces v0's queue-level retry).
63
+ */
64
+ export class V1CaptureSender {
65
+ private readonly config: V1CaptureSenderConfig
66
+ private readonly maxBackoffMs: number
67
+ private readonly fetchFn: FetchLike
68
+ private readonly onError: (error: Error) => void
69
+ private readonly now: () => number
70
+ private readonly sleep: (ms: number) => Promise<void>
71
+ private readonly generateRequestId: () => string
72
+ private readonly compress: (payload: string, isDebug?: boolean) => Promise<Blob | null>
73
+
74
+ constructor(config: V1CaptureSenderConfig, hooks: V1CaptureSenderHooks) {
75
+ this.config = config
76
+ this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS
77
+ this.fetchFn = hooks.fetch
78
+ this.onError = hooks.onError
79
+ this.now = hooks.now ?? Date.now
80
+ this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve) => safeSetTimeout(resolve, ms)))
81
+ this.generateRequestId = hooks.generateRequestId ?? uuidv7
82
+ this.compress = hooks.compress ?? gzipCompress
83
+ }
84
+
85
+ async sendV1Batch(messages: PostHogEventProperties[]): Promise<void> {
86
+ if (messages.length === 0) {
87
+ return
88
+ }
89
+
90
+ const requestId = this.generateRequestId()
91
+ // created_at is generated once and stays stable across every retry.
92
+ const createdAt = new Date(this.now()).toISOString()
93
+ const { batch } = buildV1Batch(messages, {
94
+ createdAt,
95
+ historicalMigration: this.config.historicalMigration,
96
+ })
97
+
98
+ const url = `${this.config.host}${V1_ANALYTICS_PATH}`
99
+ const drops: V1DroppedEvent[] = []
100
+ let pending = batch
101
+
102
+ // Guard against a misconfigured budget (e.g. fetchRetryCount: -1): always make
103
+ // at least one attempt so a bad config surfaces a delivery error instead of
104
+ // silently dropping the batch without ever sending or calling onError.
105
+ const maxAttempts = Math.max(1, this.config.maxAttempts)
106
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
107
+ const isLastAttempt = attempt === maxAttempts
108
+ const payload = safeJsonStringify({
109
+ created_at: createdAt,
110
+ ...(this.config.historicalMigration ? { historical_migration: true } : {}),
111
+ batch: pending,
112
+ })
113
+
114
+ let response: PostHogFetchResponse
115
+ try {
116
+ response = await this.sendOnce(url, payload, attempt, requestId)
117
+ } catch (transportError) {
118
+ // Connection/timeout with no HTTP response: retry until the budget runs out.
119
+ if (isLastAttempt) {
120
+ return this.surfaceBatchFailure(requestId, drops, pending, transportError)
121
+ }
122
+ await this.sleep(this.backoffDelay(attempt))
123
+ continue
124
+ }
125
+
126
+ const { status } = response
127
+ if (status < 200 || status >= 300) {
128
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
129
+ const retryAfterMs = this.parseRetryAfter(response)
130
+ await this.cancelBody(response)
131
+ await this.sleep(this.backoffDelay(attempt, retryAfterMs))
132
+ continue
133
+ }
134
+ const httpError = await this.buildHttpError(response, status)
135
+ return this.surfaceBatchFailure(requestId, drops, pending, httpError)
136
+ }
137
+
138
+ let parsed: V1BatchResponse
139
+ try {
140
+ parsed = await this.parseResponse(response)
141
+ } catch {
142
+ // A 2xx we cannot parse is terminal — re-sending against a broken success would loop forever.
143
+ return this.surfaceBatchFailure(
144
+ requestId,
145
+ drops,
146
+ pending,
147
+ new Error(`Capture V1 returned an unparseable ${status} response body`)
148
+ )
149
+ }
150
+
151
+ const retryable = this.classify(pending, parsed, drops)
152
+ if (retryable.length === 0) {
153
+ return this.surfacePartialDrops(requestId, drops)
154
+ }
155
+ if (isLastAttempt) {
156
+ this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: retryable.map((event) => event.uuid) }))
157
+ return
158
+ }
159
+ pending = retryable
160
+ // A 200 partial-retry body can also carry Retry-After (e.g. rate-limited
161
+ // retry events); honor it as a minimum the same way as on a retryable status.
162
+ const retryAfterMs = this.parseRetryAfter(response)
163
+ await this.sleep(this.backoffDelay(attempt, retryAfterMs))
164
+ }
165
+ }
166
+
167
+ private async sendOnce(
168
+ url: string,
169
+ payload: string,
170
+ attempt: number,
171
+ requestId: string
172
+ ): Promise<PostHogFetchResponse> {
173
+ const headers = this.buildHeaders(attempt, requestId)
174
+ let body: string | Blob = payload
175
+ if (this.config.compressionEnabled) {
176
+ const compressed = await this.compress(payload, this.config.isDebug)
177
+ if (compressed !== null) {
178
+ body = compressed
179
+ headers['Content-Encoding'] = 'gzip'
180
+ }
181
+ // A codec that fails to compress falls back to sending uncompressed.
182
+ }
183
+
184
+ const controller = new AbortController()
185
+ const timer = safeSetTimeout(() => controller.abort(), this.config.requestTimeoutMs)
186
+ try {
187
+ return await this.fetchFn(url, { method: 'POST', headers, body, signal: controller.signal })
188
+ } finally {
189
+ clearTimeout(timer)
190
+ }
191
+ }
192
+
193
+ private buildHeaders(attempt: number, requestId: string): PostHogFetchOptions['headers'] {
194
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`
195
+ const headers: { [key: string]: string } = {
196
+ 'Content-Type': 'application/json',
197
+ Authorization: `Bearer ${this.config.apiKey}`,
198
+ 'PostHog-Sdk-Info': sdkInfo,
199
+ 'PostHog-Attempt': String(attempt),
200
+ 'PostHog-Request-Id': requestId,
201
+ // Regenerated per attempt — a per-attempt wall-clock stamp, unlike Request-Id / created_at.
202
+ 'PostHog-Request-Timestamp': new Date(this.now()).toISOString(),
203
+ }
204
+ if (this.config.userAgent) {
205
+ headers['User-Agent'] = this.config.userAgent
206
+ }
207
+ return headers
208
+ }
209
+
210
+ /**
211
+ * Partition the pending events against a 2xx result map: `drop` accumulates as
212
+ * a terminal failure, `retry` is returned for the next attempt, and
213
+ * `ok`/`warning`/unknown/absent are terminal successes.
214
+ */
215
+ private classify(pending: V1Event[], parsed: V1BatchResponse, drops: V1DroppedEvent[]): V1Event[] {
216
+ const results = parsed.results ?? {}
217
+ const retryable: V1Event[] = []
218
+ for (const event of pending) {
219
+ const result = results[event.uuid]
220
+ if (!result) {
221
+ continue
222
+ }
223
+ if (result.result === 'drop') {
224
+ drops.push({ uuid: event.uuid, details: result.details ?? undefined })
225
+ } else if (result.result === 'retry') {
226
+ retryable.push(event)
227
+ }
228
+ // ok / warning / unknown codes are terminal successes.
229
+ }
230
+ return retryable
231
+ }
232
+
233
+ private backoffDelay(attempt: number, retryAfterMs?: number): number {
234
+ const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs)
235
+ if (retryAfterMs === undefined) {
236
+ return exponential
237
+ }
238
+ // Retry-After is a minimum (never lets us retry earlier than our own backoff) and is clamped to the ceiling.
239
+ return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs))
240
+ }
241
+
242
+ /** Parse `Retry-After` (delta-seconds or HTTP-date). Non-positive/past values are ignored. */
243
+ private parseRetryAfter(response: PostHogFetchResponse): number | undefined {
244
+ const raw = response.headers?.get('Retry-After')
245
+ if (!raw) {
246
+ return undefined
247
+ }
248
+ const trimmed = raw.trim()
249
+ if (/^\d+$/.test(trimmed)) {
250
+ const seconds = parseInt(trimmed, 10)
251
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined
252
+ }
253
+ const dateMs = Date.parse(trimmed)
254
+ if (Number.isNaN(dateMs)) {
255
+ return undefined
256
+ }
257
+ const delta = dateMs - this.now()
258
+ return delta > 0 ? delta : undefined
259
+ }
260
+
261
+ private async parseResponse(response: PostHogFetchResponse): Promise<V1BatchResponse> {
262
+ const text = await response.text()
263
+ const parsed = JSON.parse(text)
264
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
265
+ throw new Error('unexpected response shape')
266
+ }
267
+ const results = (parsed as { results?: unknown }).results
268
+ if (results !== undefined && (typeof results !== 'object' || results === null || Array.isArray(results))) {
269
+ throw new Error('unexpected results shape')
270
+ }
271
+ return { results: (results as V1BatchResponse['results']) ?? {} }
272
+ }
273
+
274
+ private async buildHttpError(response: PostHogFetchResponse, status: number): Promise<Error> {
275
+ let bodyText = ''
276
+ try {
277
+ bodyText = (await response.text()).slice(0, 512)
278
+ } catch {
279
+ // best-effort; a missing body should not mask the status
280
+ }
281
+ const suffix = bodyText ? `: ${bodyText}` : ''
282
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`)
283
+ }
284
+
285
+ private surfaceBatchFailure(requestId: string, drops: V1DroppedEvent[], pending: V1Event[], cause: unknown): void {
286
+ this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: pending.map((event) => event.uuid), cause }))
287
+ }
288
+
289
+ private surfacePartialDrops(requestId: string, drops: V1DroppedEvent[]): void {
290
+ if (drops.length > 0) {
291
+ this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: [] }))
292
+ }
293
+ }
294
+
295
+ private async cancelBody(response: PostHogFetchResponse): Promise<void> {
296
+ await response.body?.cancel()?.catch(() => {})
297
+ }
298
+ }
@@ -0,0 +1,159 @@
1
+ import type { JsonType, PostHogEventProperties } from '@posthog/core'
2
+
3
+ import type { V1Batch, V1Event, V1EventOptions } from './types'
4
+
5
+ /**
6
+ * Coerce a value to a boolean the way the capture server does, or return
7
+ * `undefined` if it cannot be coerced (the option is then omitted so the server
8
+ * falls back to its default). Accepts native booleans, the strings
9
+ * `"true"`/`"1"`/`"false"`/`"0"` (trimmed, case-insensitive), and any number
10
+ * (nonzero -> true).
11
+ */
12
+ export function coerceBool(value: JsonType): boolean | undefined {
13
+ if (typeof value === 'boolean') {
14
+ return value
15
+ }
16
+ if (typeof value === 'number') {
17
+ return value !== 0
18
+ }
19
+ if (typeof value === 'string') {
20
+ const normalized = value.trim().toLowerCase()
21
+ if (normalized === 'true' || normalized === '1') {
22
+ return true
23
+ }
24
+ if (normalized === 'false' || normalized === '0') {
25
+ return false
26
+ }
27
+ }
28
+ return undefined
29
+ }
30
+
31
+ /**
32
+ * Accept only a native string, else return `undefined` (the option is then
33
+ * omitted). The backend's `product_tour_id` is `Option<String>`, so numbers,
34
+ * booleans, objects, and arrays are dropped rather than coerced — matching
35
+ * posthog-go, posthog-rs, and posthog-python exactly.
36
+ */
37
+ export function coerceString(value: JsonType): string | undefined {
38
+ return typeof value === 'string' ? value : undefined
39
+ }
40
+
41
+ /** Legacy sentinel property -> typed `options` field, with its coercion. */
42
+ const OPTION_SENTINELS: ReadonlyArray<{
43
+ property: string
44
+ optionKey: keyof V1EventOptions
45
+ coerce: (value: JsonType) => boolean | string | undefined
46
+ }> = [
47
+ { property: '$cookieless_mode', optionKey: 'cookieless_mode', coerce: coerceBool },
48
+ { property: '$ignore_sent_at', optionKey: 'disable_skew_correction', coerce: coerceBool },
49
+ { property: '$process_person_profile', optionKey: 'process_person_profile', coerce: coerceBool },
50
+ { property: '$product_tour_id', optionKey: 'product_tour_id', coerce: coerceString },
51
+ ]
52
+
53
+ /** Sentinel property -> top-level string field (string-only, non-string dropped). */
54
+ const TOPLEVEL_SENTINELS: ReadonlyArray<{ property: string; field: 'session_id' | 'window_id' }> = [
55
+ { property: '$session_id', field: 'session_id' },
56
+ { property: '$window_id', field: 'window_id' },
57
+ ]
58
+
59
+ function isRecord(value: JsonType | undefined): value is PostHogEventProperties {
60
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
61
+ }
62
+
63
+ /**
64
+ * Normalize an event timestamp to an RFC 3339 string. The queued message
65
+ * carries either an ISO string (from `currentISOTime()`) or a `Date` (when the
66
+ * caller passed one); numbers are treated as epoch milliseconds. Invalid values
67
+ * fall back to "now" so a bad timestamp never rejects the whole batch.
68
+ */
69
+ function toRfc3339(timestamp: unknown): string {
70
+ if (typeof timestamp === 'string') {
71
+ const asDate = new Date(timestamp)
72
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : timestamp
73
+ }
74
+ if (timestamp instanceof Date) {
75
+ return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString()
76
+ }
77
+ const asDate = timestamp == null ? new Date() : new Date(timestamp as string | number)
78
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString()
79
+ }
80
+
81
+ /**
82
+ * Relocate a top-level `$set`/`$set_once` value into `properties`. v1 has no
83
+ * top-level form; the server reads them from inside `properties`. An existing
84
+ * `properties` value wins on collision.
85
+ */
86
+ function relocateInto(properties: PostHogEventProperties, key: string, value: JsonType | undefined): void {
87
+ if (value !== undefined && !(key in properties)) {
88
+ properties[key] = value
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Transform one already-normalized queued message into a Capture V1 wire event.
94
+ *
95
+ * The input message is never mutated (events may be retried or handed to
96
+ * callbacks): a fresh `properties` map is built. Sentinel properties are lifted
97
+ * out of `properties` (deleting the copy) into the typed `options` object and
98
+ * the top-level `session_id`/`window_id` fields; `$lib`/`$lib_version` are
99
+ * stripped (the server injects them from `PostHog-Sdk-Info`); top-level
100
+ * `$set`/`$set_once` are relocated into `properties`.
101
+ */
102
+ export function buildV1Event(message: PostHogEventProperties): V1Event {
103
+ const sourceProperties = isRecord(message.properties) ? message.properties : {}
104
+ const properties: PostHogEventProperties = { ...sourceProperties }
105
+
106
+ const options: V1EventOptions = {}
107
+ for (const { property, optionKey, coerce } of OPTION_SENTINELS) {
108
+ if (property in properties) {
109
+ const coerced = coerce(properties[property])
110
+ if (coerced !== undefined) {
111
+ ;(options as Record<string, boolean | string>)[optionKey] = coerced
112
+ }
113
+ // Always strip the sentinel, even when coercion omits the option.
114
+ delete properties[property]
115
+ }
116
+ }
117
+
118
+ const topLevel: { session_id?: string; window_id?: string } = {}
119
+ for (const { property, field } of TOPLEVEL_SENTINELS) {
120
+ if (property in properties) {
121
+ const value = properties[property]
122
+ if (typeof value === 'string') {
123
+ topLevel[field] = value
124
+ }
125
+ delete properties[property]
126
+ }
127
+ }
128
+
129
+ delete properties.$lib
130
+ delete properties.$lib_version
131
+
132
+ relocateInto(properties, '$set', message.$set)
133
+ relocateInto(properties, '$set_once', message.$set_once)
134
+
135
+ return {
136
+ event: String(message.event ?? ''),
137
+ uuid: String(message.uuid ?? ''),
138
+ distinct_id: String(message.distinct_id ?? ''),
139
+ timestamp: toRfc3339(message.timestamp),
140
+ ...topLevel,
141
+ options,
142
+ properties,
143
+ }
144
+ }
145
+
146
+ /** Build a Capture V1 batch envelope from already-normalized queued messages. */
147
+ export function buildV1Batch(
148
+ messages: PostHogEventProperties[],
149
+ { createdAt, historicalMigration }: { createdAt: string; historicalMigration?: boolean }
150
+ ): V1Batch {
151
+ const batch: V1Batch = {
152
+ created_at: createdAt,
153
+ batch: messages.map(buildV1Event),
154
+ }
155
+ if (historicalMigration) {
156
+ batch.historical_migration = true
157
+ }
158
+ return batch
159
+ }
@@ -0,0 +1,55 @@
1
+ import type { PostHogEventProperties } from '@posthog/core'
2
+
3
+ /**
4
+ * Typed `options` object on a Capture V1 event. Legacy `$`-prefixed sentinel
5
+ * properties are lifted here (renamed + strictly typed) by the transform.
6
+ * Always serialized as an object (`{}` when empty), never `null`.
7
+ */
8
+ export interface V1EventOptions {
9
+ cookieless_mode?: boolean
10
+ disable_skew_correction?: boolean
11
+ process_person_profile?: boolean
12
+ product_tour_id?: string
13
+ }
14
+
15
+ /**
16
+ * A single event in a Capture V1 batch (`POST /i/v1/analytics/events`).
17
+ * `session_id`/`window_id` are promoted from the `$session_id`/`$window_id`
18
+ * sentinels; there is no top-level `api_key`.
19
+ */
20
+ export interface V1Event {
21
+ event: string
22
+ uuid: string
23
+ distinct_id: string
24
+ timestamp: string
25
+ session_id?: string
26
+ window_id?: string
27
+ options: V1EventOptions
28
+ properties: PostHogEventProperties
29
+ }
30
+
31
+ /**
32
+ * The Capture V1 batch envelope. Unlike v0 there is no `api_key` (Bearer auth)
33
+ * and no `sent_at`. `historical_migration` is omitted when false.
34
+ */
35
+ export interface V1Batch {
36
+ created_at: string
37
+ historical_migration?: boolean
38
+ batch: V1Event[]
39
+ }
40
+
41
+ /**
42
+ * Per-event result codes in a v1 2xx response body. Unknown strings are
43
+ * tolerated as terminal success for forward compatibility.
44
+ */
45
+ export type V1ResultCode = 'ok' | 'warning' | 'drop' | 'retry'
46
+
47
+ export interface V1EventResult {
48
+ result: V1ResultCode | string
49
+ details?: string | null
50
+ }
51
+
52
+ /** Shape of a v1 2xx response body: a per-uuid map of results. */
53
+ export interface V1BatchResponse {
54
+ results: Record<string, V1EventResult>
55
+ }
package/src/client.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  PostHogFlagsAndPayloadsResponse,
14
14
  PostHogFlagsResponse,
15
15
  PostHogPersistedProperty,
16
+ RetriableOptions,
16
17
  safeSetTimeout,
17
18
  uuidv7,
18
19
  } from '@posthog/core'
@@ -48,6 +49,9 @@ import {
48
49
  import ErrorTracking from './extensions/error-tracking'
49
50
  import { PostHogMemoryStorage } from './storage-memory'
50
51
  import { ContextData, ContextOptions, IPostHogContext } from './extensions/context/types'
52
+ import { type CaptureMode, resolveCaptureMode } from './capture-v1/config'
53
+ import { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from './capture-v1/routing'
54
+ import { V1CaptureSender } from './capture-v1/sender'
51
55
 
52
56
  // Standard local evaluation rate limit is 600 per minute (10 per second),
53
57
  // so the fastest a poller should ever be set is 100ms.
@@ -68,7 +72,6 @@ function emitDeprecationWarningOnce(id: string, message: string): void {
68
72
  return
69
73
  }
70
74
  _emittedDeprecations.add(id)
71
- // eslint-disable-next-line no-console
72
75
  console.warn(`[PostHog] ${message}`)
73
76
  }
74
77
 
@@ -131,6 +134,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
131
134
  public readonly options: PostHogOptions
132
135
  protected readonly context?: IPostHogContext
133
136
 
137
+ private readonly captureMode: CaptureMode
138
+ private _v1Sender?: V1CaptureSender
139
+
134
140
  // Feature flag overrides for local testing/development
135
141
  private _flagOverrides?: Record<string, FeatureFlagValue>
136
142
  private _payloadOverrides?: Record<string, JsonType>
@@ -184,6 +190,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
184
190
  super(normalizedApiKey, normalizedOptions)
185
191
 
186
192
  this.options = normalizedOptions
193
+ this.captureMode = resolveCaptureMode()
187
194
  this.context = this.initializeContext()
188
195
 
189
196
  this.options.featureFlagsPollingInterval =
@@ -394,6 +401,75 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
394
401
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options)
395
402
  }
396
403
 
404
+ /**
405
+ * Route an event to its queue. In v1 mode `$ai_*` events go to the isolated {@link AI_ROUTE}
406
+ * (legacy transport) and everything else to {@link ANALYTICS_ROUTE} (Capture V1); in v0 mode
407
+ * every event stays on {@link ANALYTICS_ROUTE}, which maps to the historical queue. Routing runs
408
+ * on the post-`before_send`, normalized event name (core calls this after `processBeforeEnqueue`).
409
+ */
410
+ protected getQueueRouteKey(message: PostHogEventProperties): string {
411
+ return this.captureMode === 'v1' && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE
412
+ }
413
+
414
+ protected persistedQueueKeyForRoute(route: string): PostHogPersistedProperty {
415
+ return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue
416
+ }
417
+
418
+ protected getActiveQueueRoutes(): string[] {
419
+ // Only surface the AI route in v1 mode — v0 mode never enqueues onto it, so keeping it out
420
+ // keeps v0's flush/shutdown identical to before (a single queue on ANALYTICS_ROUTE).
421
+ return this.captureMode === 'v1' ? [ANALYTICS_ROUTE, AI_ROUTE] : [ANALYTICS_ROUTE]
422
+ }
423
+
424
+ /**
425
+ * Capture submission seam shared by the batched (`_flush`) and immediate (`sendImmediate`)
426
+ * paths. Events are routed to homogeneous per-route queues at enqueue time, so a batch here is
427
+ * never mixed: the {@link AI_ROUTE} (and all of v0 mode) uses the legacy `/batch/` transport,
428
+ * which throws so `_flush` can shrink/persist/retry its own queue; the {@link ANALYTICS_ROUTE}
429
+ * in v1 mode uses the Capture V1 endpoint. Because the routes flush independently, a v0/AI leg
430
+ * failure can never re-send analytics events already accepted on the V1 leg.
431
+ */
432
+ protected async sendBatch(
433
+ batchMessages: (PostHogEventProperties | undefined)[],
434
+ retryOptions?: Partial<RetriableOptions>,
435
+ route: string = ANALYTICS_ROUTE
436
+ ): Promise<void> {
437
+ if (this.captureMode !== 'v1' || route === AI_ROUTE) {
438
+ return super.sendBatch(batchMessages, retryOptions, route)
439
+ }
440
+
441
+ // Analytics route in v1 mode: homogeneous (no `$ai_*`, routed away at enqueue) and never
442
+ // undefined for a freshly-enqueued event; drop any legacy undefined queue artifacts.
443
+ const v1Events = batchMessages.filter((message): message is PostHogEventProperties => message !== undefined)
444
+ await this.getV1Sender().sendV1Batch(v1Events)
445
+ }
446
+
447
+ private getV1Sender(): V1CaptureSender {
448
+ if (!this._v1Sender) {
449
+ this._v1Sender = new V1CaptureSender(
450
+ {
451
+ host: this.host,
452
+ apiKey: this.apiKey,
453
+ libraryId: this.getLibraryId(),
454
+ libraryVersion: this.getLibraryVersion(),
455
+ userAgent: this.getCustomUserAgent() || undefined,
456
+ historicalMigration: this.historicalMigration,
457
+ compressionEnabled: !this.disableCompression,
458
+ requestTimeoutMs: this.requestTimeout,
459
+ // Reuse the existing v0 retry knobs: 1 initial attempt + fetchRetryCount retries.
460
+ maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
461
+ initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
462
+ isDebug: this.isDebug,
463
+ },
464
+ {
465
+ fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
466
+ onError: (error) => this._events.emit('error', error),
467
+ }
468
+ )
469
+ }
470
+ return this._v1Sender
471
+ }
472
+
397
473
  /**
398
474
  * Get the library version from package.json.
399
475
  *
@@ -8,7 +8,6 @@
8
8
  const postHogNodeExperimentalDeprecationWarning =
9
9
  "[PostHog] `posthog-node/experimental` is deprecated. Use `import type { FlagDefinitionCacheData, FlagDefinitionCacheProvider } from 'posthog-node'` instead."
10
10
 
11
- // eslint-disable-next-line no-console
12
11
  console.warn(postHogNodeExperimentalDeprecationWarning)
13
12
 
14
13
  export type { FlagDefinitionCacheProvider, FlagDefinitionCacheData } from './extensions/feature-flags/cache'
@@ -3,7 +3,7 @@ import { PostHogBackendClient } from '@/client'
3
3
  import { isObject } from '@posthog/core'
4
4
  import { EventMessage, PostHogOptions } from '@/types'
5
5
  import type { Logger } from '@posthog/core'
6
- import { BucketedRateLimiter } from '@posthog/core'
6
+ import { BucketedRateLimiter, resolveExceptionRateLimiterConfig } from '@posthog/core'
7
7
  import { ErrorTracking as CoreErrorTracking } from '@posthog/core'
8
8
 
9
9
  const SHUTDOWN_TIMEOUT = 2000
@@ -19,12 +19,18 @@ export default class ErrorTracking {
19
19
  this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false
20
20
  this._logger = _logger
21
21
 
22
- // by default captures ten exceptions before rate limiting by exception type
23
- // refills at a rate of one token / 10 second period
24
- // e.g. will capture 1 exception rate limited exception every 10 seconds until burst ends
22
+ // Burst protection is scoped PER EXCEPTION TYPE: the rate limiter is keyed by exception type
23
+ // (see `consumeRateLimit(exceptionType)` below), so each distinct type gets its own fresh
24
+ // token bucket. There is no aggregate cap across all types — a burst made up of many distinct
25
+ // types is not throttled in total, only per individual type.
26
+ //
27
+ // By default each exception type captures ten exceptions before being rate limited, then
28
+ // refills at a rate of one token / 10 second period (e.g. captures 1 rate-limited exception of
29
+ // that type every 10 seconds until the burst ends). The bucket size and refill rate can be
30
+ // tuned via the `exceptionRateLimiterBucketSize` and `exceptionRateLimiterRefillRate`
31
+ // options.
25
32
  this._rateLimiter = new BucketedRateLimiter({
26
- refillRate: 1,
27
- bucketSize: 10,
33
+ ...resolveExceptionRateLimiterConfig(options),
28
34
  refillInterval: 10000, // ten seconds in milliseconds
29
35
  _logger: this._logger,
30
36
  })
package/src/types.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type {
2
2
  PostHogCoreOptions,
3
+ ExceptionRateLimiterConfig,
3
4
  FeatureFlagValue,
4
5
  JsonType,
5
6
  PostHogFetchOptions,
@@ -309,7 +310,7 @@ export type PostHogOptions = Omit<PostHogCoreOptions, 'before_send'> & {
309
310
  * new PostHog('key', { isServer: false })
310
311
  */
311
312
  isServer?: boolean
312
- }
313
+ } & ExceptionRateLimiterConfig
313
314
 
314
315
  export type PostHogFeatureFlag = {
315
316
  id: number