posthog-node 5.74.0 → 6.0.1

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 (144) hide show
  1. package/MIGRATION.md +556 -0
  2. package/README.md +3 -1
  3. package/dist/ai-capture/routing.d.ts +0 -3
  4. package/dist/ai-capture/routing.d.ts.map +1 -1
  5. package/dist/ai-capture/routing.js +2 -14
  6. package/dist/ai-capture/routing.mjs +1 -4
  7. package/dist/capture-lane/lane.d.ts +109 -0
  8. package/dist/capture-lane/lane.d.ts.map +1 -0
  9. package/dist/capture-lane/lane.js +308 -0
  10. package/dist/capture-lane/lane.mjs +270 -0
  11. package/dist/capture-lane/limits.d.ts +7 -0
  12. package/dist/capture-lane/limits.d.ts.map +1 -0
  13. package/dist/{capture-v1/config.js → capture-lane/limits.js} +13 -11
  14. package/dist/capture-lane/limits.mjs +4 -0
  15. package/dist/capture-lane/settings.d.ts +30 -0
  16. package/dist/capture-lane/settings.d.ts.map +1 -0
  17. package/dist/capture-lane/settings.js +100 -0
  18. package/dist/capture-lane/settings.mjs +47 -0
  19. package/dist/capture-v1/compression.d.ts +18 -0
  20. package/dist/capture-v1/compression.d.ts.map +1 -0
  21. package/dist/capture-v1/compression.js +70 -0
  22. package/dist/capture-v1/compression.mjs +26 -0
  23. package/dist/capture-v1/errors.d.ts +23 -7
  24. package/dist/capture-v1/errors.d.ts.map +1 -1
  25. package/dist/capture-v1/errors.js +37 -8
  26. package/dist/capture-v1/errors.mjs +29 -6
  27. package/dist/capture-v1/sender.d.ts +63 -23
  28. package/dist/capture-v1/sender.d.ts.map +1 -1
  29. package/dist/capture-v1/sender.js +281 -74
  30. package/dist/capture-v1/sender.mjs +275 -77
  31. package/dist/capture-v1/serialize.d.ts +28 -0
  32. package/dist/capture-v1/serialize.d.ts.map +1 -0
  33. package/dist/capture-v1/serialize.js +82 -0
  34. package/dist/capture-v1/serialize.mjs +38 -0
  35. package/dist/capture-v1/transform.d.ts +10 -25
  36. package/dist/capture-v1/transform.d.ts.map +1 -1
  37. package/dist/capture-v1/transform.js +33 -64
  38. package/dist/capture-v1/transform.mjs +28 -53
  39. package/dist/capture-v1/types.d.ts +16 -14
  40. package/dist/capture-v1/types.d.ts.map +1 -1
  41. package/dist/capture-v1/types.js +27 -1
  42. package/dist/capture-v1/types.mjs +3 -1
  43. package/dist/capture-v1/uuid.d.ts +9 -0
  44. package/dist/capture-v1/uuid.d.ts.map +1 -0
  45. package/dist/capture-v1/uuid.js +75 -0
  46. package/dist/capture-v1/uuid.mjs +34 -0
  47. package/dist/client.d.ts +203 -96
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +456 -228
  50. package/dist/client.mjs +455 -227
  51. package/dist/compression.node.d.ts +13 -0
  52. package/dist/compression.node.d.ts.map +1 -0
  53. package/dist/{capture-v1/routing.js → compression.node.js} +23 -16
  54. package/dist/compression.node.mjs +18 -0
  55. package/dist/entrypoints/index.node.d.ts +2 -0
  56. package/dist/entrypoints/index.node.d.ts.map +1 -1
  57. package/dist/entrypoints/index.node.js +11 -4
  58. package/dist/entrypoints/index.node.mjs +4 -0
  59. package/dist/event-defaults.d.ts +46 -0
  60. package/dist/event-defaults.d.ts.map +1 -0
  61. package/dist/event-defaults.js +141 -0
  62. package/dist/event-defaults.mjs +79 -0
  63. package/dist/exports.d.ts +3 -0
  64. package/dist/exports.d.ts.map +1 -1
  65. package/dist/exports.js +22 -11
  66. package/dist/exports.mjs +1 -0
  67. package/dist/extensions/context/context.d.ts +0 -1
  68. package/dist/extensions/context/context.d.ts.map +1 -1
  69. package/dist/extensions/context/context.js +4 -3
  70. package/dist/extensions/context/context.mjs +4 -3
  71. package/dist/extensions/context/event-context.d.ts.map +1 -1
  72. package/dist/extensions/context/event-context.js +3 -0
  73. package/dist/extensions/context/event-context.mjs +3 -0
  74. package/dist/extensions/context/types.d.ts +9 -1
  75. package/dist/extensions/context/types.d.ts.map +1 -1
  76. package/dist/extensions/error-tracking/index.d.ts +1 -1
  77. package/dist/extensions/error-tracking/index.d.ts.map +1 -1
  78. package/dist/extensions/error-tracking/index.js +71 -7
  79. package/dist/extensions/error-tracking/index.mjs +75 -11
  80. package/dist/extensions/express.d.ts +8 -0
  81. package/dist/extensions/express.d.ts.map +1 -1
  82. package/dist/extensions/express.js +3 -3
  83. package/dist/extensions/express.mjs +4 -4
  84. package/dist/extensions/fetch-request.d.ts.map +1 -1
  85. package/dist/extensions/fetch-request.js +2 -2
  86. package/dist/extensions/fetch-request.mjs +3 -3
  87. package/dist/extensions/nestjs.d.ts.map +1 -1
  88. package/dist/extensions/nestjs.js +7 -4
  89. package/dist/extensions/nestjs.mjs +8 -5
  90. package/dist/extensions/tracing-headers.d.ts +7 -0
  91. package/dist/extensions/tracing-headers.d.ts.map +1 -1
  92. package/dist/extensions/tracing-headers.js +11 -1
  93. package/dist/extensions/tracing-headers.mjs +9 -2
  94. package/dist/flag-events.d.ts +1 -1
  95. package/dist/flag-events.d.ts.map +1 -1
  96. package/dist/flag-events.js +2 -2
  97. package/dist/flag-events.mjs +2 -2
  98. package/dist/types.d.ts +191 -27
  99. package/dist/types.d.ts.map +1 -1
  100. package/dist/version.d.ts +1 -1
  101. package/dist/version.d.ts.map +1 -1
  102. package/dist/version.js +1 -1
  103. package/dist/version.mjs +1 -1
  104. package/package.json +3 -2
  105. package/src/ai-capture/routing.ts +0 -6
  106. package/src/capture-lane/lane.ts +414 -0
  107. package/src/capture-lane/limits.ts +8 -0
  108. package/src/capture-lane/settings.ts +119 -0
  109. package/src/capture-v1/compression.ts +50 -0
  110. package/src/capture-v1/errors.ts +50 -11
  111. package/src/capture-v1/sender.ts +405 -111
  112. package/src/capture-v1/serialize.ts +77 -0
  113. package/src/capture-v1/transform.ts +59 -92
  114. package/src/capture-v1/types.ts +19 -15
  115. package/src/capture-v1/uuid.ts +53 -0
  116. package/src/client.ts +847 -424
  117. package/src/compression.node.ts +30 -0
  118. package/src/entrypoints/index.node.ts +6 -0
  119. package/src/event-defaults.ts +177 -0
  120. package/src/exports.ts +3 -0
  121. package/src/extensions/context/context.ts +4 -4
  122. package/src/extensions/context/event-context.ts +3 -1
  123. package/src/extensions/context/types.ts +10 -1
  124. package/src/extensions/error-tracking/index.ts +51 -7
  125. package/src/extensions/express.ts +12 -3
  126. package/src/extensions/fetch-request.ts +7 -3
  127. package/src/extensions/nestjs.ts +9 -5
  128. package/src/extensions/tracing-headers.ts +26 -7
  129. package/src/flag-events.ts +5 -2
  130. package/src/types.ts +211 -44
  131. package/src/version.ts +1 -1
  132. package/dist/ai-capture/batching.d.ts +0 -11
  133. package/dist/ai-capture/batching.d.ts.map +0 -1
  134. package/dist/ai-capture/batching.js +0 -77
  135. package/dist/ai-capture/batching.mjs +0 -36
  136. package/dist/capture-v1/config.d.ts +0 -11
  137. package/dist/capture-v1/config.d.ts.map +0 -1
  138. package/dist/capture-v1/config.mjs +0 -8
  139. package/dist/capture-v1/routing.d.ts +0 -21
  140. package/dist/capture-v1/routing.d.ts.map +0 -1
  141. package/dist/capture-v1/routing.mjs +0 -7
  142. package/src/ai-capture/batching.ts +0 -47
  143. package/src/capture-v1/config.ts +0 -18
  144. package/src/capture-v1/routing.ts +0 -28
