@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
@@ -0,0 +1,554 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ DUPLICATE_EVENT_UUID: ()=>DUPLICATE_EVENT_UUID,
32
+ MAX_RETRY_DELAY_MS: ()=>MAX_RETRY_DELAY_MS,
33
+ RETRY_BASE_DELAY_MS: ()=>RETRY_BASE_DELAY_MS,
34
+ V1CaptureSender: ()=>V1CaptureSender
35
+ });
36
+ const uuidv7_js_namespaceObject = require("../vendor/uuidv7.js");
37
+ const external_compression_js_namespaceObject = require("./compression.js");
38
+ const external_errors_js_namespaceObject = require("./errors.js");
39
+ const external_serialize_js_namespaceObject = require("./serialize.js");
40
+ const external_uuid_js_namespaceObject = require("./uuid.js");
41
+ const RETRY_BASE_DELAY_MS = 100;
42
+ const MAX_RETRY_DELAY_MS = 30000;
43
+ async function raceAbort(work, signal) {
44
+ if (!signal) return work;
45
+ let onAbort;
46
+ const aborted = new Promise((_resolve, reject)=>{
47
+ onAbort = ()=>{
48
+ const abortError = new Error('Capture V1 request aborted while compressing the body');
49
+ abortError.name = 'AbortError';
50
+ abortError.cause = signal.reason;
51
+ reject(abortError);
52
+ };
53
+ if (signal.aborted) onAbort();
54
+ else signal.addEventListener('abort', onAbort, {
55
+ once: true
56
+ });
57
+ });
58
+ try {
59
+ return await Promise.race([
60
+ work,
61
+ aborted
62
+ ]);
63
+ } finally{
64
+ signal.removeEventListener('abort', onAbort);
65
+ }
66
+ }
67
+ const COMPRESSION_TIMED_OUT = Symbol('compression timed out');
68
+ function abortableSleep(ms, signal) {
69
+ return new Promise((resolve)=>{
70
+ const onAbort = ()=>{
71
+ clearTimeout(timer);
72
+ resolve();
73
+ };
74
+ const timer = setTimeout(()=>{
75
+ signal?.removeEventListener('abort', onAbort);
76
+ resolve();
77
+ }, ms);
78
+ signal?.addEventListener('abort', onAbort, {
79
+ once: true
80
+ });
81
+ });
82
+ }
83
+ const RETRYABLE_STATUSES = new Set([
84
+ 404,
85
+ 408,
86
+ 429,
87
+ 500,
88
+ 502,
89
+ 503,
90
+ 504
91
+ ]);
92
+ const FOLLOWED_REDIRECT_STATUSES = new Set([
93
+ 307,
94
+ 308
95
+ ]);
96
+ const MAX_REDIRECTS = 5;
97
+ const timeoutErrors = new WeakSet();
98
+ const DUPLICATE_EVENT_UUID = 'duplicate_event_uuid';
99
+ class V1CaptureSender {
100
+ constructor(config, hooks){
101
+ this.config = config;
102
+ this.hostOrigin = originOf(config.host);
103
+ this.fetchFn = hooks.fetch;
104
+ this.onError = hooks.onError;
105
+ this.now = hooks.now ?? Date.now;
106
+ this.sleep = hooks.sleep ?? abortableSleep;
107
+ this.generateRequestId = hooks.generateRequestId ?? uuidv7_js_namespaceObject.uuidv7;
108
+ this.random = hooks.random ?? Math.random;
109
+ this.compress = hooks.compress ?? external_compression_js_namespaceObject.webCompressor.compress;
110
+ }
111
+ async send(events, options = {}) {
112
+ if (0 === events.length) return [];
113
+ const { signal, keepUnsent = false, onDeferred, retryOf } = options;
114
+ const requestId = retryOf?.requestId ?? this.generateRequestId();
115
+ const createdAt = retryOf?.createdAt ?? new Date(this.now()).toISOString();
116
+ const attemptsBefore = retryOf?.attempt ?? 0;
117
+ let lastAttempt = attemptsBefore;
118
+ const url = `${this.config.host}${this.config.path}`;
119
+ const drops = [];
120
+ const loss = new external_errors_js_namespaceObject.CaptureLossTally();
121
+ let pending = events;
122
+ const unsent = (cause, failure)=>{
123
+ if (keepUnsent) {
124
+ this.surfacePartialDrops(requestId, drops, loss);
125
+ const timedOut = cause instanceof Error && timeoutErrors.has(cause);
126
+ onDeferred?.({
127
+ reason: failure,
128
+ tooLarge: false,
129
+ ...timedOut ? {
130
+ timedOut
131
+ } : {},
132
+ request: {
133
+ requestId,
134
+ createdAt,
135
+ attempt: lastAttempt
136
+ }
137
+ });
138
+ return pending;
139
+ }
140
+ this.surfaceBatchFailure(requestId, drops, pending, cause, loss, failure);
141
+ return [];
142
+ };
143
+ const deferred = (kept, deferral)=>{
144
+ this.surfacePartialDrops(requestId, drops, loss);
145
+ onDeferred?.({
146
+ ...deferral,
147
+ request: {
148
+ requestId,
149
+ createdAt,
150
+ attempt: lastAttempt
151
+ }
152
+ });
153
+ return kept;
154
+ };
155
+ const { maxRetries } = this.config;
156
+ const maxAttempts = (Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 0) + 1;
157
+ for(let attempt = 1; attempt <= maxAttempts; attempt++){
158
+ if (signal?.aborted) return unsent(signal.reason, 'not sent: aborted');
159
+ const isLastAttempt = attempt === maxAttempts;
160
+ const payload = (0, external_serialize_js_namespaceObject.buildV1Body)(pending, {
161
+ createdAt,
162
+ historicalMigration: this.config.historicalMigration
163
+ });
164
+ let captureAttempt;
165
+ let retryDelayMs;
166
+ try {
167
+ lastAttempt = attemptsBefore + attempt;
168
+ captureAttempt = await this.sendOnce(url, payload, lastAttempt, requestId, signal);
169
+ const { response, signal: attemptSignal, redirectFailure } = captureAttempt;
170
+ const { status } = response;
171
+ if (void 0 !== redirectFailure) {
172
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
173
+ const failure = `failed on a redirect it does not follow (HTTP ${status})`;
174
+ this.surfaceBatchFailure(requestId, drops, pending, new Error(redirectFailure), loss, failure);
175
+ return [];
176
+ }
177
+ if (status < 200 || status >= 300) {
178
+ const tooLarge = 413 === status && pending.length > 1;
179
+ if (onDeferred && (tooLarge || isLastAttempt && RETRYABLE_STATUSES.has(status))) {
180
+ const retryAfterMs = this.parseRetryAfter(response);
181
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
182
+ return deferred(pending, {
183
+ reason: `HTTP ${status}`,
184
+ retryAfterMs,
185
+ tooLarge
186
+ });
187
+ }
188
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
189
+ const retryAfterMs = this.parseRetryAfter(response);
190
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
191
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
192
+ } else {
193
+ const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);
194
+ this.surfaceBatchFailure(requestId, drops, pending, httpError, loss, `failed with HTTP ${status}`);
195
+ return [];
196
+ }
197
+ } else {
198
+ let parsed;
199
+ try {
200
+ parsed = await captureAttempt.waitFor(this.parseResponse(response));
201
+ } catch (error) {
202
+ if (attemptSignal.aborted) throw error;
203
+ this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`), loss, `failed with an unreadable response (HTTP ${status})`);
204
+ return [];
205
+ }
206
+ const dropsBefore = drops.length;
207
+ const retryable = this.classify(pending, parsed, drops);
208
+ for (const drop of drops.slice(dropsBefore)){
209
+ const cause = drop.details === DUPLICATE_EVENT_UUID ? 'dropped as duplicate uuids' : 'dropped by the server';
210
+ loss.add(`${cause} (HTTP ${status})`, 1);
211
+ }
212
+ if (0 === retryable.length) {
213
+ this.surfacePartialDrops(requestId, drops, loss);
214
+ return [];
215
+ }
216
+ if (isLastAttempt && onDeferred) return deferred(retryable, {
217
+ reason: 'the server asked to retry them',
218
+ retryAfterMs: this.parseRetryAfter(response),
219
+ tooLarge: false
220
+ });
221
+ if (isLastAttempt) {
222
+ loss.add(`still marked for retry after ${maxAttempts} attempt(s) (HTTP ${status})`, retryable.length);
223
+ this.report(this.captureError({
224
+ requestId,
225
+ drops,
226
+ retryExhausted: retryable.map((event)=>event.uuid)
227
+ }), loss);
228
+ return [];
229
+ }
230
+ pending = retryable;
231
+ const retryAfterMs = this.parseRetryAfter(response);
232
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
233
+ }
234
+ } catch (transportError) {
235
+ if (captureAttempt && !captureAttempt.signal.aborted) throw transportError;
236
+ if (isLastAttempt || signal?.aborted) return unsent(transportError, this.describeTransportFailure(transportError, signal));
237
+ retryDelayMs = this.backoffDelay(attempt);
238
+ } finally{
239
+ captureAttempt?.cleanup();
240
+ }
241
+ if (void 0 !== retryDelayMs) await this.sleepUnlessAborted(retryDelayMs, signal);
242
+ }
243
+ return [];
244
+ }
245
+ async sleepUnlessAborted(ms, signal) {
246
+ if (!signal) return this.sleep(ms);
247
+ if (signal.aborted) return;
248
+ let onAbort;
249
+ const aborted = new Promise((resolve)=>{
250
+ onAbort = resolve;
251
+ signal.addEventListener('abort', onAbort, {
252
+ once: true
253
+ });
254
+ });
255
+ try {
256
+ await Promise.race([
257
+ this.sleep(ms, signal),
258
+ aborted
259
+ ]);
260
+ } finally{
261
+ signal.removeEventListener('abort', onAbort);
262
+ }
263
+ }
264
+ async sendOnce(url, payload, attempt, requestId, externalSignal) {
265
+ const { body, contentEncoding } = await this.encodeBody(payload, externalSignal);
266
+ const headers = this.buildHeaders(attempt, requestId);
267
+ if (contentEncoding) headers['Content-Encoding'] = contentEncoding;
268
+ const controller = new AbortController();
269
+ let timeoutPhase = 'waiting for response headers';
270
+ let timer;
271
+ let onExternalAbort;
272
+ const stopListening = ()=>{
273
+ if (onExternalAbort) externalSignal?.removeEventListener('abort', onExternalAbort);
274
+ };
275
+ const deadline = new Promise((_resolve, reject)=>{
276
+ const abortWith = (error)=>{
277
+ reject(error);
278
+ controller.abort(error);
279
+ };
280
+ timer = setTimeout(()=>{
281
+ const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);
282
+ timeoutError.name = 'AbortError';
283
+ timeoutErrors.add(timeoutError);
284
+ abortWith(timeoutError);
285
+ }, this.config.requestTimeoutMs);
286
+ if (externalSignal) {
287
+ onExternalAbort = ()=>{
288
+ const abortError = new Error(`Capture V1 request aborted ${timeoutPhase}`);
289
+ abortError.name = 'AbortError';
290
+ abortError.cause = externalSignal.reason;
291
+ abortWith(abortError);
292
+ };
293
+ if (externalSignal.aborted) onExternalAbort();
294
+ else externalSignal.addEventListener('abort', onExternalAbort, {
295
+ once: true
296
+ });
297
+ }
298
+ });
299
+ deadline.catch(()=>{});
300
+ try {
301
+ const fetchPromise = this.fetchFollowingRedirects(url, headers, body, controller.signal);
302
+ let responseAccepted = false;
303
+ fetchPromise.then((late)=>{
304
+ if (controller.signal.aborted && !responseAccepted) this.cancelBody(late.response);
305
+ }).catch(()=>{});
306
+ const { response, redirectFailure } = await Promise.race([
307
+ fetchPromise,
308
+ deadline
309
+ ]);
310
+ responseAccepted = true;
311
+ timeoutPhase = 'while reading the response body';
312
+ let cleanedUp = false;
313
+ let cancellation;
314
+ const cancelBody = ()=>cancellation ??= this.cancelBody(response);
315
+ return {
316
+ response,
317
+ redirectFailure,
318
+ signal: controller.signal,
319
+ waitFor: (operation)=>Promise.race([
320
+ operation,
321
+ deadline
322
+ ]),
323
+ cancelBody,
324
+ cleanup: ()=>{
325
+ if (cleanedUp) return;
326
+ cleanedUp = true;
327
+ clearTimeout(timer);
328
+ stopListening();
329
+ if (controller.signal.aborted) cancelBody();
330
+ }
331
+ };
332
+ } catch (error) {
333
+ clearTimeout(timer);
334
+ stopListening();
335
+ throw error;
336
+ }
337
+ }
338
+ async fetchFollowingRedirects(url, headers, body, signal) {
339
+ let target = url;
340
+ for(let redirects = 0;; redirects++){
341
+ const response = await this.fetchFn(target, {
342
+ method: 'POST',
343
+ headers,
344
+ body: 'string' == typeof body ? body : body.slice(),
345
+ signal,
346
+ redirect: 'manual'
347
+ });
348
+ const { status } = response;
349
+ if (status < 300 || status >= 400) return {
350
+ response
351
+ };
352
+ if (!FOLLOWED_REDIRECT_STATUSES.has(status)) return {
353
+ response,
354
+ redirectFailure: `Capture V1 request got an HTTP ${status} redirect, which it does not follow`
355
+ };
356
+ if (redirects === MAX_REDIRECTS) return {
357
+ response,
358
+ redirectFailure: `Capture V1 request was redirected more than ${MAX_REDIRECTS} times`
359
+ };
360
+ const next = resolveLocation(response.headers?.get('Location'), target);
361
+ if (void 0 === next || originOf(next) !== this.hostOrigin) return {
362
+ response,
363
+ redirectFailure: `Capture V1 request got an HTTP ${status} redirect away from the configured host`
364
+ };
365
+ this.cancelBody(response);
366
+ if (signal.aborted) throw signal.reason;
367
+ target = next;
368
+ }
369
+ }
370
+ async encodeBody(payload, signal) {
371
+ const codec = this.config.compression;
372
+ if ('none' === codec) return {
373
+ body: payload
374
+ };
375
+ let timer;
376
+ try {
377
+ const compression = this.compress(payload, codec);
378
+ compression.catch(()=>{});
379
+ const timedOut = new Promise((resolve)=>{
380
+ timer = setTimeout(()=>resolve(COMPRESSION_TIMED_OUT), this.config.requestTimeoutMs);
381
+ });
382
+ const compressed = await raceAbort(Promise.race([
383
+ compression,
384
+ timedOut
385
+ ]), signal);
386
+ if (compressed === COMPRESSION_TIMED_OUT) {
387
+ if (this.config.isDebug) console.error(`Capture request body ${codec} compression took over ${this.config.requestTimeoutMs}ms, sending it uncompressed`);
388
+ } else if (null !== compressed) return {
389
+ body: compressed,
390
+ contentEncoding: codec
391
+ };
392
+ } catch (error) {
393
+ if (signal?.aborted) throw error;
394
+ if (this.config.isDebug) console.error(`Failed to ${codec} compress the capture request body`, error);
395
+ } finally{
396
+ clearTimeout(timer);
397
+ }
398
+ return {
399
+ body: payload
400
+ };
401
+ }
402
+ buildHeaders(attempt, requestId) {
403
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
404
+ const headers = {
405
+ 'Content-Type': 'application/json',
406
+ Authorization: `Bearer ${this.config.projectToken ?? this.config.apiKey}`,
407
+ 'PostHog-Sdk-Info': sdkInfo,
408
+ 'PostHog-Attempt': String(attempt),
409
+ 'PostHog-Request-Id': requestId,
410
+ 'PostHog-Request-Timestamp': new Date(this.now()).toISOString()
411
+ };
412
+ if (this.config.userAgent) headers['User-Agent'] = this.config.userAgent;
413
+ const extraHeaders = this.config.extraHeaders;
414
+ if (extraHeaders) {
415
+ const reserved = new Set([
416
+ 'user-agent',
417
+ 'content-encoding',
418
+ ...Object.keys(headers).map((name)=>name.toLowerCase())
419
+ ]);
420
+ for (const [name, value] of Object.entries(extraHeaders))if (!reserved.has(name.toLowerCase())) headers[name] = value;
421
+ }
422
+ return headers;
423
+ }
424
+ classify(pending, parsed, drops) {
425
+ const results = new Map();
426
+ for (const [uuid, result] of Object.entries(parsed.results))results.set((0, external_uuid_js_namespaceObject.canonicalizeUuid)(uuid) ?? uuid, result);
427
+ const retryable = [];
428
+ let copiesSeen;
429
+ for (const event of pending){
430
+ const result = results.get(event.uuid);
431
+ if (!result) continue;
432
+ const duplicates = result.duplicates_dropped;
433
+ if ('number' == typeof duplicates && Number.isSafeInteger(duplicates) && duplicates > 0) {
434
+ copiesSeen ??= new Map();
435
+ const copy = copiesSeen.get(event.uuid) ?? 0;
436
+ copiesSeen.set(event.uuid, copy + 1);
437
+ if (copy >= 1 && copy <= duplicates) {
438
+ drops.push({
439
+ uuid: event.uuid,
440
+ details: DUPLICATE_EVENT_UUID
441
+ });
442
+ continue;
443
+ }
444
+ }
445
+ if ('drop' === result.result) drops.push({
446
+ uuid: event.uuid,
447
+ details: result.details ?? void 0
448
+ });
449
+ else if ('retry' === result.result) retryable.push(event);
450
+ }
451
+ return retryable;
452
+ }
453
+ backoffDelay(attempt, retryAfterMs) {
454
+ const jitter = 0.75 + 0.5 * this.random();
455
+ const backoff = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1) * jitter, MAX_RETRY_DELAY_MS);
456
+ if (void 0 === retryAfterMs) return backoff;
457
+ return Math.max(backoff, Math.min(retryAfterMs, MAX_RETRY_DELAY_MS));
458
+ }
459
+ parseRetryAfter(response) {
460
+ const raw = response.headers?.get('Retry-After');
461
+ if (!raw) return;
462
+ const trimmed = raw.trim();
463
+ if (/^\d+$/.test(trimmed)) {
464
+ const seconds = parseInt(trimmed, 10);
465
+ return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : void 0;
466
+ }
467
+ const dateMs = Date.parse(trimmed);
468
+ if (Number.isNaN(dateMs)) return;
469
+ const delta = dateMs - this.now();
470
+ return delta > 0 ? delta : void 0;
471
+ }
472
+ async parseResponse(response) {
473
+ const text = await response.text();
474
+ const parsed = JSON.parse(text);
475
+ if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');
476
+ const results = parsed.results;
477
+ if ('object' != typeof results || null === results || Array.isArray(results)) throw new Error('unexpected results shape');
478
+ return {
479
+ results: results
480
+ };
481
+ }
482
+ async buildHttpError(response, status, waitFor) {
483
+ let bodyText = '';
484
+ try {
485
+ bodyText = (await waitFor(response.text())).slice(0, 512);
486
+ } catch {}
487
+ const suffix = bodyText ? `: ${bodyText}` : '';
488
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
489
+ }
490
+ surfaceBatchFailure(requestId, drops, pending, cause, loss, failure) {
491
+ loss.add(failure, pending.length);
492
+ this.report(this.captureError({
493
+ requestId,
494
+ drops,
495
+ retryExhausted: pending.map((event)=>event.uuid),
496
+ cause
497
+ }), loss);
498
+ }
499
+ surfacePartialDrops(requestId, drops, loss) {
500
+ if (drops.length > 0) this.report(this.captureError({
501
+ requestId,
502
+ drops,
503
+ retryExhausted: []
504
+ }), loss);
505
+ }
506
+ report(error, loss) {
507
+ this.onError(error, (0, external_errors_js_namespaceObject.describeCaptureLoss)(this.config.path, loss));
508
+ }
509
+ describeTransportFailure(error, signal) {
510
+ if (error instanceof Error && timeoutErrors.has(error)) return 'failed: request timed out';
511
+ if (signal?.aborted) return 'failed: request aborted';
512
+ const name = error instanceof Error && /^\w{1,64}$/.test(error.name) ? error.name : 'unknown';
513
+ return `failed with a network error (${name})`;
514
+ }
515
+ captureError(params) {
516
+ return new external_errors_js_namespaceObject.CaptureError({
517
+ endpoint: this.config.path,
518
+ ...params
519
+ });
520
+ }
521
+ async cancelBody(response) {
522
+ try {
523
+ await response.body?.cancel();
524
+ } catch {}
525
+ }
526
+ }
527
+ function originOf(url) {
528
+ try {
529
+ return new URL(url).origin;
530
+ } catch {
531
+ return;
532
+ }
533
+ }
534
+ function resolveLocation(location, base) {
535
+ if (!location) return;
536
+ try {
537
+ return new URL(location, base).href;
538
+ } catch {
539
+ return;
540
+ }
541
+ }
542
+ exports.DUPLICATE_EVENT_UUID = __webpack_exports__.DUPLICATE_EVENT_UUID;
543
+ exports.MAX_RETRY_DELAY_MS = __webpack_exports__.MAX_RETRY_DELAY_MS;
544
+ exports.RETRY_BASE_DELAY_MS = __webpack_exports__.RETRY_BASE_DELAY_MS;
545
+ exports.V1CaptureSender = __webpack_exports__.V1CaptureSender;
546
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
547
+ "DUPLICATE_EVENT_UUID",
548
+ "MAX_RETRY_DELAY_MS",
549
+ "RETRY_BASE_DELAY_MS",
550
+ "V1CaptureSender"
551
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
552
+ Object.defineProperty(exports, '__esModule', {
553
+ value: true
554
+ });