@posthog/core 1.69.9 → 1.71.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 (122) hide show
  1. package/capture-v1/package.json +6 -0
  2. package/dist/capture-v1/compression.d.ts +18 -0
  3. package/dist/capture-v1/compression.d.ts.map +1 -0
  4. package/dist/capture-v1/compression.js +70 -0
  5. package/dist/capture-v1/compression.mjs +26 -0
  6. package/dist/capture-v1/errors.d.ts +48 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +82 -0
  9. package/dist/capture-v1/errors.mjs +38 -0
  10. package/dist/capture-v1/index.d.ts +15 -0
  11. package/dist/capture-v1/index.d.ts.map +1 -0
  12. package/dist/capture-v1/index.js +88 -0
  13. package/dist/capture-v1/index.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +150 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +554 -0
  17. package/dist/capture-v1/sender.mjs +507 -0
  18. package/dist/capture-v1/serialize.d.ts +30 -0
  19. package/dist/capture-v1/serialize.d.ts.map +1 -0
  20. package/dist/capture-v1/serialize.js +106 -0
  21. package/dist/capture-v1/serialize.mjs +59 -0
  22. package/dist/capture-v1/transform.d.ts +19 -0
  23. package/dist/capture-v1/transform.d.ts.map +1 -0
  24. package/dist/capture-v1/transform.js +118 -0
  25. package/dist/capture-v1/transform.mjs +77 -0
  26. package/dist/capture-v1/types.d.ts +52 -0
  27. package/dist/capture-v1/types.d.ts.map +1 -0
  28. package/dist/capture-v1/types.js +44 -0
  29. package/dist/capture-v1/types.mjs +3 -0
  30. package/dist/capture-v1/uuid.d.ts +9 -0
  31. package/dist/capture-v1/uuid.d.ts.map +1 -0
  32. package/dist/capture-v1/uuid.js +75 -0
  33. package/dist/capture-v1/uuid.mjs +34 -0
  34. package/dist/featureFlagLocalEvaluation.d.ts +2 -0
  35. package/dist/featureFlagLocalEvaluation.d.ts.map +1 -1
  36. package/dist/featureFlagLocalEvaluation.js +38 -0
  37. package/dist/featureFlagLocalEvaluation.mjs +38 -0
  38. package/dist/featureFlagUtils.d.ts +7 -5
  39. package/dist/featureFlagUtils.d.ts.map +1 -1
  40. package/dist/featureFlagUtils.js +17 -11
  41. package/dist/featureFlagUtils.mjs +14 -11
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +27 -16
  45. package/dist/index.mjs +1 -1
  46. package/dist/posthog-core-stateless.d.ts +44 -7
  47. package/dist/posthog-core-stateless.d.ts.map +1 -1
  48. package/dist/posthog-core-stateless.js +103 -24
  49. package/dist/posthog-core-stateless.mjs +103 -24
  50. package/dist/posthog-core.d.ts +138 -53
  51. package/dist/posthog-core.d.ts.map +1 -1
  52. package/dist/posthog-core.js +341 -115
  53. package/dist/posthog-core.mjs +338 -115
  54. package/dist/types.d.ts +33 -1
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/utils/index.d.ts +1 -1
  57. package/dist/utils/index.d.ts.map +1 -1
  58. package/dist/utils/index.js +25 -12
  59. package/dist/utils/index.mjs +1 -1
  60. package/dist/utils/json-utils.d.ts +11 -1
  61. package/dist/utils/json-utils.d.ts.map +1 -1
  62. package/dist/utils/json-utils.js +50 -2
  63. package/dist/utils/json-utils.mjs +46 -1
  64. package/package.json +13 -3
  65. package/src/capture-v1/compression.ts +50 -0
  66. package/src/capture-v1/errors.ts +91 -0
  67. package/src/capture-v1/index.ts +34 -0
  68. package/src/capture-v1/sender.ts +779 -0
  69. package/src/capture-v1/serialize.ts +113 -0
  70. package/src/capture-v1/transform.ts +135 -0
  71. package/src/capture-v1/types.ts +59 -0
  72. package/src/capture-v1/uuid.ts +53 -0
  73. package/src/featureFlagLocalEvaluation.ts +51 -0
  74. package/src/featureFlagUtils.ts +22 -10
  75. package/src/index.ts +1 -0
  76. package/src/posthog-core-stateless.ts +190 -35
  77. package/src/posthog-core.ts +615 -178
  78. package/src/types.ts +31 -1
  79. package/src/utils/index.ts +1 -1
  80. package/src/utils/json-utils.ts +64 -1
  81. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  82. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  83. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  84. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  85. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  86. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  87. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  88. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  89. package/src/error-tracking/exception-steps.spec.ts +0 -115
  90. package/src/error-tracking/parsers/base.spec.ts +0 -156
  91. package/src/error-tracking/parsers/index.spec.ts +0 -270
  92. package/src/error-tracking/parsers/node.spec.ts +0 -34
  93. package/src/error-tracking/release.spec.ts +0 -34
  94. package/src/logs/index.spec.ts +0 -2421
  95. package/src/logs/logs-utils.spec.ts +0 -266
  96. package/src/metrics/index.spec.ts +0 -1249
  97. package/src/surveys/activation.spec.ts +0 -61
  98. package/src/surveys/events.spec.ts +0 -183
  99. package/src/surveys/keys.spec.ts +0 -29
  100. package/src/surveys/property-matching.spec.ts +0 -539
  101. package/src/surveys/shuffling.spec.ts +0 -51
  102. package/src/surveys/translations.spec.ts +0 -274
  103. package/src/surveys/validation.spec.ts +0 -168
  104. package/src/traces/config.spec.ts +0 -271
  105. package/src/traces/ids.spec.ts +0 -115
  106. package/src/traces/index.spec.ts +0 -3287
  107. package/src/traces/live-spans.spec.ts +0 -69
  108. package/src/traces/otlp.spec.ts +0 -368
  109. package/src/traces/span.spec.ts +0 -1137
  110. package/src/traces/traceparent.spec.ts +0 -184
  111. package/src/utils/bot-detection.spec.ts +0 -107
  112. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  113. package/src/utils/json-utils.spec.ts +0 -115
  114. package/src/utils/named-error.spec.ts +0 -36
  115. package/src/utils/number-utils.spec.ts +0 -212
  116. package/src/utils/otlp-any-value.spec.ts +0 -376
  117. package/src/utils/otlp-resource.spec.ts +0 -171
  118. package/src/utils/promise-queue.spec.ts +0 -55
  119. package/src/utils/string-utils.spec.ts +0 -158
  120. package/src/utils/type-utils.spec.ts +0 -38
  121. package/src/utils/webview-app-utils.spec.ts +0 -118
  122. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -2,6 +2,7 @@ import type { OtlpLogsPayload, OtlpMetricsPayload, OtlpTracesPayload } from '@po