package/dist/client.js CHANGED
@@ -51,13 +51,18 @@ const index_js_namespaceObject = require("./extensions/error-tracking/index.js")
51
51
  var index_js_default = /*#__PURE__*/ __webpack_require__.n(index_js_namespaceObject);
52
52
  const trace_context_js_namespaceObject = require("./extensions/error-tracking/trace-context.js");
53
53
  const external_storage_memory_js_namespaceObject = require("./storage-memory.js");
54
+ const sender_js_namespaceObject = require("./capture-v1/sender.js");
55
+ const types_js_namespaceObject = require("./capture-v1/types.js");
56
+ const lane_js_namespaceObject = require("./capture-lane/lane.js");
57
+ const limits_js_namespaceObject = require("./capture-lane/limits.js");
58
+ const settings_js_namespaceObject = require("./capture-lane/settings.js");
59
+ const compression_js_namespaceObject = require("./capture-v1/compression.js");
60
+ const uuid_js_namespaceObject = require("./capture-v1/uuid.js");
61
+ const transform_js_namespaceObject = require("./capture-v1/transform.js");
62
+ const external_event_defaults_js_namespaceObject = require("./event-defaults.js");
63
+ const routing_js_namespaceObject = require("./ai-capture/routing.js");
54
64
  const listeners_js_namespaceObject = require("./extensions/context/listeners.js");
55
65
  const event_context_js_namespaceObject = require("./extensions/context/event-context.js");
56
- const config_js_namespaceObject = require("./capture-v1/config.js");
57
- const routing_js_namespaceObject = require("./capture-v1/routing.js");
58
- const sender_js_namespaceObject = require("./capture-v1/sender.js");
59
- const batching_js_namespaceObject = require("./ai-capture/batching.js");
60
- const external_ai_capture_routing_js_namespaceObject = require("./ai-capture/routing.js");
61
66
  const emails_js_namespaceObject = require("./emails/emails.js");
62
67
  const external_logs_config_js_namespaceObject = require("./logs-config.js");
63
68
  const MINIMUM_POLLING_INTERVAL = 100;
@@ -67,10 +72,10 @@ const WAITUNTIL_DEBOUNCE_MS = 50;
67
72
  const WAITUNTIL_MAX_WAIT_MS = 500;
68
73
  const DEFAULT_NODE_HOST = 'https://us.i.posthog.com';
69
74
  const _emittedDeprecations = new Set();
