posthog-node 6.4.1 → 6.4.2

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 (67) hide show
  1. package/dist/capture-lane/lane.d.ts +4 -4
  2. package/dist/capture-lane/lane.d.ts.map +1 -1
  3. package/dist/capture-lane/lane.js +8 -9
  4. package/dist/capture-lane/lane.mjs +1 -2
  5. package/dist/capture-lane/settings.d.ts +1 -1
  6. package/dist/capture-lane/settings.d.ts.map +1 -1
  7. package/dist/capture-lane/settings.js +3 -3
  8. package/dist/capture-lane/settings.mjs +1 -1
  9. package/dist/client.d.ts +1 -1
  10. package/dist/client.js +16 -20
  11. package/dist/client.mjs +2 -6
  12. package/dist/compression.node.d.ts +1 -1
  13. package/dist/entrypoints/index.node.d.ts +1 -1
  14. package/dist/entrypoints/index.node.d.ts.map +1 -1
  15. package/dist/exports.d.ts +3 -3
  16. package/dist/exports.d.ts.map +1 -1
  17. package/dist/exports.js +5 -5
  18. package/dist/exports.mjs +1 -1
  19. package/dist/types.d.ts +1 -1
  20. package/dist/types.d.ts.map +1 -1
  21. package/dist/version.d.ts +1 -1
  22. package/dist/version.js +1 -1
  23. package/dist/version.mjs +1 -1
  24. package/package.json +4 -4
  25. package/src/capture-lane/lane.ts +4 -4
  26. package/src/capture-lane/settings.ts +1 -1
  27. package/src/client.ts +7 -7
  28. package/src/compression.node.ts +1 -1
  29. package/src/entrypoints/index.node.ts +1 -1
  30. package/src/exports.ts +3 -3
  31. package/src/types.ts +1 -1
  32. package/src/version.ts +1 -1
  33. package/dist/capture-v1/compression.d.ts +0 -18
  34. package/dist/capture-v1/compression.d.ts.map +0 -1
  35. package/dist/capture-v1/compression.js +0 -70
  36. package/dist/capture-v1/compression.mjs +0 -26
  37. package/dist/capture-v1/errors.d.ts +0 -48
  38. package/dist/capture-v1/errors.d.ts.map +0 -1
  39. package/dist/capture-v1/errors.js +0 -82
  40. package/dist/capture-v1/errors.mjs +0 -38
  41. package/dist/capture-v1/sender.d.ts +0 -110
  42. package/dist/capture-v1/sender.d.ts.map +0 -1
  43. package/dist/capture-v1/sender.js +0 -481
  44. package/dist/capture-v1/sender.mjs +0 -434
  45. package/dist/capture-v1/serialize.d.ts +0 -28
  46. package/dist/capture-v1/serialize.d.ts.map +0 -1
  47. package/dist/capture-v1/serialize.js +0 -82
  48. package/dist/capture-v1/serialize.mjs +0 -38
  49. package/dist/capture-v1/transform.d.ts +0 -19
  50. package/dist/capture-v1/transform.d.ts.map +0 -1
  51. package/dist/capture-v1/transform.js +0 -118
  52. package/dist/capture-v1/transform.mjs +0 -77
  53. package/dist/capture-v1/types.d.ts +0 -52
  54. package/dist/capture-v1/types.d.ts.map +0 -1
  55. package/dist/capture-v1/types.js +0 -44
  56. package/dist/capture-v1/types.mjs +0 -3
  57. package/dist/capture-v1/uuid.d.ts +0 -9
  58. package/dist/capture-v1/uuid.d.ts.map +0 -1
  59. package/dist/capture-v1/uuid.js +0 -75
  60. package/dist/capture-v1/uuid.mjs +0 -34
  61. package/src/capture-v1/compression.ts +0 -50
  62. package/src/capture-v1/errors.ts +0 -91
  63. package/src/capture-v1/sender.ts +0 -668
  64. package/src/capture-v1/serialize.ts +0 -77
  65. package/src/capture-v1/transform.ts +0 -134
  66. package/src/capture-v1/types.ts +0 -59
  67. package/src/capture-v1/uuid.ts +0 -53