2
2
  import type { SendMetricsBatchOutcome } from './metrics/types'
3
3
  import type { SendTracesBatchOutcome } from './traces/types'
4
4
  import { SimpleEventEmitter } from './eventemitter'
5
+ import { EVENT_OPTION_LEGACY_PROPERTIES } from './event-options'
5
6
  import { getFeatureFlagValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse } from './featureFlagUtils'
6
7
  import { gzipCompress, isGzipSupported } from './gzip'
7
8
  import {
@@ -26,6 +27,7 @@ import {
26
27
  Logger,
27
28
  GetFlagsResult,
28
29
  FeatureFlagRequestError,
30
+ PostHogFlagsKnownAbsentPropertyKeys,
29
31
  } from './types'
30
32
  import {
31
33
  allSettled,
@@ -157,6 +159,9 @@ type SuccessfulWriteResponseHandling = {
157
159
  type: 'successful-write'
158
160
  }
159
161
 
162
+ /** Properties that set a per-event option, kept on a minimal `$feature_flag_called` event so it keeps the option. */
163
+ const FLAG_CALLED_OPTION_PROPERTIES: readonly string[] = Object.values(EVENT_OPTION_LEGACY_PROPERTIES)
164
+
160
165
  export const maybeAdd = (key: string, value: JsonType | undefined): Record<string, JsonType> =>
161
166
  value !== undefined ? { [key]: value } : {}
162
167
 
@@ -285,6 +290,15 @@ function isWellFormedQueueItem(item: unknown): item is PostHogQueueItem {
285
290
  return isPostHogEventProperties((item as PostHogQueueItem).message)
286
291
  }
287
292
 
293
+ /**
294
+ * What a `sendBatch()` override can resolve with when the transport keeps some events for a later
295
+ * flush. The flush removes the rest of the batch from the queue, keeps the events at `keepIndices`
296
+ * (positions in the batch passed to `sendBatch()`), and stops draining that route until the next
297
+ * flush. `tooLarge` halves the batch size and resends the kept events instead. `timedOut` keeps the
298
+ * events the same way and halves the batch size for the next flush.
299
+ */
300
+ export type SendBatchOutcome = { keepIndices: readonly number[]; tooLarge?: boolean; timedOut?: boolean }
301
+
288
302
  /**
289
303
  * Outcome of a logs batch send. Keeps HTTP error classification inside core so
290
304
  * PostHogLogs doesn't need to know about specific error types.
@@ -348,6 +362,8 @@ export abstract class PostHogCoreStateless {
348
362
  readonly preloadFeatureFlags: boolean
349
363
  readonly disableSurveys: boolean
350
364
  private maxBatchSize: number
365
+ // The batch size before a timeout lowered it; each delivered batch doubles `maxBatchSize` back towards it.
366
+ private batchSizeBeforeTimeout: number | undefined
351
367
  private maxQueueSize: number
352
368
  private flushInterval: number
353
369
  private flushPromise: Promise<any> | null = null
@@ -490,7 +506,7 @@ export abstract class PostHogCoreStateless {
490
506
  'evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.'
491
507
  )
492
508
  }
493
- this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false)
509
+ this.disableCompression = !this.isCompressionAvailable() || (options?.disableCompression ?? false)
494
510
  }
495
511
 
496
512
  protected logMsgIfDebug(fn: () => void): void {
@@ -618,7 +634,7 @@ export abstract class PostHogCoreStateless {
618
634
  properties.$feature_flag_has_experiment === false &&
619
635
  this.isMinimalFlagCalledEventsEnabled()
620
636
  ) {
621
- properties = minimizeFlagCalledEventProperties(properties)
637
+ properties = minimizeFlagCalledEventProperties(properties, FLAG_CALLED_OPTION_PROPERTIES)
622
638
  }
623
639
  return {
624
640
  distinct_id: payload.distinct_id,
@@ -1073,7 +1089,8 @@ export abstract class PostHogCoreStateless {
1073
1089
  personProperties: Record<string, string> = {},
1074
1090
  groupProperties: Record<string, Record<string, string>> = {},
1075
1091
  disableGeoip?: boolean,
1076
- flagKeysToEvaluate?: string[]
1092
+ flagKeysToEvaluate?: string[],
1093
+ knownAbsentPropertyKeys?: PostHogFlagsKnownAbsentPropertyKeys
1077
1094
  ): Promise<{
1078
1095
  flags: PostHogFlagsResponse['featureFlags'] | undefined
1079
1096
  payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined
@@ -1087,7 +1104,8 @@ export abstract class PostHogCoreStateless {
1087
1104
  personProperties,
1088
1105
  groupProperties,
1089
1106
  disableGeoip,
1090
- flagKeysToEvaluate
1107
+ flagKeysToEvaluate,
1108
+ knownAbsentPropertyKeys
1091
1109
  )
1092
1110
  }
1093
1111
 
@@ -1097,7 +1115,8 @@ export abstract class PostHogCoreStateless {
1097
1115
  personProperties: Record<string, string> = {},
1098
1116
  groupProperties: Record<string, Record<string, string>> = {},
1099
1117
  disableGeoip?: boolean,
1100
- flagKeysToEvaluate?: string[]
1118
+ flagKeysToEvaluate?: string[],
1119
+ knownAbsentPropertyKeys?: PostHogFlagsKnownAbsentPropertyKeys
1101
1120
  ): Promise<{
1102
1121
  flags: PostHogFlagsResponse['featureFlags'] | undefined
1103
1122
  payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined
@@ -1111,7 +1130,8 @@ export abstract class PostHogCoreStateless {
1111
1130
  personProperties,
1112
1131
  groupProperties,
1113
1132
  disableGeoip,
1114
- flagKeysToEvaluate
1133
+ flagKeysToEvaluate,
1134
+ knownAbsentPropertyKeys
1115
1135
  )
1116
1136
 
1117
1137
  if (!featureFlagDetails) {
@@ -1135,7 +1155,8 @@ export abstract class PostHogCoreStateless {
1135
1155
  personProperties: Record<string, string> = {},
1136
1156
  groupProperties: Record<string, Record<string, string>> = {},
1137
1157
  disableGeoip?: boolean,
1138
- flagKeysToEvaluate?: string[]
1158
+ flagKeysToEvaluate?: string[],
1159
+ knownAbsentPropertyKeys?: PostHogFlagsKnownAbsentPropertyKeys
1139
1160
  ): Promise<PostHogFeatureFlagDetails | undefined> {
1140
1161
  await this._initPromise
1141
1162
 
@@ -1145,6 +1166,19 @@ export abstract class PostHogCoreStateless {
1145
1166
  if (flagKeysToEvaluate) {
1146
1167
  extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate
1147
1168
  }
1169
+ const personKeysKnownAbsent = knownAbsentPropertyKeys?.personPropertyKeysKnownAbsent
1170
+ if (personKeysKnownAbsent && personKeysKnownAbsent.length > 0) {
1171
+ extraPayload['person_property_keys_known_absent'] = [...personKeysKnownAbsent]
1172
+ }
1173
+ // fromEntries keeps a group type such as `__proto__` as a normal key.
1174
+ const groupKeysKnownAbsent: Record<string, string[]> = Object.fromEntries(
1175
+ Object.entries(knownAbsentPropertyKeys?.groupPropertyKeysKnownAbsent ?? {})
1176
+ .filter(([, keys]) => keys && keys.length > 0)
1177
+ .map(([groupType, keys]) => [groupType, [...keys]])
1178
+ )
1179
+ if (Object.keys(groupKeysKnownAbsent).length > 0) {
1180
+ extraPayload['group_property_keys_known_absent'] = groupKeysKnownAbsent
1181
+ }
1148
1182
  const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload)
1149
1183
 
1150
1184
  if (!result.success) {
@@ -1396,6 +1430,42 @@ export abstract class PostHogCoreStateless {
1396
1430
  }
1397
1431
  }
1398
1432
 
1433
+ /** The most event bytes one batch may carry, or undefined to batch by count only. */
1434
+ protected batchByteTarget(): number | undefined {
1435
+ return undefined
1436
+ }
1437
+
1438
+ /** The bytes an event adds to a batch, used when `batchByteTarget()` is set. */
1439
+ protected batchEventBytes(_message: PostHogEventProperties): number {
1440
+ return 0
1441
+ }
1442
+
1443
+ /**
1444
+ * When the leading `messages` are a resend that has to go out on its own, how many of them;
1445
+ * otherwise undefined.
1446
+ */
1447
+ protected resendBatchSize(_messages: (PostHogEventProperties | undefined)[]): number | undefined {
1448
+ return undefined
1449
+ }
1450
+
1451
+ /** How many leading messages fit the byte target; the first always does, so an oversize event goes alone. */
1452
+ private countWithinBatchByteTarget(messages: (PostHogEventProperties | undefined)[]): number {
1453
+ const target = this.batchByteTarget()
1454
+ if (target === undefined) {
1455
+ return messages.length
1456
+ }
1457
+ let total = 0
1458
+ for (let index = 0; index < messages.length; index++) {
1459
+ const message = messages[index]
1460
+ const bytes = message === undefined ? 0 : this.batchEventBytes(message)
1461
+ if (index > 0 && total + bytes > target) {
1462
+ return index
1463
+ }
1464
+ total += bytes
1465
+ }
1466
+ return messages.length
1467
+ }
1468
+
1399
1469
  protected normalizeMessage(message: PostHogEventProperties): PostHogEventProperties {
1400
1470
  // Top-level `type` is deprecated and a no-op for batch ingestion.
1401
1471
  // Top-level `library` and `library_version` are deprecated; `$lib` and
@@ -1416,7 +1486,7 @@ export abstract class PostHogCoreStateless {
1416
1486
  sanitizedMessage.properties = properties
1417
1487
  }
1418
1488
 
1419
- sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7)
1489
+ sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, () => this.generateEventUuid())
1420
1490
 
1421
1491
  return sanitizedMessage
1422
1492
  }