70
- function emitDeprecationWarningOnce(id, message) {
75
+ function emitDeprecationWarningOnce(id, message, log = console.warn) {
71
76
  if (_emittedDeprecations.has(id)) return;
72
77
  _emittedDeprecations.add(id);
73
- console.warn(`[PostHog] ${message}`);
78
+ log(`[PostHog] ${message}`);
74
79
  }
75
80
  function _resetDeprecationWarningsForTests() {
76
81
  _emittedDeprecations.clear();
@@ -78,14 +83,122 @@ function _resetDeprecationWarningsForTests() {
78
83
  function normalizeApiKey(value) {
79
84
  return 'string' == typeof value ? value.trim() : '';
80
85
  }
86
+ function apiKeyProblem(apiKey) {
87
+ if (!apiKey) return 'No project API key was passed';
88
+ if (apiKey.startsWith('phx_')) return 'A personal API key ("phx_...") was passed where the project API key ("phc_...") belongs';
89
+ }
90
+ function summarizeForDebugLog(payload) {
91
+ if (Array.isArray(payload)) return `${payload.length} item(s)`;
92
+ if (payload instanceof Error) return `${payload.name}: ${payload.message}`;
93
+ if (payload && 'object' == typeof payload && 'string' == typeof payload.event) {
94
+ const { event, uuid } = payload;
95
+ return void 0 === uuid ? {
96
+ event
97
+ } : {
98
+ event,
99
+ uuid
100
+ };
101
+ }
102
+ }
81
103
  function normalizePersonalApiKey(value) {
82
104
  const normalizedValue = 'string' == typeof value ? value.trim() : '';
83
105
  return normalizedValue || void 0;
84
106
  }
107
+ function isUnsetUuid(uuid) {
108
+ return null == uuid || '' === uuid;
109
+ }
110
+ function isInvalidUuid(uuid) {
111
+ return !isUnsetUuid(uuid) && ('string' != typeof uuid || void 0 === (0, uuid_js_namespaceObject.canonicalizeUuid)(uuid));
112
+ }
85
113
  function normalizeHost(value) {
86
114
  const normalizedValue = 'string' == typeof value ? value.trim() : '';
87
115
  return normalizedValue || DEFAULT_NODE_HOST;
88
116
  }
117
+ const FLAG_CALLED_OPTION_SOURCE_PROPERTIES = [
118
+ '$cookieless_mode',
119
+ '$ignore_sent_at',
120
+ '$product_tour_id',
121
+ '$process_person_profile',
122
+ '$session_id',
123
+ '$window_id'
124
+ ];
125
+ function readCaptureExceptionArgs(method, second, rest, legacyHasUuid) {
126
+ if ('string' != typeof second && (0 === rest.length || (0, core_namespaceObject.isPlainObject)(second))) {
127
+ if (rest.length > 0) emitDeprecationWarningOnce(`${method} extra arguments`, `${method}(error, options) ignores the arguments after the options object.`);
128
+ return (0, core_namespaceObject.isPlainObject)(second) ? second : {};
129
+ }
130
+ emitDeprecationWarningOnce(`${method} positional arguments`, `${method}(error, distinctId, properties) is deprecated: pass an object instead, e.g. ${method}(error, { distinctId, properties }). The old form will be removed in the next major version.`, console.error);
131
+ const [properties, ...tail] = rest;
132
+ const [uuid, flags] = legacyHasUuid ? tail : [
133
+ void 0,
134
+ tail[0]
135
+ ];
136
+ return {
137
+ distinctId: second ?? void 0,
138
+ properties: properties,
139
+ uuid: uuid,
140
+ flags: flags
141
+ };
142
+ }
143
+ class UnreadableEventError extends Error {
144
+ constructor(original){
145
+ super('A value in the event threw while it was read'), this.original = original;
146
+ }
147
+ }
148
+ function readCallerValues(read) {
149
+ try {
150
+ return read();
151
+ } catch (error) {
152
+ throw new UnreadableEventError(error);
153
+ }
154
+ }
155
+ function isolateForBeforeSend(eventMessage) {
156
+ const isolated = copyPlainValues(eventMessage, new WeakMap());
157
+ isolated.options ??= {};
158
+ return isolated;
159
+ }
160
+ function isPlainRecord(value) {
161
+ if (null === value || 'object' != typeof value) return false;
162
+ const prototype = Object.getPrototypeOf(value);
163
+ return prototype === Object.prototype || null === prototype;
164
+ }
165
+ function copyPlainValues(value, seen) {
166
+ if (!Array.isArray(value) && !isPlainRecord(value)) return value;
167
+ const known = seen.get(value);
168
+ if (void 0 !== known) return known;
169
+ if (Array.isArray(value)) {
170
+ const copy = new Array(value.length);
171
+ seen.set(value, copy);
172
+ value.forEach((item, index)=>{
173
+ copy[index] = copyPlainValues(item, seen);
174
+ });
175
+ return copy;
176
+ }
177
+ const copy = null === Object.getPrototypeOf(value) ? Object.create(null) : {};
178
+ seen.set(value, copy);
179
+ for (const key of Object.keys(value))copy[key] = copyPlainValues(value[key], seen);
180
+ return copy;
181
+ }
182
+ function identifyEventProperties(properties) {
183
+ const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
184
+ return {
185
+ $set: $set || rest,
186
+ ...null != $set_once ? {
187
+ $set_once
188
+ } : {},
189
+ $anon_distinct_id: $anon_distinct_id ?? void 0
190
+ };
191
+ }
192
+ const ALIAS_PREPARE_OPTIONS = {
193
+ callOnlyProperties: [
194
+ 'alias'
195
+ ],
196
+ distinctIdProperty: true
197
+ };
198
+ function presentDistinctId(value) {
199
+ if (null == value || 'string' == typeof value && '' === value.trim()) return;
200
+ return 'string' == typeof value ? value : String(value);
201
+ }
89
202
  function positiveNumberOr(value, fallback) {
90
203
  return 'number' == typeof value && Number.isFinite(value) && value > 0 ? value : fallback;
91
204
  }
@@ -115,16 +228,20 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
115
228
  }
116
229
  constructor(apiKey, options = {}){
117
230
  const normalizedApiKey = normalizeApiKey(apiKey);
231
+ const keyProblem = apiKeyProblem(normalizedApiKey);
118
232
  const normalizedOptions = {
119
233
  ...options,
234
+ disabled: options.disabled || void 0 !== keyProblem,
120
235
  maxQueueSize: options.maxQueueSize ?? 10000,
121
236
  flushInterval: options.flushInterval ?? 5000,
122
237
  host: normalizeHost(options.host),
123
238
  personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)
124
239
  };
125
- super(normalizedApiKey, normalizedOptions), this._memoryStorage = new external_storage_memory_js_namespaceObject.PostHogMemoryStorage(), this._isShutdown = false, this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false, this._loggedFlagsResponseWithoutTypedValues = false, this._experimentExposuresReported = new Map();
240
+ super(normalizedApiKey, normalizedOptions), this._memoryStorage = new external_storage_memory_js_namespaceObject.PostHogMemoryStorage(), this._captureLanes = new Map(), this._isShutdown = false, this._globalOptions = {}, this._minimalFlagCalledEvents = false, this._loggedFlagsResponseWithoutTypedValues = false, this._experimentExposuresReported = new Map();
126
241
  this.options = normalizedOptions;
127
- this.captureMode = (0, config_js_namespaceObject.resolveCaptureMode)();
242
+ if (keyProblem) console.error(`[PostHog] ${keyProblem}, so the client is disabled.`);
243
+ this.warnIfCaptureModeSet();
244
+ this._captureSettings = (0, settings_js_namespaceObject.resolveCaptureSettings)(normalizedOptions, (message)=>console.error(`[PostHog] ${message}`));
128
245
  this.enableFullAiCapture = true === normalizedOptions.enableFullAiCapture;
129
246
  this.privacyMode = true === normalizedOptions.privacyMode;
130
247
  this.context = this.initializeContext();
@@ -161,11 +278,45 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
161
278
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
162
279
  }
163
280
  enqueue(type, message, options, explicitRoute) {
164
- super.enqueue(type, message, options, explicitRoute);
281
+ this.wrap(()=>{
282
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
283
+ const prepared = this._prepareLaneMessage(message, options);
284
+ if (null === prepared) return;
285
+ this._captureLane(explicitRoute).enqueue(prepared);
286
+ this._events.emit(type, prepared);
287
+ });
165
288
  this.scheduleDebouncedFlush();
166
289
  }
290
+ async sendImmediate(type, message, options, explicitRoute) {
291
+ if (this.disabled) return void this._logger.warn('The client is disabled');
292
+ if (!this._isInitialized) await this._initPromise;
293
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
294
+ const prepared = this._prepareLaneMessage(message, options);
295
+ if (null === prepared) return;
296
+ try {
297
+ await this._captureLane(explicitRoute).sendImmediate(prepared);
298
+ } catch (err) {
299
+ this._events.emit('error', err);
300
+ }
301
+ }
302
+ _prepareLaneMessage(message, options) {
303
+ const { _invalidUuidWarned, ...captureOptions } = options ?? {};
304
+ const uuid = this._canonicalEventUuid(captureOptions.uuid, !_invalidUuidWarned) ?? (0, uuid_js_namespaceObject.eventUuidv7)();
305
+ const prepared = this.processBeforeEnqueue(this.prepareMessage(message, {
306
+ ...captureOptions,
307
+ uuid
308
+ }));
309
+ return null === prepared ? null : this.normalizeMessage(prepared);
310
+ }
311
+ _canonicalEventUuid(uuid, warnIfInvalid = true) {
312
+ if (isUnsetUuid(uuid)) return;
313
+ const canonical = 'string' == typeof uuid ? (0, uuid_js_namespaceObject.canonicalizeUuid)(uuid) : void 0;
314
+ if (void 0 !== canonical) return canonical;
315
+ if (warnIfInvalid) console.warn('[PostHog] Replaced an invalid event uuid with a generated one; uuids must be RFC 4122 strings');
316
+ return (0, uuid_js_namespaceObject.eventUuidv7)();
317
+ }
167
318
  _flushEventsAndSpans(skipThrottledSpans = false) {
168
- const events = this.flushWithPendingPromises();
319
+ const events = this.flushWithPendingPromises().then(()=>this._flushCaptureLanes());
169
320
  const others = [];
170
321
  if (this._traces && !(skipThrottledSpans && this._traces.throttled)) others.push(this._traces.flush().catch(()=>{}));
171
322
  if (this._logs && !(skipThrottledSpans && this._logs.throttled)) others.push(this._logs.flushInBackground());
@@ -177,15 +328,24 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
177
328
  if ('rejected' === eventsResult.status) throw eventsResult.reason;
178
329
  });