@@ -1,668 +0,0 @@
1
- import { type FetchLike, type PostHogFetchOptions, type PostHogFetchResponse, uuidv7 } from '@posthog/core'
2
-
3
- import { type CaptureCodec, type CaptureCompression, webCompressor } from './compression'
4
- import {
5
- CaptureError,
6
- CaptureLossTally,
7
- type CaptureDroppedEvent,
8
- type CaptureErrorParams,
9
- describeCaptureLoss,
10
- } from './errors'
11
- import { type SerializedV1Event, buildV1Body } from './serialize'
12
- import type { CaptureEndpoint, V1BatchResponse, V1EventResult } from './types'
13
- import { canonicalizeUuid } from './uuid'
14
-
15
- /** Wait before the first retry; each later retry doubles it. */
16
- export const RETRY_BASE_DELAY_MS = 100
17
- /** Ceiling for every retry wait, including one raised by `Retry-After`. */
18
- export const MAX_RETRY_DELAY_MS = 30_000
19
-
20
- // Retry waits and request deadlines use ref'd timers, unlike safeSetTimeout, so an
21
- // awaited flush or shutdown keeps the process alive until the send finishes.
22
- /** Settles with `work`, or rejects with an `AbortError` as soon as `signal` aborts. */
23
- async function raceAbort<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
24
- if (!signal) {
25
- return work
26
- }
27
- let onAbort!: () => void
28
- const aborted = new Promise<never>((_resolve, reject) => {
29
- onAbort = () => {
30
- const abortError = new Error('Capture V1 request aborted while compressing the body')
31
- abortError.name = 'AbortError'
32
- abortError.cause = signal.reason
33
- reject(abortError)
34
- }
35
- if (signal.aborted) {
36
- onAbort()
37
- } else {
38
- signal.addEventListener('abort', onAbort, { once: true })
39
- }
40
- })
41
- try {
42
- return await Promise.race([work, aborted])
43
- } finally {
44
- signal.removeEventListener('abort', onAbort)
45
- }
46
- }
47
-
48
- function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
49
- return new Promise((resolve) => {
50
- const onAbort = (): void => {
51
- clearTimeout(timer)
52
- resolve()
53
- }
54
- // A lane reuses one signal for every send, so a finished wait must not leave its listener behind.
55
- const timer = setTimeout(() => {
56
- signal?.removeEventListener('abort', onAbort)
57
- resolve()
58
- }, ms)
59
- signal?.addEventListener('abort', onAbort, { once: true })
60
- })
61
- }
62
-
63
- /** HTTP statuses a capture request is retried on. 404 and 429 can come from a proxy in front of capture. */
64
- const RETRYABLE_STATUSES = new Set([404, 408, 429, 500, 502, 503, 504])
65
-
66
- /** Only these redirects keep the method and body, so they are the only ones a capture request follows. */
67
- const FOLLOWED_REDIRECT_STATUSES = new Set([307, 308])
68
- const MAX_REDIRECTS = 5
69
-
70
- /** Errors the sender raised for its own request deadline, so a loss summary can call them timeouts. */
71
- const timeoutErrors = new WeakSet<Error>()
72
-
73
- /** Drop details for a copy of an event the server dropped as a duplicate of an earlier one in the request. */
74
- export const DUPLICATE_EVENT_UUID = 'duplicate_event_uuid'
75
-
76
- export interface V1CaptureSenderConfig {
77
- host: string
78
- /** The capture lane this sender posts to. */
79
- path: CaptureEndpoint
80
- apiKey: string
81
- /** The `PostHog-Sdk-Info` library name. PostHog fills `$lib` from it only for an event that has no `$lib`. */
82
- libraryId: string
83
- libraryVersion: string
84
- /** Value for the `User-Agent` header, if the runtime allows setting it. */
85
- userAgent?: string
86
- historicalMigration: boolean
87
- /** The body encoding; a body that fails to compress is sent uncompressed. */
88
- compression: CaptureCompression
89
- requestTimeoutMs: number
90
- /** Retries after the first attempt. */
91
- maxRetries: number
92
- isDebug?: boolean
93
- }
94
-
95
- export interface V1CaptureSenderHooks {
96
- fetch: FetchLike
97
- /**
98
- * Surfaces partial/terminal delivery failures on the client error channel, at most once per
99
- * batch. `summary` is one line with counts and causes only, for when nothing listens.
100
- */
101
- onError: (error: CaptureError, summary: string) => void
102
- now?: () => number
103
- /** Waits between attempts. The sender stops waiting when `signal` aborts, even if this does not. */
104
- sleep?: (ms: number, signal?: AbortSignal) => Promise<void>
105
- generateRequestId?: () => string
106
- /** Uniform in [0, 1); sets the jitter of each retry wait. */
107
- random?: () => number
108
- compress?: (payload: string, codec: CaptureCodec) => Promise<Uint8Array | null>
109
- }
110
-
111
- export interface V1SendOptions {
112
- /** Aborting stops the current attempt and every later one; the pending events come back as unsent. */
113
- signal?: AbortSignal
114
- /**
115
- * When true, events whose last attempt got no HTTP response (or were cut off by `signal`) are
116
- * returned to the caller unreported, so it can queue them again. When false they are reported
117
- * as undelivered.
118
- */
119
- keepUnsent?: boolean
120
- }
121
-
122
- interface RedirectOutcome {
123
- response: PostHogFetchResponse
124
- /** Set when `response` is a redirect the sender does not follow. */
125
- redirectFailure?: string
126
- }
127
-
128
- interface V1CaptureAttempt extends RedirectOutcome {
129
- signal: AbortSignal
130
- waitFor<T>(operation: Promise<T>): Promise<T>
131
- cancelBody: () => Promise<void>
132
- cleanup: () => void
133
- }
134
-
135
- /**
136
- * Sends already-serialized events to one Capture V1 lane (`config.path`),
137
- * owning the full attempt loop: per-event partial retry, exponential backoff
138
- * clamped against `Retry-After`, v1 status classification, and surfacing drops
139
- * / undelivered events on the error channel. Used by both the batched and
140
- * immediate send paths.
141
- *
142
- * Never throws for a handled outcome: after exhausting its own attempt budget it
143
- * reports the failure via `onError` and resolves. Only events that never got an
144
- * HTTP response can come back to the caller, and only with `keepUnsent`.
145
- */
146
- export class V1CaptureSender {
147
- private readonly config: V1CaptureSenderConfig
148
- private readonly hostOrigin: string | undefined
149
- private readonly fetchFn: FetchLike
150
- private readonly onError: (error: CaptureError, summary: string) => void
151
- private readonly now: () => number
152
- private readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>
153
- private readonly generateRequestId: () => string
154
- private readonly random: () => number
155
- private readonly compress: (payload: string, codec: CaptureCodec) => Promise<Uint8Array | null>
156
-
157
- constructor(config: V1CaptureSenderConfig, hooks: V1CaptureSenderHooks) {
158
- this.config = config
159
- this.hostOrigin = originOf(config.host)
160
- this.fetchFn = hooks.fetch
161
- this.onError = hooks.onError
162
- this.now = hooks.now ?? Date.now
163
- this.sleep = hooks.sleep ?? abortableSleep
164
- this.generateRequestId = hooks.generateRequestId ?? uuidv7
165
- this.random = hooks.random ?? Math.random
166
- this.compress = hooks.compress ?? webCompressor.compress
167
- }
168
-
169
- /** Sends `events` and resolves with the ones to queue again (always empty unless `keepUnsent`). */
170
- async send<T extends SerializedV1Event>(events: T[], options: V1SendOptions = {}): Promise<T[]> {
171
- if (events.length === 0) {
172
- return []
173
- }
174
-
175
- const { signal, keepUnsent = false } = options
176
- const requestId = this.generateRequestId()
177
- // created_at is generated once and stays stable across every retry.
178
- const createdAt = new Date(this.now()).toISOString()
179
- const url = `${this.config.host}${this.config.path}`
180
- const drops: CaptureDroppedEvent[] = []
181
- const loss = new CaptureLossTally()
182
- let pending = events
183
-
184
- const unsent = (cause: unknown, failure: string): T[] => {
185
- if (keepUnsent) {
186
- this.surfacePartialDrops(requestId, drops, loss)
187
- return pending
188
- }
189
- this.surfaceBatchFailure(requestId, drops, pending, cause, loss, failure)
190
- return []
191
- }
192
-
193
- // Always make one attempt, so a bad budget reports a delivery error instead of dropping the batch silently.
194
- const { maxRetries } = this.config
195
- const maxAttempts = (Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 0) + 1
196
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
197
- if (signal?.aborted) {
198
- return unsent(signal.reason, 'not sent: aborted')
199
- }
200
- const isLastAttempt = attempt === maxAttempts
201
- const payload = buildV1Body(pending, { createdAt, historicalMigration: this.config.historicalMigration })
202
-
203
- let captureAttempt: V1CaptureAttempt | undefined
204
- let retryDelayMs: number | undefined
205
- try {
206
- captureAttempt = await this.sendOnce(url, payload, attempt, requestId, signal)
207
- const { response, signal: attemptSignal, redirectFailure } = captureAttempt
208
- const { status } = response
209
- if (redirectFailure !== undefined) {
210
- await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {})
211
- const failure = `failed on a redirect it does not follow (HTTP ${status})`
212
- this.surfaceBatchFailure(requestId, drops, pending, new Error(redirectFailure), loss, failure)
213
- return []
214
- }
215
- if (status < 200 || status >= 300) {
216
- if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
217
- const retryAfterMs = this.parseRetryAfter(response)
218
- await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {})
219
- retryDelayMs = this.backoffDelay(attempt, retryAfterMs)
220
- } else {
221
- const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor)
222
- this.surfaceBatchFailure(requestId, drops, pending, httpError, loss, `failed with HTTP ${status}`)
223
- return []
224
- }
225
- } else {
226
- let parsed: V1BatchResponse
227
- try {
228
- parsed = await captureAttempt.waitFor(this.parseResponse(response))
229
- } catch (error) {
230
- if (attemptSignal.aborted) {
231
- throw error
232
- }
233
- // A 2xx without a readable results map is terminal — re-sending against a broken success would loop forever.
234
- this.surfaceBatchFailure(
235
- requestId,
236
- drops,
237
- pending,
238
- new Error(`Capture V1 returned an unparseable ${status} response body`),
239
- loss,
240
- `failed with an unreadable response (HTTP ${status})`
241
- )
242
- return []
243
- }
244
-
245
- const dropsBefore = drops.length
246
- const retryable = this.classify(pending, parsed, drops)
247
- for (const drop of drops.slice(dropsBefore)) {
248
- const cause = drop.details === DUPLICATE_EVENT_UUID ? 'dropped as duplicate uuids' : 'dropped by the server'
249
- loss.add(`${cause} (HTTP ${status})`, 1)
250
- }
251
- if (retryable.length === 0) {
252
- this.surfacePartialDrops(requestId, drops, loss)
253
- return []
254
- }
255
- if (isLastAttempt) {
256
- loss.add(`still marked for retry after ${maxAttempts} attempt(s) (HTTP ${status})`, retryable.length)
257
- this.report(
258
- this.captureError({
259
- requestId,
260
- drops,
261
- retryExhausted: retryable.map((event) => event.uuid),
262
- }),
263
- loss
264
- )
265
- return []
266
- }
267
- pending = retryable
268
- // A 200 partial-retry body can also carry Retry-After (e.g. rate-limited
269
- // retry events); honor it as a minimum the same way as on a retryable status.
270
- const retryAfterMs = this.parseRetryAfter(response)
271
- retryDelayMs = this.backoffDelay(attempt, retryAfterMs)
272
- }
273
- } catch (transportError) {
274
- if (captureAttempt && !captureAttempt.signal.aborted) {
275
- throw transportError
276
- }
277
- // Connection/timeouts, including a timeout while consuming the response body,
278
- // are retried until the budget runs out.
279
- if (isLastAttempt || signal?.aborted) {
280
- return unsent(transportError, this.describeTransportFailure(transportError, signal))
281
- }
282
- retryDelayMs = this.backoffDelay(attempt)
283
- } finally {
284
- captureAttempt?.cleanup()
285
- }
286
-
287
- if (retryDelayMs !== undefined) {
288
- await this.sleepUnlessAborted(retryDelayMs, signal)
289
- }
290
- }
291
- return []
292
- }
293
-
294
- private async sleepUnlessAborted(ms: number, signal: AbortSignal | undefined): Promise<void> {
295
- if (!signal) {
296
- return this.sleep(ms)
297
- }
298
- if (signal.aborted) {
299
- return
300
- }
301
- let onAbort!: () => void
302
- const aborted = new Promise<void>((resolve) => {
303
- onAbort = resolve
304
- signal.addEventListener('abort', onAbort, { once: true })
305
- })
306
- try {
307
- await Promise.race([this.sleep(ms, signal), aborted])
308
- } finally {
309
- signal.removeEventListener('abort', onAbort)
310
- }
311
- }
312
-
313
- private async sendOnce(
314
- url: string,
315
- payload: string,
316
- attempt: number,
317
- requestId: string,
318
- externalSignal: AbortSignal | undefined
319
- ): Promise<V1CaptureAttempt> {
320
- const headers = this.buildHeaders(attempt, requestId)
321
- // Compression runs on the libuv pool, so a busy pool must not hold the request past an external deadline.
322
- const body = await raceAbort(this.encodeBody(payload, headers), externalSignal)
323
-
324
- const controller = new AbortController()
325
- let timeoutPhase = 'waiting for response headers'
326
- let timer: ReturnType<typeof setTimeout> | undefined
327
- let onExternalAbort: (() => void) | undefined
328
- const stopListening = (): void => {
329
- if (onExternalAbort) {
330
- externalSignal?.removeEventListener('abort', onExternalAbort)
331
- }
332
- }
333
- // hooks.fetch is user-injectable, so it may ignore an abort signal while
334
- // resolving headers or reading the body. Race both phases against the same
335
- // deadline rather than relying only on standards-compliant fetch behavior.
336
- const deadline = new Promise<never>((_resolve, reject) => {
337
- const abortWith = (error: Error): void => {
338
- // Reject first so this phase-specific error wins even when an abort-aware
339
- // custom fetch rejects synchronously from the abort event.
340
- reject(error)
341
- controller.abort(error)
342
- }
343
- timer = setTimeout(() => {
344
- const timeoutError = new Error(
345
- `Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`
346
- )
347
- timeoutError.name = 'AbortError'
348
- timeoutErrors.add(timeoutError)
349
- abortWith(timeoutError)
350
- }, this.config.requestTimeoutMs)
351
- if (externalSignal) {
352
- onExternalAbort = () => {
353
- const abortError = new Error(`Capture V1 request aborted ${timeoutPhase}`)
354
- abortError.name = 'AbortError'
355
- abortError.cause = externalSignal.reason
356
- abortWith(abortError)
357
- }
358
- if (externalSignal.aborted) {
359
- onExternalAbort()
360
- } else {
361
- externalSignal.addEventListener('abort', onExternalAbort, { once: true })
362
- }
363
- }
364
- })
365
- // Keeps an early abort from surfacing as an unhandled rejection before the race below observes it.
366
- deadline.catch(() => {})
367
- try {
368
- const fetchPromise = this.fetchFollowingRedirects(url, headers, body, controller.signal)
369
- let responseAccepted = false
370
- void fetchPromise
371
- .then((late) => {
372
- if (controller.signal.aborted && !responseAccepted) {
373
- // An injected fetch may ignore abort and resolve after the deadline.
374
- // Cancel its otherwise unreachable body to release any held resources.
375
- void this.cancelBody(late.response)
376
- }
377
- })
378
- .catch(() => {})
379
- const { response, redirectFailure } = await Promise.race([fetchPromise, deadline])
380
- responseAccepted = true
381
- timeoutPhase = 'while reading the response body'
382
- let cleanedUp = false
383
- let cancellation: Promise<void> | undefined
384
- const cancelBody = (): Promise<void> => (cancellation ??= this.cancelBody(response))
385
- return {
386
- response,
387
- redirectFailure,
388
- signal: controller.signal,
389
- waitFor: <T>(operation: Promise<T>) => Promise.race([operation, deadline]),
390
- cancelBody,
391
- cleanup: () => {
392
- if (cleanedUp) {
393
- return
394
- }
395
- cleanedUp = true
396
- clearTimeout(timer)
397
- stopListening()
398
- if (controller.signal.aborted) {
399
- // The attempt deadline has already elapsed, so cleanup cannot wait
400
- // for a custom response body's cancellation promise to settle.
401
- void cancelBody()
402
- }
403
- },
404
- }
405
- } catch (error) {
406
- clearTimeout(timer)
407
- stopListening()
408
- throw error
409
- }
410
- }
411
-
412
- /**
413
- * Sends with `redirect: 'manual'` and follows 307 and 308 to the configured host's origin, at most
414
- * `MAX_REDIRECTS` times, with the same method, headers and body. A fetch that follows redirects
415
- * itself still works: its final response is not a redirect.
416
- */
417
- private async fetchFollowingRedirects(
418
- url: string,
419
- headers: PostHogFetchOptions['headers'],
420
- body: string | Uint8Array,
421
- signal: AbortSignal
422
- ): Promise<RedirectOutcome> {
423
- let target = url
424
- for (let redirects = 0; ; redirects++) {
425
- const response = await this.fetchFn(target, {
426
- method: 'POST',
427
- headers,
428
- // A fresh copy per request: fetch may detach a byte body it has sent.
429
- body: typeof body === 'string' ? body : body.slice(),
430
- signal,
431
- redirect: 'manual',
432
- })
433
- const { status } = response
434
- if (status < 300 || status >= 400) {
435
- return { response }
436
- }
437
- if (!FOLLOWED_REDIRECT_STATUSES.has(status)) {
438
- return {
439
- response,
440
- redirectFailure: `Capture V1 request got an HTTP ${status} redirect, which it does not follow`,
441
- }
442
- }
443
- if (redirects === MAX_REDIRECTS) {
444
- return { response, redirectFailure: `Capture V1 request was redirected more than ${MAX_REDIRECTS} times` }
445
- }
446
- const next = resolveLocation(response.headers?.get('Location'), target)
447
- if (next === undefined || originOf(next) !== this.hostOrigin) {
448
- return {
449
- response,
450
- redirectFailure: `Capture V1 request got an HTTP ${status} redirect away from the configured host`,
451
- }
452
- }
453
- void this.cancelBody(response)
454
- // An injected fetch may ignore abort, so stop the chain here.
455
- if (signal.aborted) {
456
- throw signal.reason
457
- }
458
- target = next
459
- }
460
- }
461
-
462
- /** Compresses `payload` with the configured codec and sets `Content-Encoding` to match. */
463
- private async encodeBody(payload: string, headers: PostHogFetchOptions['headers']): Promise<string | Uint8Array> {
464
- const codec = this.config.compression
465
- if (codec === 'none') {
466
- return payload
467
- }
468
- try {
469
- const compressed = await this.compress(payload, codec)
470
- if (compressed !== null) {
471
- headers['Content-Encoding'] = codec
472
- return compressed
473
- }
474
- } catch (error) {
475
- if (this.config.isDebug) {
476
- console.error(`Failed to ${codec} compress the capture request body`, error)
477
- }
478
- }
479
- return payload
480
- }
481
-
482
- private buildHeaders(attempt: number, requestId: string): PostHogFetchOptions['headers'] {
483
- const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`
484
- const headers: { [key: string]: string } = {
485
- 'Content-Type': 'application/json',
486
- Authorization: `Bearer ${this.config.apiKey}`,
487
- 'PostHog-Sdk-Info': sdkInfo,
488
- 'PostHog-Attempt': String(attempt),
489
- 'PostHog-Request-Id': requestId,
490
- // Regenerated per attempt — a per-attempt wall-clock stamp, unlike Request-Id / created_at.
491
- 'PostHog-Request-Timestamp': new Date(this.now()).toISOString(),
492
- }
493
- if (this.config.userAgent) {
494
- headers['User-Agent'] = this.config.userAgent
495
- }
496
- return headers
497
- }
498
-
499
- /**
500
- * Partition the pending events against a 2xx result map: `drop` accumulates as
501
- * a terminal failure, `retry` is returned for the next attempt, and
502
- * `ok`/`warning`/unknown/absent are terminal successes.
503
- */
504
- private classify<T extends SerializedV1Event>(
505
- pending: T[],
506
- parsed: V1BatchResponse,
507
- drops: CaptureDroppedEvent[]
508
- ): T[] {
509
- // Events carry canonical uuids, so results match by the canonical form of the server's keys.
510
- const results = new Map<string, V1EventResult>()
511
- for (const [uuid, result] of Object.entries(parsed.results)) {
512
- results.set(canonicalizeUuid(uuid) ?? uuid, result)
513
- }
514
- const retryable: T[] = []
515
- // Only built when a result reports duplicates, so the usual response costs nothing extra.
516
- let copiesSeen: Map<string, number> | undefined
517
- for (const event of pending) {
518
- const result = results.get(event.uuid)
519
- if (!result) {
520
- continue
521
- }
522
- const duplicates = result.duplicates_dropped
523
- if (typeof duplicates === 'number' && Number.isSafeInteger(duplicates) && duplicates > 0) {
524
- copiesSeen ??= new Map()
525
- const copy = copiesSeen.get(event.uuid) ?? 0
526
- copiesSeen.set(event.uuid, copy + 1)
527
- // The first copy takes the result; the next `duplicates` copies are the ones the server dropped.
528
- if (copy >= 1 && copy <= duplicates) {
529
- drops.push({ uuid: event.uuid, details: DUPLICATE_EVENT_UUID })
530
- continue
531
- }
532
- }
533
- if (result.result === 'drop') {
534
- drops.push({ uuid: event.uuid, details: result.details ?? undefined })
535
- } else if (result.result === 'retry') {
536
- retryable.push(event)
537
- }
538
- // ok / warning / unknown codes are terminal successes.
539
- }
540
- return retryable
541
- }
542
-
543
- /** The wait after failed attempt `attempt` (1-based): jittered exponential backoff, raised to `Retry-After`. */
544
- private backoffDelay(attempt: number, retryAfterMs?: number): number {
545
- const jitter = 0.75 + 0.5 * this.random()
546
- const backoff = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1) * jitter, MAX_RETRY_DELAY_MS)
547
- if (retryAfterMs === undefined) {
548
- return backoff
549
- }
550
- // Compared after jitter, so jitter can never make the wait shorter than Retry-After.
551
- return Math.max(backoff, Math.min(retryAfterMs, MAX_RETRY_DELAY_MS))
552
- }
553
-
554
- /** Parse `Retry-After` (delta-seconds or HTTP-date). Non-positive/past values are ignored. */
555
- private parseRetryAfter(response: PostHogFetchResponse): number | undefined {
556
- const raw = response.headers?.get('Retry-After')
557
- if (!raw) {
558
- return undefined
559
- }
560
- const trimmed = raw.trim()
561
- if (/^\d+$/.test(trimmed)) {
562
- const seconds = parseInt(trimmed, 10)
563
- return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined
564
- }
565
- const dateMs = Date.parse(trimmed)
566
- if (Number.isNaN(dateMs)) {
567
- return undefined
568
- }
569
- const delta = dateMs - this.now()
570
- return delta > 0 ? delta : undefined
571
- }
572
-
573
- private async parseResponse(response: PostHogFetchResponse): Promise<V1BatchResponse> {
574
- const text = await response.text()
575
- const parsed = JSON.parse(text)
576
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
577
- throw new Error('unexpected response shape')
578
- }
579
- const results = (parsed as { results?: unknown }).results
580
- if (typeof results !== 'object' || results === null || Array.isArray(results)) {
581
- throw new Error('unexpected results shape')
582
- }
583
- return { results: results as V1BatchResponse['results'] }
584
- }
585
-
586
- private async buildHttpError(
587
- response: PostHogFetchResponse,
588
- status: number,
589
- waitFor: V1CaptureAttempt['waitFor']
590
- ): Promise<Error> {
591
- let bodyText = ''
592
- try {
593
- bodyText = (await waitFor(response.text())).slice(0, 512)
594
- } catch {
595
- // best-effort; a missing or timed-out body should not mask the status
596
- }
597
- const suffix = bodyText ? `: ${bodyText}` : ''
598
- return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`)
599
- }
600
-
601
- private surfaceBatchFailure(
602
- requestId: string,
603
- drops: CaptureDroppedEvent[],
604
- pending: SerializedV1Event[],
605
- cause: unknown,
606
- loss: CaptureLossTally,
607
- failure: string
608
- ): void {
609
- loss.add(failure, pending.length)
610
- this.report(
611
- this.captureError({ requestId, drops, retryExhausted: pending.map((event) => event.uuid), cause }),
612
- loss
613
- )
614
- }
615
-
616
- private surfacePartialDrops(requestId: string, drops: CaptureDroppedEvent[], loss: CaptureLossTally): void {
617
- if (drops.length > 0) {
618
- this.report(this.captureError({ requestId, drops, retryExhausted: [] }), loss)
619
- }
620
- }
621
-
622
- private report(error: CaptureError, loss: CaptureLossTally): void {
623
- this.onError(error, describeCaptureLoss(this.config.path, loss))
624
- }
625
-
626
- /** A failure without an HTTP response, named by type only: its message can carry server or proxy text. */
627
- private describeTransportFailure(error: unknown, signal: AbortSignal | undefined): string {
628
- if (error instanceof Error && timeoutErrors.has(error)) {
629
- return 'failed: request timed out'
630
- }
631
- if (signal?.aborted) {
632
- return 'failed: request aborted'
633
- }
634
- const name = error instanceof Error && /^\w{1,64}$/.test(error.name) ? error.name : 'unknown'
635
- return `failed with a network error (${name})`
636
- }
637
-
638
- private captureError(params: Omit<CaptureErrorParams, 'endpoint'>): CaptureError {
639
- return new CaptureError({ endpoint: this.config.path, ...params })
640
- }
641
-
642
- private async cancelBody(response: PostHogFetchResponse): Promise<void> {
643
- try {
644
- await response.body?.cancel()
645
- } catch {
646
- // Cancellation is best-effort and must never mask delivery handling.
647
- }
648
- }
649
- }
650
-
651
- function originOf(url: string): string | undefined {
652
- try {
653
- return new URL(url).origin
654
- } catch {
655
- return undefined
656
- }
657
- }
658
-
659
- function resolveLocation(location: string | null | undefined, base: string): string | undefined {
660
- if (!location) {
661
- return undefined
662
- }
663
- try {
664
- return new URL(location, base).href
665
- } catch {
666
- return undefined
667
- }
668
- }