@posthog/core 1.70.0 → 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 (117) 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/featureFlagUtils.d.ts +7 -5
  35. package/dist/featureFlagUtils.d.ts.map +1 -1
  36. package/dist/featureFlagUtils.js +17 -11
  37. package/dist/featureFlagUtils.mjs +14 -11
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +27 -16
  41. package/dist/index.mjs +1 -1
  42. package/dist/posthog-core-stateless.d.ts +40 -3
  43. package/dist/posthog-core-stateless.d.ts.map +1 -1
  44. package/dist/posthog-core-stateless.js +87 -19
  45. package/dist/posthog-core-stateless.mjs +87 -19
  46. package/dist/posthog-core.d.ts +138 -53
  47. package/dist/posthog-core.d.ts.map +1 -1
  48. package/dist/posthog-core.js +341 -115
  49. package/dist/posthog-core.mjs +338 -115
  50. package/dist/types.d.ts +24 -1
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/utils/index.d.ts +1 -1
  53. package/dist/utils/index.d.ts.map +1 -1
  54. package/dist/utils/index.js +25 -12
  55. package/dist/utils/index.mjs +1 -1
  56. package/dist/utils/json-utils.d.ts +11 -1
  57. package/dist/utils/json-utils.d.ts.map +1 -1
  58. package/dist/utils/json-utils.js +50 -2
  59. package/dist/utils/json-utils.mjs +46 -1
  60. package/package.json +12 -2
  61. package/src/capture-v1/compression.ts +50 -0
  62. package/src/capture-v1/errors.ts +91 -0
  63. package/src/capture-v1/index.ts +34 -0
  64. package/src/capture-v1/sender.ts +779 -0
  65. package/src/capture-v1/serialize.ts +113 -0
  66. package/src/capture-v1/transform.ts +135 -0
  67. package/src/capture-v1/types.ts +59 -0
  68. package/src/capture-v1/uuid.ts +53 -0
  69. package/src/featureFlagUtils.ts +22 -10
  70. package/src/index.ts +1 -0
  71. package/src/posthog-core-stateless.ts +166 -30
  72. package/src/posthog-core.ts +615 -178
  73. package/src/types.ts +21 -1
  74. package/src/utils/index.ts +1 -1
  75. package/src/utils/json-utils.ts +64 -1
  76. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  77. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  78. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  79. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  80. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  81. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  82. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  83. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  84. package/src/error-tracking/exception-steps.spec.ts +0 -115
  85. package/src/error-tracking/parsers/base.spec.ts +0 -156
  86. package/src/error-tracking/parsers/index.spec.ts +0 -270
  87. package/src/error-tracking/parsers/node.spec.ts +0 -34
  88. package/src/error-tracking/release.spec.ts +0 -34
  89. package/src/logs/index.spec.ts +0 -2421
  90. package/src/logs/logs-utils.spec.ts +0 -266
  91. package/src/metrics/index.spec.ts +0 -1249
  92. package/src/surveys/activation.spec.ts +0 -61
  93. package/src/surveys/events.spec.ts +0 -183
  94. package/src/surveys/keys.spec.ts +0 -29
  95. package/src/surveys/property-matching.spec.ts +0 -539
  96. package/src/surveys/shuffling.spec.ts +0 -51
  97. package/src/surveys/translations.spec.ts +0 -274
  98. package/src/surveys/validation.spec.ts +0 -168
  99. package/src/traces/config.spec.ts +0 -271
  100. package/src/traces/ids.spec.ts +0 -115
  101. package/src/traces/index.spec.ts +0 -3287
  102. package/src/traces/live-spans.spec.ts +0 -69
  103. package/src/traces/otlp.spec.ts +0 -368
  104. package/src/traces/span.spec.ts +0 -1137
  105. package/src/traces/traceparent.spec.ts +0 -184
  106. package/src/utils/bot-detection.spec.ts +0 -107
  107. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  108. package/src/utils/json-utils.spec.ts +0 -115
  109. package/src/utils/named-error.spec.ts +0 -36
  110. package/src/utils/number-utils.spec.ts +0 -212
  111. package/src/utils/otlp-any-value.spec.ts +0 -376
  112. package/src/utils/otlp-resource.spec.ts +0 -171
  113. package/src/utils/promise-queue.spec.ts +0 -55
  114. package/src/utils/string-utils.spec.ts +0 -158
  115. package/src/utils/type-utils.spec.ts +0 -38
  116. package/src/utils/webview-app-utils.spec.ts +0 -118
  117. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -37,6 +37,7 @@ __webpack_require__.d(__webpack_exports__, {
37
37
  maybeAdd: ()=>maybeAdd
38
38
  });