179
330
  }
180
- flushAutomatic() {
181
- return this._flushKeepingRuntimeAlive(true);
182
- }
183
331
  async flush() {
184
332
  this.errorTracking.capturePendingExceptions();
185
- return this._flushKeepingRuntimeAlive(false);
186
- }
187
- _flushKeepingRuntimeAlive(skipThrottledSpans) {
188
- const flushPromise = this._flushEventsAndSpans(skipThrottledSpans);
333
+ return this._keepRuntimeAlive(this._flushEventsAndSpans());
334
+ }
335
+ _flushCaptureLanes() {
336
+ return Promise.all([
337
+ ...this._captureLanes.values()
338
+ ].map((lane)=>lane.flush())).then(()=>{});
339
+ }
340
+ _onLaneBackgroundFlush(laneFlush) {
341
+ const traces = this._traces;
342
+ const flush = traces && !traces.throttled ? (0, core_namespaceObject.allSettled)([
343
+ laneFlush,
344
+ traces.flush().catch(()=>{})
345
+ ]).then(()=>{}) : laneFlush;
346
+ this._keepRuntimeAlive(flush);
347
+ }
348
+ _keepRuntimeAlive(flushPromise) {
189
349
  const waitUntil = this.options.waitUntil;
190
350
  if (waitUntil && !this._waitUntilCycle) try {
191
351
  waitUntil(flushPromise.catch(()=>{}));
@@ -254,78 +414,71 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
254
414
  fetch(url, options) {
255
415
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
256
416
  }
257
- getQueueRouteKey(message) {
258
- return 'v1' === this.captureMode && (0, routing_js_namespaceObject.isLegacyOnlyEvent)(message) ? routing_js_namespaceObject.AI_ROUTE : routing_js_namespaceObject.ANALYTICS_ROUTE;
417
+ _captureLane(route) {
418
+ const endpoint = route === routing_js_namespaceObject.AI_CAPTURE_ROUTE ? types_js_namespaceObject.AI_CAPTURE_ENDPOINT : types_js_namespaceObject.ANALYTICS_CAPTURE_ENDPOINT;
419
+ let lane = this._captureLanes.get(endpoint);
420
+ if (!lane) {
421
+ const compressor = this.captureCompressor();
422
+ lane = new lane_js_namespaceObject.CaptureLane(this._captureLaneConfig(endpoint), {
423
+ sender: new sender_js_namespaceObject.V1CaptureSender(this.captureSenderConfig(endpoint, compressor), {
424
+ fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),
425
+ onError: (error, summary)=>this._reportCaptureLoss([
426
+ error
427
+ ], summary),
428
+ compress: (payload, codec)=>compressor.compress(payload, codec)
429
+ }),
430
+ onLocalDrops: (errors, summary)=>this._reportCaptureLoss(errors, summary),
431
+ onError: (error)=>this._events.emit('error', error),
432
+ onFlush: (messages)=>this._events.emit('flush', messages),
433
+ onBackgroundFlush: (flush)=>this._onLaneBackgroundFlush(flush),
434
+ logger: this._logger
435
+ });
436
+ this._captureLanes.set(endpoint, lane);
437
+ }
438
+ return lane;
259
439
  }
260
- persistedQueueKeyForRoute(route) {
261
- if (route === external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE) return core_namespaceObject.PostHogPersistedProperty.AiCaptureQueue;
262
- return route === routing_js_namespaceObject.AI_ROUTE ? core_namespaceObject.PostHogPersistedProperty.AiQueue : core_namespaceObject.PostHogPersistedProperty.Queue;
440
+ _captureLaneConfig(endpoint) {
441
+ const isAi = endpoint === types_js_namespaceObject.AI_CAPTURE_ENDPOINT;
442
+ const flushAt = isAi ? Math.min(this.flushAt, this._captureSettings.ai.maxQueueSize) : this.flushAt;
443
+ return {
444
+ endpoint,
445
+ flushAt,
446
+ flushIntervalMs: this.options.flushInterval ?? 5000,
447
+ maxBatchSize: Math.max(flushAt, this.options.maxBatchSize ?? 100),
448
+ maxQueueSize: isAi ? this._captureSettings.ai.maxQueueSize : Math.max(this.flushAt, this.options.maxQueueSize ?? 10000),
449
+ targetBatchBytes: limits_js_namespaceObject.CAPTURE_BATCH_TARGET_BYTES,
450
+ maxEventBytes: isAi ? limits_js_namespaceObject.AI_MAX_PROPERTIES_BYTES : limits_js_namespaceObject.ANALYTICS_MAX_EVENT_BYTES,
451
+ maxEventBytesOf: isAi ? 'properties' : 'event'
452
+ };
263
453
  }
264
- getActiveQueueRoutes() {
265
- const routes = 'v1' === this.captureMode ? [
266
- routing_js_namespaceObject.ANALYTICS_ROUTE,
267
- routing_js_namespaceObject.AI_ROUTE
268
- ] : [
269
- routing_js_namespaceObject.ANALYTICS_ROUTE
270
- ];
271
- if (this._aiCaptureRouteActive) routes.push(external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE);
272
- return routes;
273
- }
274
- getBatchEndpointPath(route) {
275
- return route === external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE ? external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);
276
- }
277
- async sendBatch(batchMessages, retryOptions, route = routing_js_namespaceObject.ANALYTICS_ROUTE) {
278
- if (route === external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE) return this.sendAiCaptureBatch(batchMessages, retryOptions);
279
- if ('v1' !== this.captureMode || route === routing_js_namespaceObject.AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);
280
- const v1Events = batchMessages.filter((message)=>void 0 !== message);
281
- await this.getV1Sender().sendV1Batch(v1Events);
282
- }
283
- async sendAiCaptureBatch(batchMessages, retryOptions) {
284
- const { batches, dropped } = (0, batching_js_namespaceObject.partitionAiBatch)(batchMessages);
285
- for (const { event, bytes } of dropped){
286
- const message = `Event ${event} (${bytes} bytes) exceeds the ${external_ai_capture_routing_js_namespaceObject.AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ENDPOINT_PATH}, dropping.`;
287
- this._logger.error(message);
288
- this._events.emit('error', new Error(message));
289
- }
290
- for (const batch of batches)await this.sendAiSubBatch(batch, retryOptions);
454
+ _reportCaptureLoss(errors, summary) {
455
+ const errorListeners = this._events.events['error']?.length ?? 0;
456
+ for (const error of errors)this._events.emit('error', error);
457
+ if (0 === errorListeners) console.warn(`[PostHog] ${summary}`);
291
458
  }
292
- async sendAiSubBatch(batch, retryOptions) {
293
- try {
294
- await super.sendBatch(batch, retryOptions, external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE);
295
- } catch (err) {
296
- if (!(0, core_namespaceObject.isPostHogFetchContentTooLargeError)(err)) throw err;
297
- if (1 === batch.length) {
298
- const [event] = batch;
299
- const eventName = 'string' == typeof event.event ? event.event : 'unknown';
300
- const message = `Event ${eventName} (${(0, batching_js_namespaceObject.eventByteSize)(event)} bytes) was rejected with 413 by ${external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;
301
- this._logger.error(message);
302
- this._events.emit('error', new Error(message));
303
- return;
304
- }
305
- const mid = Math.ceil(batch.length / 2);
306
- await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);
307
- await this.sendAiSubBatch(batch.slice(mid), retryOptions);
308
- }
459
+ captureCompressor() {
460
+ return compression_js_namespaceObject.webCompressor;
309
461
  }
310
- getV1Sender() {
311
- if (!this._v1Sender) this._v1Sender = new sender_js_namespaceObject.V1CaptureSender({
462
+ captureSenderConfig(path, compressor) {
463
+ const laneSettings = path === types_js_namespaceObject.AI_CAPTURE_ENDPOINT ? this._captureSettings.ai : this._captureSettings.analytics;
464
+ const compression = (0, compression_js_namespaceObject.resolveCaptureCodec)(laneSettings.compression, compressor, (fallback)=>this._logger.debug(`zstd compression is not available in this runtime; ${path} uses ${fallback} instead`));
465
+ return {
312
466
  host: this.host,
467
+ path,
313
468
  apiKey: this.apiKey,
314
469
  libraryId: this.getLibraryId(),
315
470
  libraryVersion: this.getLibraryVersion(),
316
471
  userAgent: this.getCustomUserAgent() || void 0,
317
472
  historicalMigration: this.historicalMigration,
318
- compressionEnabled: !this.disableCompression,
319
- requestTimeoutMs: this.requestTimeout,
320
- maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
321
- initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
473
+ compression,
474
+ requestTimeoutMs: laneSettings.requestTimeoutMs,
475
+ maxRetries: this._captureSettings.maxRetries,
322
476
  isDebug: this.isDebug
323
- }, {
324
- fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),
325
- onError: (error)=>this._events.emit('error', error),
326
- compress: (payload)=>this.compressPayload(payload)
327
- });
328
- return this._v1Sender;
477
+ };
478
+ }
479
+ warnIfCaptureModeSet() {
480
+ const captureMode = "u" > typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;
481
+ if (void 0 !== captureMode) console.warn('[PostHog] POSTHOG_CAPTURE_MODE is no longer read. Capture always uses capture v1.');
329
482
  }
330
483
  getLibraryVersion() {
331
484
  return external_version_js_namespaceObject.version;
@@ -466,10 +619,34 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
466
619
  }
467
620
  };
468
621
  }
469
- getCommonEventProperties() {
470
- const commonProperties = super.getCommonEventProperties();
471
- if (this.options.isServer ?? true) commonProperties.$is_server = true;
472
- return commonProperties;
622
+ async _sdkEventProperties(event, properties, distinctId, flagInputs) {
623
+ const sdkProperties = {
624
+ ...this._serviceNameProperties(),
625
+ ...await this._flagEventProperties(distinctId, flagInputs)
626
+ };
627
+ if (this.options.isServer ?? true) sdkProperties.$is_server = true;
628
+ if (this.options.disableGeoip ?? true) sdkProperties.$geoip_disable = true;
629
+ if ('$exception' === event) {
630
+ if ((0, external_event_defaults_js_namespaceObject.isUnsetProperty)(properties, '$trace_id') && (0, external_event_defaults_js_namespaceObject.isUnsetProperty)(properties, '$span_id')) Object.assign(sdkProperties, await (0, trace_context_js_namespaceObject.getActiveTraceProperties)());
631
+ const releaseId = core_namespaceObject.ErrorTracking.getInjectedReleaseId();
632
+ if (releaseId) sdkProperties.$release_id = releaseId;
633
+ }
634
+ return sdkProperties;
635
+ }
636
+ async _flagEventProperties(distinctId, { groups, flags, sendFeatureFlags, disableGeoip }) {
637
+ try {
638
+ if (flags) {
639
+ if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');
640
+ return flags._getEventProperties();
641
+ }
642
+ if (sendFeatureFlags) {
643
+ emitDeprecationWarningOnce('sendFeatureFlags', "`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");
644
+ const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
645
+ const flagValues = await this.getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
646
+ return buildFlagEventProperties(flagValues);
647
+ }
648
+ } catch {}
649
+ return {};
473
650
  }
474
651
  enable() {
475
652
  return super.optIn();
@@ -481,34 +658,52 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
481
658
  super.debug(enabled);
482
659
  this.featureFlagsPoller?.debug(enabled);
483
660
  }
661
+ describeDebugPayload(payload) {
662
+ return summarizeForDebugLog(payload);
663
+ }
484
664
  _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {
485
665
  if ('string' == typeof props) this._logger.warn(stringArgumentWarning);
486
666
  if ('$exception' === props.event && !props._originatedFromCaptureException) this._logger.warn(exceptionCaptureWarning);
487
667
  }
488
668
  _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {
489
- return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options })=>{
669
+ const invalidUuidWarned = isInvalidUuid(props.uuid);
670
+ const uuid = this._canonicalEventUuid(props.uuid);
671
+ if (uuid !== props.uuid) props = {
672
+ ...props,
673
+ uuid
674
+ };
675
+ return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options, uuid, timestamp })=>{
490
676
  if (this.disabled || this.optedOut) prepareOptions?.onCaptureFailed?.();
491
677
  const captureOptions = {
492
- timestamp: options.timestamp,
493
- disableGeoip: options.disableGeoip,
494
- uuid: options.uuid
678
+ timestamp,
679
+ disableGeoip: false,
680
+ uuid,
681
+ _invalidUuidWarned: invalidUuidWarned
495
682
  };
496
683
  const message = {
497
- distinctId,
684
+ distinct_id: distinctId,
498
685
  event,
499
- properties: {
500
- ...properties,
501
- ...this.getCommonEventProperties()
502
- }
686
+ properties,
687
+ ...void 0 !== options ? {
688
+ options
689
+ } : {}
503
690
  };
504
691
  return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);
505
692
  }).catch((err)=>{
506
- if (err) {
693
+ if (err instanceof UnreadableEventError) {
694
+ this._dropUnreadableEvent(uuid, immediate, explicitRoute);
695
+ prepareOptions?.onCaptureFailed?.();
696
+ } else if (err) {
507
697
  console.error(err);
508
698
  prepareOptions?.onCaptureFailed?.();
509
699
  }
510
700
  }));