@@ -1436,11 +1506,16 @@ export abstract class PostHogCoreStateless {
1436
1506
  : normalized
1437
1507
  }
1438
1508
 
1509
+ /** A new event uuid. */
1510
+ protected generateEventUuid(): string {
1511
+ return uuidv7()
1512
+ }
1513
+
1439
1514
  protected prepareMessage(_message: any, options?: PostHogCaptureOptions): PostHogEventProperties {
1440
1515
  const message = {
1441
1516
  ..._message,
1442
1517
  timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
1443
- uuid: getEventUuid(options?.uuid, uuidv7),
1518
+ uuid: getEventUuid(options?.uuid, () => this.generateEventUuid()),
1444
1519
  }
1445
1520
 
1446
1521
  const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip
@@ -1481,13 +1556,22 @@ export abstract class PostHogCoreStateless {
1481
1556
 
1482
1557
  /**
1483
1558
  * The flush the SDK runs on its own, from the interval timer or the `flushAt`
1484
- * threshold. Separate from `flush()` so a host can hold back work that an
1485
- * endpoint has asked it to wait on, which an explicit flush overrides.
1559
+ * threshold. Hosts override it when an automatic flush covers less than
1560
+ * `flush()` does.
1486
1561
  */
1487
1562
  protected flushAutomatic(): Promise<void> {
1488
1563
  return this.flush()
1489
1564
  }
1490
1565
 
1566
+ /**
1567
+ * How long flushes wait before sending, in milliseconds, or 0 when they can send. Checked right
1568
+ * before a flush sends, so a flush queued behind one that got told to wait also waits. A held
1569
+ * flush resolves without sending; `shutdown()` waits the hold out when it fits in its timeout.
1570
+ */
1571
+ protected flushHoldMs(): number {
1572
+ return 0
1573
+ }
1574
+
1491
1575
  private async waitForPendingPromises(
1492
1576
  maxPromiseId: number,
1493
1577
  ignoredPromises: (Promise<any> | null | undefined)[] = []
@@ -1574,6 +1658,9 @@ export abstract class PostHogCoreStateless {
1574
1658
  if (this.pendingFlushPromise === nextFlushPromise) {
1575
1659
  this.pendingFlushPromise = null
1576
1660
  }
1661
+ if (this.flushHoldMs() > 0) {
1662
+ return
1663
+ }
1577
1664
  return this._flush()
1578
1665
  })
1579
1666
 
@@ -1610,6 +1697,14 @@ export abstract class PostHogCoreStateless {
1610
1697
  return headers
1611
1698
  }
1612
1699
 
1700
+ /**
1701
+ * Whether `compressPayload` can gzip in this runtime. Called from the constructor, so overrides must not read
1702
+ * instance fields. Clients that override `compressPayload` with another compressor override this too.
1703
+ */
1704
+ protected isCompressionAvailable(): boolean {
1705
+ return isGzipSupported()
1706
+ }
1707
+
1613
1708
  /**
1614
1709
  * Compresses an outgoing payload. Runtime-specific clients can override this
1615
1710
  * to avoid using the Web Streams compression implementation.
@@ -1638,7 +1733,7 @@ export abstract class PostHogCoreStateless {
1638
1733
  batchMessages: (PostHogEventProperties | undefined)[],
1639
1734
  retryOptions?: Partial<RetriableOptions>,
1640
1735
  route: string = DEFAULT_QUEUE_ROUTE
1641
- ): Promise<void> {
1736
+ ): Promise<void | SendBatchOutcome> {
1642
1737
  const data: Record<string, any> = {
1643
1738
  api_key: this.projectToken,
1644
1739
  batch: batchMessages.map((message) => {
@@ -1745,35 +1840,44 @@ export abstract class PostHogCoreStateless {
1745
1840
  let sentFromRoute = 0
1746
1841
 
1747
1842
  while (queue.length > 0 && sentFromRoute < originalQueueLength) {
1748
- const batchItems = queue.slice(0, this.maxBatchSize)
1749
- const batchMessages = batchItems.map((item) =>
1843
+ const countItems = queue.slice(0, this.maxBatchSize)
1844
+ const countMessages = countItems.map((item) =>
1750
1845
  item.message === undefined ? item.message : this.normalizeMessage(item.message)
1751
1846
  )
1752
-
1753
- const persistQueueChange = async (): Promise<void> => {
1847
+ const batchSize = Math.min(
1848
+ this.countWithinBatchByteTarget(countMessages),
1849
+ this.resendBatchSize(countMessages) ?? countMessages.length
1850
+ )
1851
+ const batchItems = countItems.slice(0, batchSize)
1852
+ const batchMessages = countMessages.slice(0, batchSize)
1853
+
1854
+ const persistQueueChange = async (keepIndices?: ReadonlySet<number>): Promise<void> => {
1855
+ const removedBatchItems = keepIndices ? batchItems.filter((_, index) => !keepIndices.has(index)) : batchItems
1856
+ if (removedBatchItems.length === 0) {
1857
+ await this.flushStorage()
1858
+ return
1859
+ }
1754
1860
  const refreshedQueue = this.getPersistedProperty<PostHogQueueItem[]>(queueKey) || []
1755
1861
  // The live queue may have overflowed while this batch was in flight. Remove only
1756
- // snapshotted items: UUID survives persistence, while reference identity supports
1757
- // legacy queue items without a UUID.
1758
- const remainingBatchItems = [...batchItems]
1759
- const newQueue = refreshedQueue.filter((item) => {
1760
- const itemUuid = item.message?.uuid
1761
- const batchItemIndex = remainingBatchItems.findIndex(
1762
- (batchItem) =>
1763
- batchItem === item ||
1764
- (typeof itemUuid === 'string' && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid)
1765
- )
1766
-
1767
- if (batchItemIndex === -1) {
1768
- return true
1862
+ // snapshotted items, by reference first so events sharing a UUID keep their own copy,
1863
+ // then by UUID, which survives persistence.
1864
+ const removedQueueIndices = new Set<number>()
1865
+ const findQueueIndex = (matches: (item: PostHogQueueItem) => boolean): number =>
1866
+ refreshedQueue.findIndex((item, index) => !removedQueueIndices.has(index) && matches(item))
1867
+ for (const batchItem of removedBatchItems) {
1868
+ let queueIndex = findQueueIndex((item) => item === batchItem)
1869
+ const uuid = batchItem.message?.uuid
1870
+ if (queueIndex === -1 && typeof uuid === 'string' && uuid.length > 0) {
1871
+ queueIndex = findQueueIndex((item) => item.message?.uuid === uuid)
1769
1872
  }
1770
-
1771
- remainingBatchItems.splice(batchItemIndex, 1)
1772
- return false
1773
- })
1873
+ if (queueIndex !== -1) {
1874
+ removedQueueIndices.add(queueIndex)
1875
+ }
1876
+ }
1877
+ const newQueue = refreshedQueue.filter((_, index) => !removedQueueIndices.has(index))
1774
1878
  this.setPersistedProperty<PostHogQueueItem[]>(queueKey, newQueue)
1775
1879
  queue = newQueue
1776
- this._dequeuedMessagesCount += batchItems.length
1880
+ this._dequeuedMessagesCount += removedBatchItems.length
1777
1881
  // Wait for storage to complete to prevent duplicate events on app crash
1778
1882
  await this.flushStorage()
1779
1883
  }
@@ -1789,12 +1893,14 @@ export abstract class PostHogCoreStateless {
1789
1893
  },
1790
1894
  }
1791
1895
 
1896
+ let outcome: void | SendBatchOutcome
1792
1897
  try {
1793
- await this.sendBatch(batchMessages, retryOptions, route)
1898
+ outcome = await this.sendBatch(batchMessages, retryOptions, route)
1794
1899
  } catch (err) {
1795
1900
  if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
1796
1901
  // if we get a 413 error, we want to reduce the batch size and try again
1797
1902
  this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2))
1903
+ this.batchSizeBeforeTimeout = undefined
1798
1904
  this._logger.warn(
1799
1905
  `Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`
1800
1906
  )
@@ -1812,10 +1918,45 @@ export abstract class PostHogCoreStateless {
1812
1918
  throw err
1813
1919
  }
1814
1920
 
1921
+ const keepIndices = outcome ? new Set(outcome.keepIndices) : undefined
1922
+
1923
+ if (outcome?.tooLarge && keepIndices && keepIndices.size > 1) {
1924
+ if (keepIndices.size < batchMessages.length) {
1925
+ // Remove events the transport already dropped so the smaller batches don't report them again.
1926
+ await persistQueueChange(keepIndices)
1927
+ }
1928
+ this.maxBatchSize = Math.max(1, Math.floor(keepIndices.size / 2))
1929
+ this.batchSizeBeforeTimeout = undefined
1930
+ this._logger.warn(
1931
+ `Received 413 when sending batch of size ${keepIndices.size}, reducing batch size to ${this.maxBatchSize}`
1932
+ )
1933
+ continue
1934
+ }
1935
+
1936
+ if (keepIndices && keepIndices.size > 0) {
1937
+ if (outcome?.timedOut && keepIndices.size > 1) {
1938
+ this.batchSizeBeforeTimeout ??= this.maxBatchSize
1939
+ this.maxBatchSize = Math.max(1, Math.floor(keepIndices.size / 2))
1940
+ this._logger.warn(
1941
+ `Request timed out when sending batch of size ${keepIndices.size}, reducing batch size to ${this.maxBatchSize}`
1942
+ )
1943
+ }
1944
+ await persistQueueChange(keepIndices)
1945
+ sentMessages.push(...batchMessages.filter((_, index) => !keepIndices.has(index)))
1946
+ // The transport asked to wait before sending the kept events again.
1947
+ return
1948
+ }
1949
+
1815
1950
  await persistQueueChange()
1816
1951
 
1817
1952
  sentMessages.push(...batchMessages)
1818
1953
  sentFromRoute += batchMessages.length
1954
+ if (this.batchSizeBeforeTimeout !== undefined) {
1955
+ this.maxBatchSize = Math.min(this.batchSizeBeforeTimeout, this.maxBatchSize * 2)
1956
+ if (this.maxBatchSize >= this.batchSizeBeforeTimeout) {
1957
+ this.batchSizeBeforeTimeout = undefined
1958
+ }
1959
+ }
1819
1960
  }
1820
1961
  }
1821
1962
 
@@ -2086,6 +2227,7 @@ export abstract class PostHogCoreStateless {
2086
2227
 
2087
2228
  await this._initPromise
2088
2229
  let hasTimedOut = false
2230
+ const deadline = Date.now() + shutdownTimeoutMs
2089
2231
  this.clearFlushTimer()
2090
2232
 
2091
2233
  if (this.disabled) {
@@ -2103,6 +2245,19 @@ export abstract class PostHogCoreStateless {
2103
2245
  break
2104
2246
  }
2105
2247
 
2248
+ const holdMs = this.flushHoldMs()
2249
+ if (holdMs > 0) {
2250
+ if (Date.now() + holdMs >= deadline) {
2251
+ this._logger.warn('Shutdown stopped draining: the endpoint asked to wait past the shutdown timeout.')
2252
+ break
2253
+ }
2254
+ await new Promise<void>((resolve) => safeSetTimeout(resolve, holdMs))
2255
+ if (hasTimedOut) {
2256
+ break
2257
+ }
2258
+ continue
2259
+ }
2260
+
2106
2261
  const dequeuedBeforeFlush = this._dequeuedMessagesCount
2107
2262
 
2108
2263
  // flush again to make sure we send all events, some of which might've been added