39
39
  const external_eventemitter_js_namespaceObject = require("./eventemitter.js");
40
+ const external_event_options_js_namespaceObject = require("./event-options.js");
40
41
  const external_featureFlagUtils_js_namespaceObject = require("./featureFlagUtils.js");
41
42
  const external_gzip_js_namespaceObject = require("./gzip.js");
42
43
  const external_types_js_namespaceObject = require("./types.js");
@@ -109,6 +110,7 @@ class PostHogFetchNetworkError extends Error {
109
110
  } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';
110
111
  }
111
112
  }
113
+ const FLAG_CALLED_OPTION_PROPERTIES = Object.values(external_event_options_js_namespaceObject.EVENT_OPTION_LEGACY_PROPERTIES);
112
114
  const maybeAdd = (key, value)=>void 0 !== value ? {
113
115
  [key]: value
114
116
  } : {};
@@ -232,7 +234,7 @@ class PostHogCoreStateless {
232
234
  this._isInitialized = true;
233
235
  this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;
234
236
  if (options?.evaluationEnvironments && !options?.evaluationContexts) this._logger.warn('evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.');
235
- this.disableCompression = !(0, external_gzip_js_namespaceObject.isGzipSupported)() || (options?.disableCompression ?? false);
237
+ this.disableCompression = !this.isCompressionAvailable() || (options?.disableCompression ?? false);
236
238
  }