511
701
  }
702
+ _dropUnreadableEvent(uuid, immediate, explicitRoute) {
703
+ if (this.disabled || this.optedOut) return;
704
+ this._captureLane(explicitRoute).dropUnserializable(uuid, immediate);
705
+ if (!immediate) this.scheduleDebouncedFlush();
706
+ }
512
707
  _capturePreparedEvent(props, immediate) {
513
708
  return this._sendPreparedEvent('capture', props, immediate);
514
709
  }
@@ -522,7 +717,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
522
717
  }
523
718
  captureAi(props) {
524
719
  if (this.disabled) return;
525
- const uuid = (0, core_namespaceObject.getEventUuid)(props.uuid, core_namespaceObject.uuidv7);
720
+ const uuid = this._canonicalEventUuid(props.uuid) ?? (0, uuid_js_namespaceObject.eventUuidv7)();
526
721
  this._sendPreparedAiEvent({
527
722
  ...props,
528
723
  uuid
@@ -531,7 +726,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
531
726
  }
532
727
  async captureAiImmediate(props) {
533
728
  if (this.disabled) return;
534
- const uuid = (0, core_namespaceObject.getEventUuid)(props.uuid, core_namespaceObject.uuidv7);
729
+ const uuid = this._canonicalEventUuid(props.uuid) ?? (0, uuid_js_namespaceObject.eventUuidv7)();
535
730
  await this._sendPreparedAiEvent({
536
731
  ...props,
537
732
  uuid
@@ -540,46 +735,29 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
540
735
  }
541
736
  _sendPreparedAiEvent(props, immediate) {
542
737
  if ('string' == typeof props?.event && !props.event.startsWith('$ai_')) this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`);
543
- this._aiCaptureRouteActive = true;
544
- return this._sendPreparedEvent('capture', props, immediate, void 0, external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE);
545
- }
546
- identify({ distinctId, properties = {}, disableGeoip }) {
547
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
548
- const setProps = $set || rest;
549
- const setOnceProps = $set_once || {};
550
- const eventProperties = {
551
- $set: setProps,
552
- $set_once: setOnceProps,
553
- $anon_distinct_id: $anon_distinct_id ?? void 0
554
- };
738
+ return this._sendPreparedEvent('capture', props, immediate, void 0, routing_js_namespaceObject.AI_CAPTURE_ROUTE);
739
+ }
740
+ identify({ distinctId, properties = {}, disableGeoip, options }) {
741
+ const eventProperties = identifyEventProperties(properties);
555
742
  this._sendPreparedEvent('identify', {
556
743
  distinctId,
557
744
  event: '$identify',
558
745
  properties: eventProperties,
559
- disableGeoip
560
- }, false, {
561
- includeContextProperties: false
562
- });
746
+ disableGeoip,
747
+ options
748
+ }, false);
563
749
  }
564
- async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
565
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
566
- const setProps = $set || rest;
567
- const setOnceProps = $set_once || {};
568
- const eventProperties = {
569
- $set: setProps,
570
- $set_once: setOnceProps,
571
- $anon_distinct_id: $anon_distinct_id ?? void 0
572
- };
750
+ async identifyImmediate({ distinctId, properties = {}, disableGeoip, options }) {
751
+ const eventProperties = identifyEventProperties(properties);
573
752
  await this._sendPreparedEvent('identify', {
574
753
  distinctId,
575
754
  event: '$identify',
576
755
  properties: eventProperties,
577
- disableGeoip
578
- }, true, {
579
- includeContextProperties: false
580
- });
756
+ disableGeoip,
757
+ options
758
+ }, true);
581
759
  }
582
- setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {
760
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {}, options }) {
583
761
  if (0 === Object.keys(properties).length && 0 === Object.keys(propertiesOnce).length) return;
584
762
  const eventProperties = {};
585
763
  if (Object.keys(properties).length > 0) eventProperties.$set = properties;
@@ -587,10 +765,11 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
587
765
  this.capture({
588
766
  distinctId,
589
767
  event: '$set',
590
- properties: eventProperties
768
+ properties: eventProperties,
769
+ options
591
770
  });
592
771
  }
593
- unsetPersonProperties({ distinctId, properties }) {
772
+ unsetPersonProperties({ distinctId, properties, options }) {
594
773
  const propertyNames = normalizeUnsetPersonProperties(properties);
595
774
  if (0 === propertyNames.length) return;
596
775
  this.capture({
@@ -598,7 +777,8 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
598
777
  event: '$set',
599
778
  properties: {
600
779
  $unset: propertyNames
601
- }
780
+ },
781
+ options
602
782
  });
603
783
  }
604
784
  alias(data) {
@@ -606,26 +786,22 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
606
786
  distinctId: data.distinctId,
607
787
  event: '$create_alias',
608
788
  properties: {
609
- distinct_id: data.distinctId,
610
789
  alias: data.alias
611
790
  },
612
- disableGeoip: data.disableGeoip
613
- }, false, {
614
- includeContextProperties: false
615
- });
791
+ disableGeoip: data.disableGeoip,
792
+ options: data.options
793
+ }, false, ALIAS_PREPARE_OPTIONS);
616
794
  }
617
795
  async aliasImmediate(data) {
618
796
  await this._sendPreparedEvent('alias', {
619
797
  distinctId: data.distinctId,
620
798
  event: '$create_alias',
621
799
  properties: {
622
- distinct_id: data.distinctId,
623
800
  alias: data.alias
624
801
  },
625
- disableGeoip: data.disableGeoip
626
- }, true, {
627
- includeContextProperties: false
628
- });
802
+ disableGeoip: data.disableGeoip,
803
+ options: data.options
804
+ }, true, ALIAS_PREPARE_OPTIONS);
629
805
  }
630
806
  isLocalEvaluationReady() {
631
807
  return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
@@ -1143,32 +1319,36 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1143
1319
  };
1144
1320
  return this._featureFlagEvaluationsHost;
1145
1321
  }
1146
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
1322
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }) {
1147
1323
  this._sendPreparedEvent('capture', {
1148
- distinctId: distinctId || `$${groupType}_${groupKey}`,
1324
+ distinctId,
1149
1325
  event: '$groupidentify',
1150
1326
  properties: {
1151
1327
  $group_type: groupType,
1152
1328
  $group_key: groupKey,
1153
1329
  $group_set: properties || {}
1154
1330
  },
1155
- disableGeoip
1331
+ disableGeoip,
1332
+ options
1156
1333
  }, false, {
1157
- includeContextProperties: false
1334
+ fallbackDistinctId: `$${groupType}_${groupKey}`,
1335
+ contextSession: false
1158
1336
  });
1159
1337
  }
1160
- async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {
1338
+ async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip, options }) {
1161
1339
  await this._sendPreparedEvent('capture', {
1162
- distinctId: distinctId || `$${groupType}_${groupKey}`,
1340
+ distinctId,
1163
1341
  event: '$groupidentify',
1164
1342
  properties: {
1165
1343
  $group_type: groupType,
1166
1344
  $group_key: groupKey,
1167
1345
  $group_set: properties || {}
1168
1346
  },
1169
- disableGeoip
1347
+ disableGeoip,
1348
+ options
1170
1349
  }, true, {
1171
- includeContextProperties: false
1350
+ fallbackDistinctId: `$${groupType}_${groupKey}`,
1351
+ contextSession: false
1172
1352
  });
1173
1353
  }
1174
1354
  async reloadFeatureFlags() {
@@ -1221,6 +1401,26 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1221
1401
  }
1222
1402
  return false;
1223
1403
  }
1404
+ register(properties) {
1405
+ return super.register(properties);
1406
+ }
1407
+ unregister(property) {
1408
+ return super.unregister(property);
1409
+ }
1410
+ async registerOptions(options) {
1411
+ if (!(0, core_namespaceObject.isPlainObject)(options)) return void console.error('[PostHog] registerOptions takes an object; ignoring the value');
1412
+ this._globalOptions = {
1413
+ ...this._globalOptions,
1414
+ ...options
1415
+ };
1416
+ }
1417
+ async unregisterOptions(key) {
1418
+ const remaining = {
1419
+ ...this._globalOptions
1420
+ };
1421
+ delete remaining[key];
1422
+ this._globalOptions = remaining;
1423
+ }
1224
1424
  withContext(data, fn, options) {
1225
1425
  if (!this.context) return fn();
1226
1426
  return this.context.run(data, ()=>{
@@ -1231,10 +1431,6 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1231
1431
  getContext() {
1232
1432
  return this.context?.get();
1233
1433
  }
1234
- enterContext(data, options) {
1235
- this.context?.enter(data, options);
1236
- (0, listeners_js_namespaceObject.notifyContextListeners)(this);
1237
- }
1238
1434
  async _shutdown(shutdownTimeoutMs) {
1239
1435
  const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);
1240
1436
  this._isShutdown = true;
@@ -1270,8 +1466,13 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1270
1466
  const remainingMs = Math.max(0, shutdownDeadlineMs - Date.now());
1271
1467
  const emailsSettled = emailsDrained ? (0, core_namespaceObject.raceWithTimeout)(emailsDrained, remainingMs) : void 0;
1272
1468
  try {
1273
- return await super._shutdown(remainingMs);
1469
+ await Promise.all([
1470
+ super._shutdown(remainingMs),
1471
+ this._drainCaptureLanes(shutdownDeadlineMs)
1472
+ ]);
1473
+ await this._drainCaptureLanes(shutdownDeadlineMs);
1274
1474
  } finally{
1475
+ for (const lane of this._captureLanes.values())lane.finishShutdown();
1275
1476
  await emailsSettled;
1276
1477
  await logsDrained;
1277
1478
  this._distinctIdHasSentFlagCalls.clear();
@@ -1279,6 +1480,11 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1279
1480
  resolve?.();
1280
1481
  }
1281
1482
  }
1483
+ _drainCaptureLanes(deadlineMs) {
1484
+ return Promise.all([
1485
+ ...this._captureLanes.values()
1486
+ ].map((lane)=>lane.drain(deadlineMs))).then(()=>{});
1487
+ }
1282
1488
  async _requestRemoteConfigPayload(flagKey) {
1283
1489
  if (this.disabled || !this.apiKey || !this.options.personalApiKey) return;
1284
1490
  const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;
@@ -1386,31 +1592,30 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1386
1592
  evaluationCache: {}
1387
1593
  };
1388
1594
  }
1389
- captureException(error, distinctId, additionalProperties, uuid, flags) {
1595
+ captureException(error, options, ...legacyArgs) {
1596
+ const exceptionOptions = readCaptureExceptionArgs('captureException', options, legacyArgs, true);
1390
1597
  if (!index_js_default().isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
1391
1598
  const syntheticException = new Error('PostHog syntheticException');
1392
- this.addPendingPromise(index_js_default().buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1393
- syntheticException
1394
- }, distinctId, additionalProperties, this.getContext()).then((msg)=>this._capturePreparedEvent({
1395
- ...msg,
1396
- uuid,
1397
- flags
1398
- }, false)));
1599
+ this.addPendingPromise(this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg)=>this._capturePreparedEvent(msg, false)));
1399
1600
  }
1400
1601
  }
1401
- async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
1602
+ async captureExceptionImmediate(error, options, ...legacyArgs) {
1603
+ const exceptionOptions = readCaptureExceptionArgs('captureExceptionImmediate', options, legacyArgs, false);
1402
1604
  if (!index_js_default().isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
1403
1605
  const syntheticException = new Error('PostHog syntheticException');
1404
- return this.addPendingPromise(index_js_default().buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1405
- syntheticException
1406
- }, distinctId, additionalProperties, this.getContext()).then((msg)=>this.captureImmediate({
1407
- ...msg,
1408
- flags
1409
- })));
1606
+ return this.addPendingPromise(this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg)=>this.captureImmediate(msg)));
1410
1607
  }
1411
1608
  }
1412
- async prepareEventMessage(props) {
1413
- return this._prepareEventMessage(props);
1609
+ async _buildExceptionEvent(error, syntheticException, { distinctId, properties, options, uuid, flags, level }) {
1610
+ const msg = await index_js_default().buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1611
+ syntheticException
1612
+ }, distinctId, properties, level, this.getContext());
1613
+ return {
1614
+ ...msg,
1615
+ options,
1616
+ uuid,
1617
+ flags
1618
+ };
1414
1619
  }
1415
1620
  _serviceNameProperties() {
1416
1621
  const serviceName = this._resolveServiceName();
@@ -1422,87 +1627,109 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1422
1627
  if (void 0 === this._serviceName) this._serviceName = (this.options.traces ? (0, core_namespaceObject.resolveTracesConfig)(this.options.traces, this.hostResourceAttributes()).serviceName : void 0) || (0, core_namespaceObject.resolveMetricsConfig)(this.options.metrics).serviceName || null;
1423
1628
  return this._serviceName;
1424
1629
  }
1425
- async _prepareEventMessage(props, options = {}) {
1630
+ async prepareEventMessage(props) {
1631
+ try {
1632
+ return await this._prepareEventMessage(props);
1633
+ } catch (error) {
1634
+ throw error instanceof UnreadableEventError ? error.original : error;
1635
+ }
1636
+ }
1637
+ async _prepareEventMessage(props, prepareOptions = {}) {
1426
1638
  const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
1639
+ const callOptions = (0, transform_js_namespaceObject.readEventOptions)(props.options);
1427
1640
  const contextData = (0, event_context_js_namespaceObject.getEventContext)(props, this.context?.get());
1428
- const includeContextProperties = options.includeContextProperties ?? true;
1429
- let mergedDistinctId = distinctId || contextData?.distinctId;
1430
- const mergedProperties = includeContextProperties ? {
1431
- ...this._serviceNameProperties(),
1432
- ...this.props,
1433
- ...contextData?.properties || {},
1434
- ...properties || {}
1435
- } : {
1436
- ...this._serviceNameProperties(),
1437
- ...properties || {}
1641
+ const contextProperties = (0, external_event_defaults_js_namespaceObject.snapshotLayer)(contextData?.properties);
1642
+ const contextOptions = (0, external_event_defaults_js_namespaceObject.snapshotLayer)(contextData?.options);
1643
+ const globalProperties = (0, external_event_defaults_js_namespaceObject.snapshotLayer)(this.props);
1644
+ const globalOptions = this._globalOptions;
1645
+ const libraryId = this.getLibraryId();
1646
+ const libraryVersion = this.getLibraryVersion();
1647
+ const resolvedDistinctId = presentDistinctId(distinctId) ?? presentDistinctId(contextData?.distinctId) ?? prepareOptions.fallbackDistinctId;
1648
+ const eventDistinctId = resolvedDistinctId ?? (0, uuid_js_namespaceObject.eventUuidv7)();
1649
+ const eventProperties = readCallerValues(()=>({
1650
+ ...properties || {}
1651
+ }));
1652
+ const callerPersonProfile = eventProperties[core_namespaceObject.EVENT_OPTION_LEGACY_PROPERTIES.process_person_profile];
1653
+ if (prepareOptions.distinctIdProperty) eventProperties.distinct_id = eventDistinctId;
1654
+ if ((prepareOptions.contextSession ?? true) && contextData?.sessionId && (0, external_event_defaults_js_namespaceObject.isUnsetProperty)(eventProperties, '$session_id')) eventProperties.$session_id = contextData.sessionId;
1655
+ if ((0, core_namespaceObject.isPlainObject)(groups) && Object.keys(groups).length > 0) {
1656
+ const existingGroups = eventProperties.$groups;
1657
+ eventProperties.$groups = (0, external_event_defaults_js_namespaceObject.isMergeableObject)(existingGroups) ? {
1658
+ ...existingGroups,
1659
+ ...groups
1660
+ } : {
1661
+ ...groups
1662
+ };
1663
+ }
1664
+ if (null != disableGeoip) (0, external_event_defaults_js_namespaceObject.fillProperties)(eventProperties, [
1665
+ {
1666
+ $geoip_disable: disableGeoip
1667
+ }
1668
+ ]);
1669
+ (0, external_event_defaults_js_namespaceObject.fillProperties)(eventProperties, [
1670
+ contextProperties,
1671
+ globalProperties
1672
+ ], prepareOptions.callOnlyProperties);
1673
+ (0, external_event_defaults_js_namespaceObject.fillProperties)(eventProperties, [
1674
+ await this._sdkEventProperties(event, eventProperties, eventDistinctId, {
1675
+ groups,
1676
+ flags,
1677
+ sendFeatureFlags,
1678
+ disableGeoip
1679
+ })
1680
+ ]);
1681
+ (0, external_event_defaults_js_namespaceObject.fillLibraryProperties)(eventProperties, libraryId, libraryVersion);
1682
+ const filledOptions = {
1683
+ ...callOptions
1438
1684
  };
1439
- if ('$exception' === event && !('$trace_id' in mergedProperties || '$span_id' in mergedProperties)) Object.assign(mergedProperties, await (0, trace_context_js_namespaceObject.getActiveTraceProperties)());
1440
- if (!mergedDistinctId) {
1441
- mergedDistinctId = (0, core_namespaceObject.uuidv7)();
1442
- mergedProperties.$process_person_profile = false;
1685
+ (0, external_event_defaults_js_namespaceObject.fillIdentifyStylePersonProfile)(event, filledOptions, callerPersonProfile, void 0 !== resolvedDistinctId);
1686
+ (0, external_event_defaults_js_namespaceObject.fillOptions)(filledOptions, [
1687
+ contextOptions,
1688
+ globalOptions,
1689
+ void 0 !== resolvedDistinctId ? void 0 : {
1690
+ process_person_profile: false
1691
+ }
1692
+ ]);
1693
+ (0, external_event_defaults_js_namespaceObject.dropIdentifyStyleLegacyPersonProfile)(event, filledOptions, eventProperties);
1694
+ const eventOptions = void 0 !== callOptions || Object.keys(filledOptions).length > 0 ? filledOptions : void 0;
1695
+ const flagEvent = prepareOptions.flagEvent;
1696
+ const enrichedProperties = flagEvent ? (0, external_flag_events_js_namespaceObject.applyFlagEventCapture)(eventProperties, flagEvent) : eventProperties;
1697
+ const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties) ? flagEvent ? (0, external_flag_events_js_namespaceObject.minimizeConfigVersion2FlagCalledProperties)(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES) : (0, core_namespaceObject.minimizeFlagCalledEventProperties)(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES) : enrichedProperties;
1698
+ let finalEvent = event;
1699
+ if ('$pageview' === event && this.options.__previewCaptureBotPageviews && 'string' == typeof finalProperties.$raw_user_agent && (0, core_namespaceObject.isBlockedUA)(finalProperties.$raw_user_agent, this.options.customBlockedUserAgents || [])) {
1700
+ finalEvent = '$bot_pageview';
1701
+ finalProperties.$browser_type = 'bot';
1443
1702
  }
1444
- if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;
1445
- const flagEvent = options.flagEvent;
1446
- const enrichedProperties = flagEvent ? (0, external_flag_events_js_namespaceObject.applyFlagEventCapture)(mergedProperties, flagEvent) : mergedProperties;
1447
- const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties) ? flagEvent ? (0, external_flag_events_js_namespaceObject.minimizeConfigVersion2FlagCalledProperties)(enrichedProperties) : (0, core_namespaceObject.minimizeFlagCalledEventProperties)(enrichedProperties) : enrichedProperties;
1448
1703
  const eventMessage = this._runBeforeSend({
1449
- distinctId: mergedDistinctId,
1450
- event,
1704
+ distinctId: eventDistinctId,
1705
+ event: finalEvent,
1451
1706
  properties: finalProperties,
1452
1707
  groups,
1453
1708
  flags,
1454
1709
  sendFeatureFlags,
1455
1710
  timestamp,
1456
1711
  disableGeoip,
1457
- uuid
1458
- }, options.onCaptureFailed);
1712
+ uuid,
1713
+ options: eventOptions
1714
+ }, prepareOptions.onCaptureFailed);
1459
1715
  if (!eventMessage) return Promise.reject(null);
1460
- const eventProperties = await Promise.resolve().then(async ()=>{
1461
- if (flags) {
1462
- if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');
1463
- return flags._getEventProperties();
1464
- }
1465
- if (sendFeatureFlags) {
1466
- emitDeprecationWarningOnce('sendFeatureFlags', "`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");
1467
- const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
1468
- const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
1469
- return buildFlagEventProperties(flagValues);
1470
- }
1471
- return {};
1472
- }).catch(()=>({})).then((additionalProperties)=>{
1473
- const resolvedGroups = eventMessage.groups || groups;
1474
- return {
1475
- ...additionalProperties,
1476
- ...eventMessage.properties || {},
1477
- ...void 0 !== resolvedGroups && Object.keys(resolvedGroups).length > 0 ? {
1478
- $groups: resolvedGroups
1479
- } : {}
1480
- };
1481
- });
1482
- if ('$pageview' === eventMessage.event && this.options.__preview_capture_bot_pageviews && 'string' == typeof eventProperties.$raw_user_agent) {
1483
- if ((0, core_namespaceObject.isBlockedUA)(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
1484
- eventMessage.event = '$bot_pageview';
1485
- eventProperties.$browser_type = 'bot';
1486
- }
1487
- }
1488
1716
  return {
1489
1717
  distinctId: eventMessage.distinctId,
1490
1718
  event: eventMessage.event,
1491
- properties: eventProperties,
1492
- options: {
1493
- timestamp: eventMessage.timestamp,
1494
- disableGeoip: eventMessage.disableGeoip,
1495
- uuid: eventMessage.uuid
1496
- }
1719
+ properties: eventMessage.properties || {},
1720
+ options: eventMessage.options,
1721
+ uuid: eventMessage.uuid,
1722
+ timestamp: eventMessage.timestamp,
1723
+ disableGeoip: eventMessage.disableGeoip
1497
1724
  };
1498
1725
  }
1499
1726
  _runBeforeSend(eventMessage, onError) {
1500
- const beforeSend = this.options.before_send;
1727
+ const beforeSend = this.options.beforeSend;
1501
1728
  if (!beforeSend) return eventMessage;
1502
1729
  const fns = Array.isArray(beforeSend) ? beforeSend : [
1503
1730
  beforeSend
1504
1731
  ];
1505
- let result = eventMessage;
1732
+ let result = readCallerValues(()=>isolateForBeforeSend(eventMessage));
1506
1733
  for (const fn of fns)try {
1507
1734
  result = fn(result);
1508
1735
  if (!result) {
@@ -1514,7 +1741,8 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1514
1741
  this._logger.warn(message);
1515
1742
  }
1516
1743
  } catch (error) {
1517
- this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);
1744
+ const errorType = error instanceof Error ? error.name : typeof error;
1745
+ console.error(`[PostHog] Error in beforeSend function for event '${eventMessage.event}' (${errorType})`);
1518
1746
  onError?.();
1519
1747
  return null;
1520
1748
  }