237
239
  logMsgIfDebug(fn) {
238
240
  if (this.isDebug) fn();
@@ -287,7 +289,7 @@ class PostHogCoreStateless {
287
289
  const userProperties = payload.properties || {};
288
290
  let properties = this.mergeCommonEventProperties(userProperties);
289
291
  applyCallerFeatureFlagOverrides(properties, userProperties);
290
- if ('$feature_flag_called' === payload.event && false === properties.$feature_flag_has_experiment && this.isMinimalFlagCalledEventsEnabled()) properties = (0, external_featureFlagUtils_js_namespaceObject.minimizeFlagCalledEventProperties)(properties);
292
+ if ('$feature_flag_called' === payload.event && false === properties.$feature_flag_has_experiment && this.isMinimalFlagCalledEventsEnabled()) properties = (0, external_featureFlagUtils_js_namespaceObject.minimizeFlagCalledEventProperties)(properties, FLAG_CALLED_OPTION_PROPERTIES);
291
293
  return {
292
294
  distinct_id: payload.distinct_id,
293
295
  event: payload.event,
@@ -691,6 +693,23 @@ class PostHogCoreStateless {
691
693
  this._events.emit('error', err);
692
694
  }
693
695
  }
696
+ batchByteTarget() {}
697
+ batchEventBytes(_message) {
698
+ return 0;
699
+ }
700
+ resendBatchSize(_messages) {}
701
+ countWithinBatchByteTarget(messages) {
702
+ const target = this.batchByteTarget();
703
+ if (void 0 === target) return messages.length;
704
+ let total = 0;
705
+ for(let index = 0; index < messages.length; index++){
706
+ const message = messages[index];
707
+ const bytes = void 0 === message ? 0 : this.batchEventBytes(message);
708
+ if (index > 0 && total + bytes > target) return index;
709
+ total += bytes;
710
+ }
711
+ return messages.length;
712
+ }
694
713
  normalizeMessage(message) {
695
714
  const { type: _type, library, library_version, ...sanitizedMessage } = message;
696
715
  let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : void 0;
@@ -703,7 +722,7 @@ class PostHogCoreStateless {
703
722
  $lib_version: library_version
704
723
  };
705
724
  if (properties) sanitizedMessage.properties = properties;
706
- sanitizedMessage.uuid = (0, index_js_namespaceObject.getEventUuid)(sanitizedMessage.uuid, uuidv7_js_namespaceObject.uuidv7);
725
+ sanitizedMessage.uuid = (0, index_js_namespaceObject.getEventUuid)(sanitizedMessage.uuid, ()=>this.generateEventUuid());
707
726
  return sanitizedMessage;
708
727
  }
709
728
  normalizeTimestampForWire(timestamp) {
@@ -713,11 +732,14 @@ class PostHogCoreStateless {
713
732
  const fractionalSeconds = 'string' == typeof timestamp ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : void 0;
714
733
  return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
715
734
  }
735
+ generateEventUuid() {
736
+ return (0, uuidv7_js_namespaceObject.uuidv7)();
737
+ }
716
738
  prepareMessage(_message, options) {
717
739
  const message = {
718
740
  ..._message,
719
741
  timestamp: options?.timestamp ? options?.timestamp : (0, index_js_namespaceObject.currentISOTime)(),
720
- uuid: (0, index_js_namespaceObject.getEventUuid)(options?.uuid, uuidv7_js_namespaceObject.uuidv7)
742
+ uuid: (0, index_js_namespaceObject.getEventUuid)(options?.uuid, ()=>this.generateEventUuid())
721
743
  };
722
744
  const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
723
745
  if (addGeoipDisableProperty) {
@@ -745,6 +767,9 @@ class PostHogCoreStateless {
745
767
  flushAutomatic() {
746
768
  return this.flush();
747
769
  }
770
+ flushHoldMs() {
771
+ return 0;
772
+ }
748
773
  async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
749
774
  const ignoredPendingPromises = ignoredPromises.filter((promise)=>!!promise);
750
775
  let iteration = 0;
@@ -779,6 +804,7 @@ class PostHogCoreStateless {
779
804
  previousFlushPromise
780
805
  ])).then(()=>{
781
806
  if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;
807
+ if (this.flushHoldMs() > 0) return;
782
808
  return this._flush();
783
809
  });
784
810
  this.pendingFlushPromise = nextFlushPromise;
@@ -800,6 +826,9 @@ class PostHogCoreStateless {
800
826
  if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;
801
827
  return headers;
802
828
  }
829
+ isCompressionAvailable() {
830
+ return (0, external_gzip_js_namespaceObject.isGzipSupported)();
831
+ }
803
832
  compressPayload(payload) {
804
833
  return (0, external_gzip_js_namespaceObject.gzipCompress)(payload, this.isDebug);
805
834
  }
@@ -872,23 +901,27 @@ class PostHogCoreStateless {
872
901
  const originalQueueLength = queue.length;
873
902
  let sentFromRoute = 0;
874
903
  while(queue.length > 0 && sentFromRoute < originalQueueLength){
875
- const batchItems = queue.slice(0, this.maxBatchSize);
876
- const batchMessages = batchItems.map((item)=>void 0 === item.message ? item.message : this.normalizeMessage(item.message));
877
- const persistQueueChange = async ()=>{
904
+ const countItems = queue.slice(0, this.maxBatchSize);
905
+ const countMessages = countItems.map((item)=>void 0 === item.message ? item.message : this.normalizeMessage(item.message));
906
+ const batchSize = Math.min(this.countWithinBatchByteTarget(countMessages), this.resendBatchSize(countMessages) ?? countMessages.length);
907
+ const batchItems = countItems.slice(0, batchSize);
908
+ const batchMessages = countMessages.slice(0, batchSize);
909
+ const persistQueueChange = async (keepIndices)=>{
910
+ const removedBatchItems = keepIndices ? batchItems.filter((_, index)=>!keepIndices.has(index)) : batchItems;
911
+ if (0 === removedBatchItems.length) return void await this.flushStorage();
878
912
  const refreshedQueue = this.getPersistedProperty(queueKey) || [];
879
- const remainingBatchItems = [
880
- ...batchItems
881
- ];
882
- const newQueue = refreshedQueue.filter((item)=>{
883
- const itemUuid = item.message?.uuid;
884
- const batchItemIndex = remainingBatchItems.findIndex((batchItem)=>batchItem === item || 'string' == typeof itemUuid && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
885
- if (-1 === batchItemIndex) return true;
886
- remainingBatchItems.splice(batchItemIndex, 1);
887
- return false;
888
- });
913
+ const removedQueueIndices = new Set();
914
+ const findQueueIndex = (matches)=>refreshedQueue.findIndex((item, index)=>!removedQueueIndices.has(index) && matches(item));
915
+ for (const batchItem of removedBatchItems){
916
+ let queueIndex = findQueueIndex((item)=>item === batchItem);
917
+ const uuid = batchItem.message?.uuid;
918
+ if (-1 === queueIndex && 'string' == typeof uuid && uuid.length > 0) queueIndex = findQueueIndex((item)=>item.message?.uuid === uuid);
919
+ if (-1 !== queueIndex) removedQueueIndices.add(queueIndex);
920
+ }
921
+ const newQueue = refreshedQueue.filter((_, index)=>!removedQueueIndices.has(index));
889
922
  this.setPersistedProperty(queueKey, newQueue);
890
923
  queue = newQueue;
891
- this._dequeuedMessagesCount += batchItems.length;
924
+ this._dequeuedMessagesCount += removedBatchItems.length;
892
925
  await this.flushStorage();
893
926
  };
894
927
  const retryOptions = {
@@ -897,11 +930,13 @@ class PostHogCoreStateless {
897
930
  return isPostHogFetchRetryableError(err);
898
931
  }
899
932
  };
933
+ let outcome;
900
934
  try {
901
- await this.sendBatch(batchMessages, retryOptions, route);
935
+ outcome = await this.sendBatch(batchMessages, retryOptions, route);
902
936
  } catch (err) {
903
937
  if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
904
938
  this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
939
+ this.batchSizeBeforeTimeout = void 0;
905
940
  this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
906
941
  continue;
907
942
  }
@@ -909,9 +944,31 @@ class PostHogCoreStateless {
909
944
  this._events.emit('error', err);
910
945
  throw err;
911
946
  }
947
+ const keepIndices = outcome ? new Set(outcome.keepIndices) : void 0;
948
+ if (outcome?.tooLarge && keepIndices && keepIndices.size > 1) {
949
+ if (keepIndices.size < batchMessages.length) await persistQueueChange(keepIndices);
950
+ this.maxBatchSize = Math.max(1, Math.floor(keepIndices.size / 2));
951
+ this.batchSizeBeforeTimeout = void 0;
952
+ this._logger.warn(`Received 413 when sending batch of size ${keepIndices.size}, reducing batch size to ${this.maxBatchSize}`);
953
+ continue;
954
+ }
955
+ if (keepIndices && keepIndices.size > 0) {
956
+ if (outcome?.timedOut && keepIndices.size > 1) {
957
+ this.batchSizeBeforeTimeout ??= this.maxBatchSize;
958
+ this.maxBatchSize = Math.max(1, Math.floor(keepIndices.size / 2));
959
+ this._logger.warn(`Request timed out when sending batch of size ${keepIndices.size}, reducing batch size to ${this.maxBatchSize}`);
960
+ }
961
+ await persistQueueChange(keepIndices);
962
+ sentMessages.push(...batchMessages.filter((_, index)=>!keepIndices.has(index)));
963
+ return;
964
+ }
912
965
  await persistQueueChange();
913
966
  sentMessages.push(...batchMessages);
914
967
  sentFromRoute += batchMessages.length;
968
+ if (void 0 !== this.batchSizeBeforeTimeout) {
969
+ this.maxBatchSize = Math.min(this.batchSizeBeforeTimeout, 2 * this.maxBatchSize);
970
+ if (this.maxBatchSize >= this.batchSizeBeforeTimeout) this.batchSizeBeforeTimeout = void 0;
971
+ }
915
972
  }
916
973
  }
917
974
  async _sendOtlpBatch({ path, auth, payload }) {
@@ -1096,6 +1153,7 @@ class PostHogCoreStateless {
1096
1153
  async _shutdown(shutdownTimeoutMs = 30000) {
1097
1154
  await this._initPromise;
1098
1155
  let hasTimedOut = false;
1156
+ const deadline = Date.now() + shutdownTimeoutMs;
1099
1157
  this.clearFlushTimer();
1100
1158
  if (this.disabled) return;
1101
1159
  const doShutdown = async ()=>{
@@ -1104,6 +1162,16 @@ class PostHogCoreStateless {
1104
1162
  while(true){
1105
1163
  const hasQueuedEvents = this.getActiveQueueRoutes().some((route)=>this.getRouteQueue(route).length > 0);
1106
1164
  if (!hasQueuedEvents) break;
1165
+ const holdMs = this.flushHoldMs();
1166
+ if (holdMs > 0) {
1167
+ if (Date.now() + holdMs >= deadline) {
1168
+ this._logger.warn('Shutdown stopped draining: the endpoint asked to wait past the shutdown timeout.');
1169
+ break;
1170
+ }
1171
+ await new Promise((resolve)=>(0, index_js_namespaceObject.safeSetTimeout)(resolve, holdMs));
1172
+ if (hasTimedOut) break;
1173
+ continue;
1174
+ }
1107
1175
  const dequeuedBeforeFlush = this._dequeuedMessagesCount;
1108
1176
  await this.flush();
1109
1177
  if (hasTimedOut) break;
@@ -1,4 +1,5 @@
1
1
  import { SimpleEventEmitter } from "./eventemitter.mjs";
2
+ import { EVENT_OPTION_LEGACY_PROPERTIES } from "./event-options.mjs";
2
3
  import { getFeatureFlagValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse } from "./featureFlagUtils.mjs";
3
4
  import { gzipCompress, isGzipSupported } from "./gzip.mjs";
4
5
  import { PostHogPersistedProperty } from "./types.mjs";
@@ -71,6 +72,7 @@ class PostHogFetchNetworkError extends Error {
71
72
  } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';
72
73
  }
73
74
  }
75
+ const FLAG_CALLED_OPTION_PROPERTIES = Object.values(EVENT_OPTION_LEGACY_PROPERTIES);
74
76
  const maybeAdd = (key, value)=>void 0 !== value ? {
75
77
  [key]: value
76
78
  } : {};
@@ -194,7 +196,7 @@ class PostHogCoreStateless {
194
196
  this._isInitialized = true;
195
197
  this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;
196
198
  if (options?.evaluationEnvironments && !options?.evaluationContexts) this._logger.warn('evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.');
197
- this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
199
+ this.disableCompression = !this.isCompressionAvailable() || (options?.disableCompression ?? false);
198
200
  }
199
201
  logMsgIfDebug(fn) {
200
202
  if (this.isDebug) fn();
@@ -249,7 +251,7 @@ class PostHogCoreStateless {
249
251
  const userProperties = payload.properties || {};
250
252
  let properties = this.mergeCommonEventProperties(userProperties);
251
253
  applyCallerFeatureFlagOverrides(properties, userProperties);
252
- if ('$feature_flag_called' === payload.event && false === properties.$feature_flag_has_experiment && this.isMinimalFlagCalledEventsEnabled()) properties = minimizeFlagCalledEventProperties(properties);
254
+ if ('$feature_flag_called' === payload.event && false === properties.$feature_flag_has_experiment && this.isMinimalFlagCalledEventsEnabled()) properties = minimizeFlagCalledEventProperties(properties, FLAG_CALLED_OPTION_PROPERTIES);
253
255
  return {
254
256
  distinct_id: payload.distinct_id,
255
257
  event: payload.event,
@@ -653,6 +655,23 @@ class PostHogCoreStateless {
653
655
  this._events.emit('error', err);
654
656
  }
655
657
  }
658
+ batchByteTarget() {}
659
+ batchEventBytes(_message) {
660
+ return 0;
661
+ }
662
+ resendBatchSize(_messages) {}
663
+ countWithinBatchByteTarget(messages) {
664
+ const target = this.batchByteTarget();
665
+ if (void 0 === target) return messages.length;
666
+ let total = 0;
667
+ for(let index = 0; index < messages.length; index++){
668
+ const message = messages[index];
669
+ const bytes = void 0 === message ? 0 : this.batchEventBytes(message);
670
+ if (index > 0 && total + bytes > target) return index;
671
+ total += bytes;
672
+ }
673
+ return messages.length;
674
+ }
656
675
  normalizeMessage(message) {
657
676
  const { type: _type, library, library_version, ...sanitizedMessage } = message;
658
677
  let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : void 0;
@@ -665,7 +684,7 @@ class PostHogCoreStateless {
665
684
  $lib_version: library_version
666
685
  };
667
686
  if (properties) sanitizedMessage.properties = properties;
668
- sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
687
+ sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, ()=>this.generateEventUuid());
669
688
  return sanitizedMessage;
670
689
  }
671
690
  normalizeTimestampForWire(timestamp) {
@@ -675,11 +694,14 @@ class PostHogCoreStateless {
675
694
  const fractionalSeconds = 'string' == typeof timestamp ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : void 0;
676
695
  return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
677
696
  }
697
+ generateEventUuid() {
698
+ return uuidv7();
699
+ }
678
700
  prepareMessage(_message, options) {
679
701
  const message = {
680
702
  ..._message,
681
703
  timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
682
- uuid: getEventUuid(options?.uuid, uuidv7)
704
+ uuid: getEventUuid(options?.uuid, ()=>this.generateEventUuid())
683
705
  };
684
706
  const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
685
707
  if (addGeoipDisableProperty) {
@@ -707,6 +729,9 @@ class PostHogCoreStateless {
707
729
  flushAutomatic() {
708
730
  return this.flush();
709
731
  }
732
+ flushHoldMs() {
733
+ return 0;
734
+ }
710
735
  async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
711
736
  const ignoredPendingPromises = ignoredPromises.filter((promise)=>!!promise);
712
737
  let iteration = 0;
@@ -741,6 +766,7 @@ class PostHogCoreStateless {
741
766
  previousFlushPromise
742
767
  ])).then(()=>{
743
768
  if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;
769
+ if (this.flushHoldMs() > 0) return;
744
770
  return this._flush();
745
771
  });
746
772
  this.pendingFlushPromise = nextFlushPromise;
@@ -762,6 +788,9 @@ class PostHogCoreStateless {
762
788
  if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;
763
789
  return headers;
764
790
  }
791
+ isCompressionAvailable() {
792
+ return isGzipSupported();
793
+ }
765
794
  compressPayload(payload) {
766
795
  return gzipCompress(payload, this.isDebug);
767
796
  }
@@ -834,23 +863,27 @@ class PostHogCoreStateless {
834
863
  const originalQueueLength = queue.length;
835
864
  let sentFromRoute = 0;
836
865
  while(queue.length > 0 && sentFromRoute < originalQueueLength){
837
- const batchItems = queue.slice(0, this.maxBatchSize);
838
- const batchMessages = batchItems.map((item)=>void 0 === item.message ? item.message : this.normalizeMessage(item.message));
839
- const persistQueueChange = async ()=>{
866
+ const countItems = queue.slice(0, this.maxBatchSize);
867
+ const countMessages = countItems.map((item)=>void 0 === item.message ? item.message : this.normalizeMessage(item.message));
868
+ const batchSize = Math.min(this.countWithinBatchByteTarget(countMessages), this.resendBatchSize(countMessages) ?? countMessages.length);
869
+ const batchItems = countItems.slice(0, batchSize);
870
+ const batchMessages = countMessages.slice(0, batchSize);
871
+ const persistQueueChange = async (keepIndices)=>{
872
+ const removedBatchItems = keepIndices ? batchItems.filter((_, index)=>!keepIndices.has(index)) : batchItems;
873
+ if (0 === removedBatchItems.length) return void await this.flushStorage();
840
874
  const refreshedQueue = this.getPersistedProperty(queueKey) || [];
841
- const remainingBatchItems = [
842
- ...batchItems
843
- ];
844
- const newQueue = refreshedQueue.filter((item)=>{
845
- const itemUuid = item.message?.uuid;
846
- const batchItemIndex = remainingBatchItems.findIndex((batchItem)=>batchItem === item || 'string' == typeof itemUuid && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
847
- if (-1 === batchItemIndex) return true;
848
- remainingBatchItems.splice(batchItemIndex, 1);
849
- return false;
850
- });
875
+ const removedQueueIndices = new Set();
876
+ const findQueueIndex = (matches)=>refreshedQueue.findIndex((item, index)=>!removedQueueIndices.has(index) && matches(item));
877
+ for (const batchItem of removedBatchItems){
878
+ let queueIndex = findQueueIndex((item)=>item === batchItem);
879
+ const uuid = batchItem.message?.uuid;
880
+ if (-1 === queueIndex && 'string' == typeof uuid && uuid.length > 0) queueIndex = findQueueIndex((item)=>item.message?.uuid === uuid);
881
+ if (-1 !== queueIndex) removedQueueIndices.add(queueIndex);
882
+ }
883
+ const newQueue = refreshedQueue.filter((_, index)=>!removedQueueIndices.has(index));
851
884
  this.setPersistedProperty(queueKey, newQueue);
852
885
  queue = newQueue;
853
- this._dequeuedMessagesCount += batchItems.length;
886
+ this._dequeuedMessagesCount += removedBatchItems.length;
854
887
  await this.flushStorage();
855
888
  };
856
889
  const retryOptions = {
@@ -859,11 +892,13 @@ class PostHogCoreStateless {
859
892
  return isPostHogFetchRetryableError(err);
860
893
  }
861
894
  };
895
+ let outcome;
862
896
  try {
863
- await this.sendBatch(batchMessages, retryOptions, route);
897
+ outcome = await this.sendBatch(batchMessages, retryOptions, route);
864
898
  } catch (err) {
865
899
  if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
866
900
  this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
901
+ this.batchSizeBeforeTimeout = void 0;
867
902
  this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
868
903
  continue;
869
904
  }
@@ -871,9 +906,31 @@ class PostHogCoreStateless {
871
906
  this._events.emit('error', err);
872
907
  throw err;
873
908
  }
909
+ const keepIndices = outcome ? new Set(outcome.keepIndices) : void 0;
910
+ if (outcome?.tooLarge && keepIndices && keepIndices.size > 1) {
911
+ if (keepIndices.size < batchMessages.length) await persistQueueChange(keepIndices);
912
+ this.maxBatchSize = Math.max(1, Math.floor(keepIndices.size / 2));
913
+ this.batchSizeBeforeTimeout = void 0;
914
+ this._logger.warn(`Received 413 when sending batch of size ${keepIndices.size}, reducing batch size to ${this.maxBatchSize}`);
915
+ continue;
916
+ }
917
+ if (keepIndices && keepIndices.size > 0) {
918
+ if (outcome?.timedOut && keepIndices.size > 1) {
919
+ this.batchSizeBeforeTimeout ??= this.maxBatchSize;
920
+ this.maxBatchSize = Math.max(1, Math.floor(keepIndices.size / 2));
921
+ this._logger.warn(`Request timed out when sending batch of size ${keepIndices.size}, reducing batch size to ${this.maxBatchSize}`);
922
+ }
923
+ await persistQueueChange(keepIndices);
924
+ sentMessages.push(...batchMessages.filter((_, index)=>!keepIndices.has(index)));
925
+ return;
926
+ }
874
927
  await persistQueueChange();
875
928
  sentMessages.push(...batchMessages);
876
929
  sentFromRoute += batchMessages.length;
930
+ if (void 0 !== this.batchSizeBeforeTimeout) {
931
+ this.maxBatchSize = Math.min(this.batchSizeBeforeTimeout, 2 * this.maxBatchSize);
932
+ if (this.maxBatchSize >= this.batchSizeBeforeTimeout) this.batchSizeBeforeTimeout = void 0;
933
+ }
877
934
  }
878
935
  }
879
936
  async _sendOtlpBatch({ path, auth, payload }) {
@@ -1058,6 +1115,7 @@ class PostHogCoreStateless {
1058
1115
  async _shutdown(shutdownTimeoutMs = 30000) {
1059
1116
  await this._initPromise;
1060
1117
  let hasTimedOut = false;
1118
+ const deadline = Date.now() + shutdownTimeoutMs;
1061
1119
  this.clearFlushTimer();
1062
1120
  if (this.disabled) return;
1063
1121
  const doShutdown = async ()=>{
@@ -1066,6 +1124,16 @@ class PostHogCoreStateless {
1066
1124
  while(true){
1067
1125
  const hasQueuedEvents = this.getActiveQueueRoutes().some((route)=>this.getRouteQueue(route).length > 0);
1068
1126
  if (!hasQueuedEvents) break;
1127
+ const holdMs = this.flushHoldMs();
1128
+ if (holdMs > 0) {
1129
+ if (Date.now() + holdMs >= deadline) {
1130
+ this._logger.warn('Shutdown stopped draining: the endpoint asked to wait past the shutdown timeout.');
1131
+ break;
1132
+ }
1133
+ await new Promise((resolve)=>safeSetTimeout(resolve, holdMs));
1134
+ if (hasTimedOut) break;
1135
+ continue;
1136
+ }
1069
1137
  const dequeuedBeforeFlush = this._dequeuedMessagesCount;
1070
1138
  await this.flush();
1071
1139
  if (hasTimedOut) break;