@posthog/browser 0.0.0-stage → 0.1.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 (121) hide show
  1. package/ARCHITECTURE.md +559 -0
  2. package/LICENSE +417 -0
  3. package/README.md +302 -2
  4. package/dist/analytics-buffer.d.ts +4 -0
  5. package/dist/analytics-buffer.js +200 -0
  6. package/dist/analytics-buffer.mjs +162 -0
  7. package/dist/analytics-delivery.d.ts +3 -0
  8. package/dist/analytics-delivery.js +231 -0
  9. package/dist/analytics-delivery.mjs +193 -0
  10. package/dist/analytics-internal.d.ts +64 -0
  11. package/dist/analytics-internal.js +52 -0
  12. package/dist/analytics-internal.mjs +5 -0
  13. package/dist/analytics-options.d.ts +14 -0
  14. package/dist/analytics-options.js +18 -0
  15. package/dist/analytics-options.mjs +1 -0
  16. package/dist/analytics.d.ts +5 -0
  17. package/dist/analytics.js +42 -0
  18. package/dist/analytics.mjs +4 -0
  19. package/dist/autocapture-options.d.ts +32 -0
  20. package/dist/autocapture-options.js +49 -0
  21. package/dist/autocapture-options.mjs +11 -0
  22. package/dist/autocapture.d.ts +5 -0
  23. package/dist/autocapture.js +108 -0
  24. package/dist/autocapture.mjs +70 -0
  25. package/dist/automatic-analytics.d.ts +3 -0
  26. package/dist/automatic-analytics.js +44 -0
  27. package/dist/automatic-analytics.mjs +6 -0
  28. package/dist/automatic-surveys.d.ts +2 -0
  29. package/dist/automatic-surveys.js +41 -0
  30. package/dist/automatic-surveys.mjs +3 -0
  31. package/dist/bot-filter.d.ts +2 -0
  32. package/dist/bot-filter.js +87 -0
  33. package/dist/bot-filter.mjs +49 -0
  34. package/dist/browser-client.d.ts +30 -0
  35. package/dist/browser-client.js +18 -0
  36. package/dist/browser-client.mjs +1 -0
  37. package/dist/capture-summary.d.ts +3 -0
  38. package/dist/capture-summary.js +63 -0
  39. package/dist/capture-summary.mjs +22 -0
  40. package/dist/capture-v1.d.ts +105 -0
  41. package/dist/capture-v1.js +781 -0
  42. package/dist/capture-v1.mjs +722 -0
  43. package/dist/core.d.ts +7 -0
  44. package/dist/core.js +49 -0
  45. package/dist/core.mjs +5 -0
  46. package/dist/event-buffer.d.ts +41 -0
  47. package/dist/event-buffer.js +158 -0
  48. package/dist/event-buffer.mjs +120 -0
  49. package/dist/extensions/registry.d.ts +16 -0
  50. package/dist/extensions/registry.js +128 -0
  51. package/dist/extensions/registry.mjs +90 -0
  52. package/dist/flags-internal.d.ts +8 -0
  53. package/dist/flags-internal.js +18 -0
  54. package/dist/flags-internal.mjs +1 -0
  55. package/dist/flags-options.d.ts +22 -0
  56. package/dist/flags-options.js +18 -0
  57. package/dist/flags-options.mjs +1 -0
  58. package/dist/flags-token.d.ts +15 -0
  59. package/dist/flags-token.js +40 -0
  60. package/dist/flags-token.mjs +2 -0
  61. package/dist/flags.d.ts +6 -0
  62. package/dist/flags.js +163 -0
  63. package/dist/flags.mjs +122 -0
  64. package/dist/id.d.ts +1 -0
  65. package/dist/id.js +61 -0
  66. package/dist/id.mjs +23 -0
  67. package/dist/index.d.ts +11 -0
  68. package/dist/index.js +119 -0
  69. package/dist/index.mjs +75 -0
  70. package/dist/lane.d.ts +57 -0
  71. package/dist/lane.js +363 -0
  72. package/dist/lane.mjs +325 -0
  73. package/dist/logger.d.ts +4 -0
  74. package/dist/logger.js +57 -0
  75. package/dist/logger.mjs +19 -0
  76. package/dist/logs-internal.d.ts +7 -0
  77. package/dist/logs-internal.js +18 -0
  78. package/dist/logs-internal.mjs +1 -0
  79. package/dist/logs-options.d.ts +11 -0
  80. package/dist/logs-options.js +57 -0
  81. package/dist/logs-options.mjs +19 -0
  82. package/dist/logs.d.ts +6 -0
  83. package/dist/logs.js +140 -0
  84. package/dist/logs.mjs +102 -0
  85. package/dist/named-error.d.ts +7 -0
  86. package/dist/named-error.js +49 -0
  87. package/dist/named-error.mjs +11 -0
  88. package/dist/posthog.d.ts +3 -0
  89. package/dist/posthog.js +823 -0
  90. package/dist/posthog.mjs +785 -0
  91. package/dist/rate-limiter.d.ts +19 -0
  92. package/dist/rate-limiter.js +89 -0
  93. package/dist/rate-limiter.mjs +51 -0
  94. package/dist/remote-config.d.ts +3 -0
  95. package/dist/remote-config.js +47 -0
  96. package/dist/remote-config.mjs +9 -0
  97. package/dist/request.d.ts +14 -0
  98. package/dist/request.js +130 -0
  99. package/dist/request.mjs +89 -0
  100. package/dist/state.d.ts +82 -0
  101. package/dist/state.js +625 -0
  102. package/dist/state.mjs +581 -0
  103. package/dist/surveys-extension.d.ts +9 -0
  104. package/dist/surveys-extension.js +272 -0
  105. package/dist/surveys-extension.mjs +234 -0
  106. package/dist/surveys-internal.d.ts +12 -0
  107. package/dist/surveys-internal.js +18 -0
  108. package/dist/surveys-internal.mjs +1 -0
  109. package/dist/surveys-options.d.ts +18 -0
  110. package/dist/surveys-options.js +42 -0
  111. package/dist/surveys-options.mjs +4 -0
  112. package/dist/surveys.d.ts +7 -0
  113. package/dist/surveys.js +48 -0
  114. package/dist/surveys.mjs +7 -0
  115. package/dist/types.d.ts +114 -0
  116. package/dist/types.js +18 -0
  117. package/dist/types.mjs +1 -0
  118. package/dist/version.d.ts +1 -0
  119. package/dist/version.js +40 -0
  120. package/dist/version.mjs +2 -0
  121. package/package.json +88 -3
@@ -0,0 +1,781 @@
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
+ CAPTURE_V1_BATCH_TARGET_BYTES: ()=>CAPTURE_V1_BATCH_TARGET_BYTES,
32
+ CAPTURE_V1_COMPRESSION_THRESHOLD_BYTES: ()=>CAPTURE_V1_COMPRESSION_THRESHOLD_BYTES,
33
+ CAPTURE_V1_MAX_BATCH_EVENTS: ()=>CAPTURE_V1_MAX_BATCH_EVENTS,
34
+ CAPTURE_V1_TEARDOWN_BUDGET_BYTES: ()=>CAPTURE_V1_TEARDOWN_BUDGET_BYTES,
35
+ buildCaptureV1Event: ()=>buildCaptureV1Event,
36
+ sendCaptureV1Batch: ()=>sendCaptureV1Batch,
37
+ sendCaptureV1Batches: ()=>sendCaptureV1Batches,
38
+ sendCaptureV1TeardownBatches: ()=>sendCaptureV1TeardownBatches
39
+ });
40
+ const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
41
+ const external_id_js_namespaceObject = require("./id.js");
42
+ const external_named_error_js_namespaceObject = require("./named-error.js");
43
+ const RETRYABLE_STATUSES = [
44
+ 408,
45
+ 500,
46
+ 502,
47
+ 503,
48
+ 504
49
+ ];
50
+ const CAPTURE_V1_MAX_BATCH_EVENTS = external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BATCH_EVENTS;
51
+ const CAPTURE_V1_BATCH_TARGET_BYTES = 5242880;
52
+ const CAPTURE_V1_COMPRESSION_THRESHOLD_BYTES = 1024;
53
+ const CAPTURE_V1_TEARDOWN_BUDGET_BYTES = Math.floor(52428.8);
54
+ const DEFAULT_COMPRESSION_TIMEOUT_MS = 1000;
55
+ const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
56
+ const setOutcome = (target, uuid, outcome)=>{
57
+ Object.defineProperty(target, uuid, {
58
+ configurable: true,
59
+ enumerable: true,
60
+ writable: true,
61
+ value: outcome
62
+ });
63
+ };
64
+ const mergeOutcomes = (target, source)=>{
65
+ for (const [uuid, outcome] of Object.entries(source))setOutcome(target, uuid, outcome);
66
+ };
67
+ const eventIds = (events)=>events.map(({ uuid })=>uuid);
68
+ const failedResult = (events, error, statusCode = 0)=>({
69
+ statusCode,
70
+ retry: eventIds(events),
71
+ drops: [],
72
+ outcomes: {},
73
+ error,
74
+ terminalError: error
75
+ });
76
+ const utf8Bytes = (value)=>{
77
+ let bytes = 0;
78
+ for(let index = 0; index < value.length; index++){
79
+ const code = value.charCodeAt(index);
80
+ if (code < 0x80) bytes++;
81
+ else if (code < 0x800) bytes += 2;
82
+ else if (code >= 0xd800 && code <= 0xdbff && value.charCodeAt(index + 1) >= 0xdc00) {
83
+ bytes += 4;
84
+ index++;
85
+ } else bytes += 3;
86
+ }
87
+ return bytes;
88
+ };
89
+ const prepareEvents = (messages)=>messages.map((source)=>{
90
+ const event = buildCaptureV1Event(source);
91
+ const json = JSON.stringify(event);
92
+ return {
93
+ source,
94
+ event,
95
+ uuid: event.uuid,
96
+ json,
97
+ bytes: utf8Bytes(json)
98
+ };
99
+ });
100
+ const serializeEnvelope = (createdAt, events)=>`{"created_at":${JSON.stringify(createdAt)},"batch":[${events.map(({ json })=>json).join(',')}]}`;
101
+ const partitionEvents = (events, createdAt, maxBatchEvents, targetBatchBytes)=>{
102
+ const batches = [];
103
+ const emptyBytes = utf8Bytes(serializeEnvelope(createdAt, []));
104
+ let batch = [];
105
+ let bytes = emptyBytes;
106
+ for (const event of events){
107
+ const addedBytes = event.bytes + (batch.length ? 1 : 0);
108
+ if (batch.length && (batch.length >= maxBatchEvents || bytes + addedBytes > targetBatchBytes)) {
109
+ batches.push(batch);
110
+ batch = [];
111
+ bytes = emptyBytes;
112
+ }
113
+ batch.push(event);
114
+ bytes += event.bytes + (batch.length > 1 ? 1 : 0);
115
+ }
116
+ if (batch.length) batches.push(batch);
117
+ return batches;
118
+ };
119
+ let gzipCrcTable;
120
+ const gzipCrc32 = (bytes)=>{
121
+ if (!gzipCrcTable) gzipCrcTable = Array.from({
122
+ length: 256
123
+ }, (_, value)=>{
124
+ let crc = value;
125
+ for(let bit = 0; bit < 8; bit++)crc = 1 & crc ? 0xedb88320 ^ crc >>> 1 : crc >>> 1;
126
+ return crc >>> 0;
127
+ });
128
+ let crc = 0xffffffff;
129
+ for (const byte of bytes)crc = gzipCrcTable[(crc ^ byte) & 0xff] ^ crc >>> 8;
130
+ return (0xffffffff ^ crc) >>> 0;
131
+ };
132
+ const nativeGzip = async (payload)=>{
133
+ try {
134
+ const CompressionStreamConstructor = globalThis.CompressionStream;
135
+ const TextEncoderConstructor = globalThis.TextEncoder;
136
+ const ResponseConstructor = globalThis.Response;
137
+ if ('function' != typeof CompressionStreamConstructor || 'function' != typeof TextEncoderConstructor || 'function' != typeof ResponseConstructor) return;
138
+ const input = new TextEncoderConstructor().encode(payload);
139
+ const stream = new CompressionStreamConstructor('gzip');
140
+ const writer = stream.writable.getWriter();
141
+ const write = writer.write(input).then(()=>writer.close()).catch(async (error)=>{
142
+ try {
143
+ await writer.abort(error);
144
+ } catch {}
145
+ throw error;
146
+ });
147
+ const compressed = await Promise.all([
148
+ new ResponseConstructor(stream.readable).blob(),
149
+ write
150
+ ]).then(([blob])=>blob);
151
+ if (compressed.size < 18) return;
152
+ const [headerBuffer, trailerBuffer] = await Promise.all([
153
+ compressed.slice(0, 3).arrayBuffer(),
154
+ compressed.slice(compressed.size - 8).arrayBuffer()
155
+ ]);
156
+ const header = new Uint8Array(headerBuffer);
157
+ const trailer = new DataView(trailerBuffer);
158
+ return 0x1f === header[0] && 0x8b === header[1] && 0x08 === header[2] && trailer.getUint32(0, true) === gzipCrc32(input) && trailer.getUint32(4, true) === input.length >>> 0 ? compressed : void 0;
159
+ } catch {
160
+ return;
161
+ }
162
+ };
163
+ const compressWithDeadline = async (payload, timeoutMs, signal, compress)=>{
164
+ let timer;
165
+ let onAbort;
166
+ const operation = Promise.resolve().then(()=>compress(payload)).catch(()=>void 0);
167
+ const interrupted = new Promise((resolve)=>{
168
+ try {
169
+ timer = globalThis.setTimeout(resolve, timeoutMs);
170
+ } catch {
171
+ resolve(void 0);
172
+ return;
173
+ }
174
+ if (signal) {
175
+ onAbort = ()=>resolve(void 0);
176
+ try {
177
+ signal.addEventListener('abort', onAbort, {
178
+ once: true
179
+ });
180
+ if (signal.aborted) onAbort();
181
+ } catch {
182
+ onAbort = void 0;
183
+ }
184
+ }
185
+ });
186
+ try {
187
+ return await Promise.race([
188
+ operation,
189
+ interrupted
190
+ ]);
191
+ } finally{
192
+ if (void 0 !== timer) globalThis.clearTimeout(timer);
193
+ if (onAbort) try {
194
+ signal?.removeEventListener('abort', onAbort);
195
+ } catch {}
196
+ }
197
+ };
198
+ const cancelResponseBody = async (response)=>{
199
+ try {
200
+ await response?.body?.cancel();
201
+ } catch {}
202
+ };
203
+ const coerceBoolean = (value)=>{
204
+ if ('boolean' == typeof value) return value;
205
+ if ('number' == typeof value && Number.isFinite(value)) return 0 !== value;
206
+ if ('string' == typeof value) {
207
+ const normalized = value.trim().toLowerCase();
208
+ if ('true' === normalized || '1' === normalized) return true;
209
+ if ('false' === normalized || '0' === normalized) return false;
210
+ }
211
+ };
212
+ const buildCaptureV1Event = (message)=>{
213
+ const properties = {
214
+ ...message.properties
215
+ };
216
+ const options = {};
217
+ const optionSentinels = [
218
+ [
219
+ '$cookieless_mode',
220
+ 'cookieless_mode'
221
+ ],
222
+ [
223
+ '$ignore_sent_at',
224
+ 'disable_skew_correction'
225
+ ],
226
+ [
227
+ '$process_person_profile',
228
+ 'process_person_profile'
229
+ ]
230
+ ];
231
+ for (const [property, option] of optionSentinels){
232
+ const value = coerceBoolean(properties[property]);
233
+ if (void 0 !== value) options[option] = value;
234
+ delete properties[property];
235
+ }
236
+ if ('string' == typeof properties.$product_tour_id) options.product_tour_id = properties.$product_tour_id;
237
+ delete properties.$product_tour_id;
238
+ const sessionId = properties.$session_id;
239
+ const windowId = properties.$window_id;
240
+ delete properties.$session_id;
241
+ delete properties.$window_id;
242
+ delete properties.$lib;
243
+ delete properties.$lib_version;
244
+ delete properties.token;
245
+ delete properties.distinct_id;
246
+ return {
247
+ event: message.event,
248
+ uuid: message.uuid,
249
+ distinct_id: message.distinct_id,
250
+ timestamp: message.timestamp,
251
+ ...'string' == typeof sessionId ? {
252
+ session_id: sessionId
253
+ } : {},
254
+ ...'string' == typeof windowId ? {
255
+ window_id: windowId
256
+ } : {},
257
+ options,
258
+ properties
259
+ };
260
+ };
261
+ const safeNow = (now)=>{
262
+ try {
263
+ const value = now();
264
+ return Number.isFinite(value) ? value : 0;
265
+ } catch {
266
+ return 0;
267
+ }
268
+ };
269
+ const isoNow = (now)=>{
270
+ try {
271
+ return new Date(safeNow(now)).toISOString();
272
+ } catch {
273
+ return '1970-01-01T00:00:00.000Z';
274
+ }
275
+ };
276
+ const parseRetryAfter = (response, now)=>{
277
+ try {
278
+ const raw = response?.headers.get('Retry-After')?.trim();
279
+ if (!raw) return;
280
+ if (/^\d+$/.test(raw)) {
281
+ const milliseconds = 1000 * Number(raw);
282
+ return Number.isFinite(milliseconds) && milliseconds > 0 ? milliseconds : void 0;
283
+ }
284
+ const delay = Date.parse(raw) - safeNow(now);
285
+ return delay > 0 ? delay : void 0;
286
+ } catch {
287
+ return;
288
+ }
289
+ };
290
+ const numberOption = (value, fallback, minimum)=>Math.max(minimum, Number.isFinite(value) ? value : fallback);
291
+ const retryDelay = (attempt, initialDelayMs, maxBackoffMs, random, retryAfterMs)=>{
292
+ const exponential = Math.min(initialDelayMs * 2 ** (attempt - 1), maxBackoffMs);
293
+ let randomValue = 0.5;
294
+ try {
295
+ const candidate = random();
296
+ if (Number.isFinite(candidate)) randomValue = Math.max(0, Math.min(1, candidate));
297
+ } catch {}
298
+ const jittered = Math.min(maxBackoffMs, Math.ceil(exponential * (0.5 + randomValue)));
299
+ return void 0 === retryAfterMs ? jittered : Math.max(jittered, Math.min(retryAfterMs, maxBackoffMs));
300
+ };
301
+ const cancellationError = ()=>new Error('Capture V1 retry was cancelled');
302
+ const canContinue = (check)=>{
303
+ try {
304
+ return check?.() ?? true;
305
+ } catch {
306
+ return false;
307
+ }
308
+ };
309
+ const waitForRetry = async (delayMs, sleep, signal)=>{
310
+ if (signal?.aborted) throw cancellationError();
311
+ if (!signal && sleep) return sleep(delayMs);
312
+ let timer;
313
+ let onAbort;
314
+ const wait = sleep ? sleep(delayMs) : new Promise((resolve)=>{
315
+ timer = globalThis.setTimeout(resolve, delayMs);
316
+ });
317
+ if (!signal) return wait;
318
+ const cancelled = new Promise((_resolve, reject)=>{
319
+ onAbort = ()=>{
320
+ if (void 0 !== timer) globalThis.clearTimeout(timer);
321
+ reject(cancellationError());
322
+ };
323
+ try {
324
+ signal.addEventListener('abort', onAbort, {
325
+ once: true
326
+ });
327
+ if (signal.aborted) onAbort();
328
+ } catch {
329
+ onAbort = void 0;
330
+ }
331
+ });
332
+ try {
333
+ await (onAbort ? Promise.race([
334
+ wait,
335
+ cancelled
336
+ ]) : wait);
337
+ } finally{
338
+ if (onAbort) try {
339
+ signal.removeEventListener('abort', onAbort);
340
+ } catch {}
341
+ }
342
+ };
343
+ const attemptOnce = async (runtime, events, libraryVersion, createdAt, requestId, attempt, now, timeoutMs, remainingTime, compressionEnabled, compressionThresholdBytes, compressionTimeoutMs, compress, signal, continuationCheck)=>{
344
+ if (signal?.aborted || !canContinue(continuationCheck)) return [
345
+ failedResult(events, cancellationError()),
346
+ events,
347
+ void 0
348
+ ];
349
+ const body = serializeEnvelope(createdAt, events);
350
+ const headers = {
351
+ 'Content-Type': 'application/json',
352
+ Authorization: `Bearer ${runtime[1]}`,
353
+ 'PostHog-Sdk-Info': `posthog-js/${libraryVersion}`,
354
+ 'PostHog-Attempt': String(attempt),
355
+ 'PostHog-Request-Id': requestId,
356
+ 'PostHog-Request-Timestamp': isoNow(now)
357
+ };
358
+ let requestBody = body;
359
+ if (compressionEnabled && utf8Bytes(body) >= compressionThresholdBytes) {
360
+ const compressed = await compressWithDeadline(body, Math.max(1, Math.min(compressionTimeoutMs, remainingTime())), signal, compress);
361
+ if (signal?.aborted || !canContinue(continuationCheck)) return [
362
+ failedResult(events, cancellationError()),
363
+ events,
364
+ void 0
365
+ ];
366
+ if (compressed && compressed.size < utf8Bytes(body)) {
367
+ requestBody = compressed;
368
+ headers['Content-Encoding'] = 'gzip';
369
+ }
370
+ }
371
+ let controller;
372
+ try {
373
+ controller = new AbortController();
374
+ } catch {}
375
+ const requestInit = {
376
+ method: 'POST',
377
+ credentials: 'omit',
378
+ headers,
379
+ body: requestBody,
380
+ ...controller ? {
381
+ signal: controller.signal
382
+ } : {}
383
+ };
384
+ const remainingAfterSetup = remainingTime();
385
+ if (remainingAfterSetup <= 0) return [
386
+ failedResult(events, new Error('Capture V1 exhausted its elapsed retry budget')),
387
+ events,
388
+ void 0
389
+ ];
390
+ const attemptTimeoutMs = Math.max(1, Math.min(timeoutMs, remainingAfterSetup));
391
+ let response;
392
+ let timer;
393
+ let onAbort;
394
+ let interrupted = false;
395
+ let timedOut = false;
396
+ let timeoutPhase = 'waiting for response headers';
397
+ const deadline = new Promise((_resolve, reject)=>{
398
+ timer = globalThis.setTimeout(()=>{
399
+ timedOut = true;
400
+ const error = new Error(`Capture V1 request timed out ${timeoutPhase} after ${attemptTimeoutMs}ms`);
401
+ (0, external_named_error_js_namespaceObject.defineErrorName)(error, 'AbortError');
402
+ reject(error);
403
+ try {
404
+ controller?.abort(error);
405
+ } catch {}
406
+ cancelResponseBody(response);
407
+ }, attemptTimeoutMs);
408
+ });
409
+ const cancelled = new Promise((_resolve, reject)=>{
410
+ if (!signal) return;
411
+ onAbort = ()=>{
412
+ interrupted = true;
413
+ const error = cancellationError();
414
+ reject(error);
415
+ try {
416
+ controller?.abort(error);
417
+ } catch {}
418
+ cancelResponseBody(response);
419
+ };
420
+ try {
421
+ signal.addEventListener('abort', onAbort, {
422
+ once: true
423
+ });
424
+ if (signal.aborted) onAbort();
425
+ } catch {
426
+ onAbort = void 0;
427
+ }
428
+ });
429
+ let text;
430
+ try {
431
+ const fetchPromise = runtime[2](`${runtime[0].api}/i/v1/analytics/events`, requestInit);
432
+ fetchPromise.then((lateResponse)=>{
433
+ if ((timedOut || interrupted) && !response) cancelResponseBody(lateResponse);
434
+ }, ()=>{});
435
+ response = await Promise.race([
436
+ fetchPromise,
437
+ deadline,
438
+ cancelled
439
+ ]);
440
+ timeoutPhase = 'while reading the response body';
441
+ text = await Promise.race([
442
+ response.text(),
443
+ deadline,
444
+ cancelled
445
+ ]);
446
+ } catch (error) {
447
+ const status = response?.status ?? 0;
448
+ const retryEvents = !response || status >= 200 && status < 300 || RETRYABLE_STATUSES.includes(status) ? events : [];
449
+ return [
450
+ failedResult(retryEvents, error, status),
451
+ retryEvents,
452
+ response
453
+ ];
454
+ } finally{
455
+ if (void 0 !== timer) globalThis.clearTimeout(timer);
456
+ if (onAbort) try {
457
+ signal?.removeEventListener('abort', onAbort);
458
+ } catch {}
459
+ }
460
+ const status = response.status;
461
+ const retryableStatus = RETRYABLE_STATUSES.includes(status);
462
+ let json;
463
+ if (text) try {
464
+ json = JSON.parse(text);
465
+ } catch {
466
+ json = void 0;
467
+ }
468
+ if (status < 200 || status >= 300) {
469
+ const suffix = text ? `: ${text.slice(0, 512)}` : '';
470
+ const retryEvents = retryableStatus ? events : [];
471
+ return [
472
+ failedResult(retryEvents, new Error(`Capture V1 request failed with HTTP ${status}${suffix}`), status),
473
+ retryEvents,
474
+ response
475
+ ];
476
+ }
477
+ if (!isRecord(json) || void 0 !== json.results && !isRecord(json.results)) return [
478
+ failedResult([], new Error(`Capture V1 returned an unparseable ${status} response body`), status),
479
+ [],
480
+ response
481
+ ];
482
+ const results = isRecord(json.results) ? json.results : {};
483
+ const retryEvents = [];
484
+ const drops = [];
485
+ const outcomes = {};
486
+ for (const prepared of events){
487
+ const outcome = Object.hasOwn(results, prepared.uuid) ? results[prepared.uuid] : void 0;
488
+ if (!isRecord(outcome) || ![
489
+ 'ok',
490
+ 'warning',
491
+ 'drop',
492
+ 'retry'
493
+ ].includes(String(outcome.result))) continue;
494
+ const parsed = {
495
+ result: outcome.result,
496
+ ...'string' == typeof outcome.details ? {
497
+ details: outcome.details
498
+ } : {}
499
+ };
500
+ setOutcome(outcomes, prepared.uuid, parsed);
501
+ if ('retry' === parsed.result) retryEvents.push(prepared);
502
+ else if ('drop' === parsed.result) drops.push({
503
+ uuid: prepared.uuid,
504
+ ...void 0 === parsed.details ? {} : {
505
+ details: parsed.details
506
+ }
507
+ });
508
+ }
509
+ return [
510
+ {
511
+ statusCode: status,
512
+ retry: eventIds(retryEvents),
513
+ drops,
514
+ outcomes
515
+ },
516
+ retryEvents,
517
+ response
518
+ ];
519
+ };
520
+ const sendCaptureV1Batch = async (runtime, messages, libraryVersion, options = {})=>{
521
+ if (0 === messages.length) return {
522
+ statusCode: 204,
523
+ retry: [],
524
+ drops: [],
525
+ outcomes: {}
526
+ };
527
+ if (!runtime[2]) return failedResult(messages, new Error('Fetch is not available'));
528
+ const now = options.now ?? Date.now;
529
+ const random = options.random ?? Math.random;
530
+ const maxAttempts = Math.floor(numberOption(options.maxAttempts, 4, 1));
531
+ const initialDelayMs = numberOption(options.initialRetryDelayMs, 3000, 0);
532
+ const maxBackoffMs = numberOption(options.maxBackoffMs, 30000, 0);
533
+ const requestTimeoutMs = Math.floor(numberOption(options.requestTimeoutMs, 10000, 1));
534
+ const maxElapsedMs = Math.floor(numberOption(options.maxElapsedMs, 60000, 1));
535
+ const compressionThresholdBytes = Math.floor(numberOption(options.compressionThresholdBytes, CAPTURE_V1_COMPRESSION_THRESHOLD_BYTES, 0));
536
+ const compressionTimeoutMs = Math.floor(numberOption(options.compressionTimeoutMs, DEFAULT_COMPRESSION_TIMEOUT_MS, 1));
537
+ const elapsedNow = options.elapsedNow ?? (()=>globalThis.performance?.now() ?? Date.now());
538
+ const startedAt = safeNow(elapsedNow);
539
+ const remainingTime = ()=>maxElapsedMs - Math.max(0, safeNow(elapsedNow) - startedAt);
540
+ let requestId;
541
+ try {
542
+ requestId = (options.generateRequestId ?? external_id_js_namespaceObject.createId)();
543
+ } catch {
544
+ requestId = `capture-${isoNow(now)}`;
545
+ }
546
+ const createdAt = options.createdAt ?? isoNow(now);
547
+ let pending;
548
+ try {
549
+ pending = options.prepared ?? prepareEvents(messages);
550
+ } catch (error) {
551
+ return failedResult(messages, error);
552
+ }
553
+ const drops = [];
554
+ const outcomes = {};
555
+ let latest = {
556
+ statusCode: 0,
557
+ retry: eventIds(pending),
558
+ drops: [],
559
+ outcomes: {}
560
+ };
561
+ const finish = (error, terminal = false)=>{
562
+ latest.retry = eventIds(pending);
563
+ latest.drops = drops;
564
+ latest.outcomes = outcomes;
565
+ latest.error = error;
566
+ if (terminal || void 0 !== latest.terminalError || 0 === Object.keys(outcomes).length) latest.terminalError = error;
567
+ return latest;
568
+ };
569
+ for(let attempt = 1; attempt <= maxAttempts; attempt++){
570
+ const remainingBeforeAttempt = remainingTime();
571
+ if (remainingBeforeAttempt <= 0) return finish(new Error('Capture V1 exhausted its elapsed retry budget'));
572
+ let retryEvents;
573
+ let response;
574
+ try {
575
+ [latest, retryEvents, response] = await attemptOnce(runtime, pending, libraryVersion, createdAt, requestId, attempt, now, requestTimeoutMs, remainingTime, options.compressionEnabled ?? false, compressionThresholdBytes, compressionTimeoutMs, options.compress ?? nativeGzip, options.signal, options.canRetry);
576
+ } catch (error) {
577
+ latest = failedResult(pending, error);
578
+ retryEvents = pending;
579
+ }
580
+ drops.push(...latest.drops);
581
+ mergeOutcomes(outcomes, latest.outcomes);
582
+ if (0 === retryEvents.length) {
583
+ latest.drops = drops;
584
+ latest.outcomes = outcomes;
585
+ if (drops.length) latest.error ??= new Error('Capture V1 dropped one or more events');
586
+ return latest;
587
+ }
588
+ pending = retryEvents;
589
+ if (attempt === maxAttempts) return finish(latest.error ?? new Error('Capture V1 exhausted its retry budget'));
590
+ if (!canContinue(options.canRetry)) return finish(new Error('Capture V1 retry was cancelled'), true);
591
+ const delay = retryDelay(attempt, initialDelayMs, maxBackoffMs, random, parseRetryAfter(response, now));
592
+ if (delay >= remainingTime()) return finish(new Error('Capture V1 exhausted its elapsed retry budget'));
593
+ try {
594
+ await waitForRetry(delay, options.sleep, options.signal);
595
+ if (!canContinue(options.canRetry)) throw cancellationError();
596
+ } catch (error) {
597
+ return finish(error, true);
598
+ }
599
+ }
600
+ latest.retry = eventIds(pending);
601
+ latest.drops = drops;
602
+ latest.outcomes = outcomes;
603
+ return latest;
604
+ };
605
+ const sendCaptureV1TeardownBatches = (runtime, messages, libraryVersion, options = {})=>{
606
+ const result = {
607
+ attempted: [],
608
+ overflow: [],
609
+ bytes: 0
610
+ };
611
+ if (0 === messages.length || !canContinue(options.canContinue)) return result;
612
+ const fetch = runtime[2];
613
+ if (!fetch) {
614
+ try {
615
+ options.onError?.(new Error('Fetch is not available'));
616
+ } catch {}
617
+ return result;
618
+ }
619
+ const now = options.now ?? Date.now;
620
+ let remaining = Math.max(0, Math.floor(Number.isFinite(options.maxBytes) ? options.maxBytes : CAPTURE_V1_TEARDOWN_BUDGET_BYTES));
621
+ let prepared;
622
+ try {
623
+ prepared = prepareEvents(messages);
624
+ } catch (error) {
625
+ try {
626
+ options.onError?.(error);
627
+ } catch {}
628
+ return result;
629
+ }
630
+ for(let index = 0; index < prepared.length && canContinue(options.canContinue);){
631
+ remaining = Math.min(remaining, options.budget?.remaining ?? remaining);
632
+ const createdAt = isoNow(now);
633
+ const batch = [];
634
+ let body = serializeEnvelope(createdAt, batch);
635
+ let bodyBytes = utf8Bytes(body);
636
+ while(index + batch.length < prepared.length && batch.length < CAPTURE_V1_MAX_BATCH_EVENTS){
637
+ const candidate = prepared[index + batch.length];
638
+ const candidateBody = serializeEnvelope(createdAt, [
639
+ ...batch,
640
+ candidate
641
+ ]);
642
+ const candidateBytes = utf8Bytes(candidateBody);
643
+ if (candidateBytes > remaining || batch.length > 0 && candidateBytes > CAPTURE_V1_BATCH_TARGET_BYTES) break;
644
+ batch.push(candidate);
645
+ body = candidateBody;
646
+ bodyBytes = candidateBytes;
647
+ }
648
+ if (0 === batch.length) {
649
+ result.overflow.push(...prepared.slice(index).map(({ source })=>source));
650
+ break;
651
+ }
652
+ remaining -= bodyBytes;
653
+ result.bytes += bodyBytes;
654
+ result.attempted.push(...batch.map(({ source })=>source));
655
+ index += batch.length;
656
+ let requestId;
657
+ try {
658
+ requestId = (options.generateRequestId ?? external_id_js_namespaceObject.createId)();
659
+ } catch {
660
+ requestId = `capture-${createdAt}`;
661
+ }
662
+ const headers = {
663
+ 'Content-Type': 'application/json',
664
+ Authorization: `Bearer ${runtime[1]}`,
665
+ 'PostHog-Sdk-Info': `posthog-js/${libraryVersion}`,
666
+ 'PostHog-Attempt': '1',
667
+ 'PostHog-Request-Id': requestId,
668
+ 'PostHog-Request-Timestamp': isoNow(now)
669
+ };
670
+ const budget = options.budget;
671
+ if (budget) budget.remaining -= bodyBytes;
672
+ const release = ()=>{
673
+ if (budget) budget.remaining += bodyBytes;
674
+ };
675
+ try {
676
+ const request = fetch(`${runtime[0].api}/i/v1/analytics/events`, {
677
+ method: 'POST',
678
+ credentials: 'omit',
679
+ headers,
680
+ body,
681
+ keepalive: true
682
+ });
683
+ Promise.resolve(request).then(cancelResponseBody, (error)=>{
684
+ try {
685
+ options.onError?.(error);
686
+ } catch {}
687
+ }).then(release, release);
688
+ } catch (error) {
689
+ release();
690
+ try {
691
+ options.onError?.(error);
692
+ } catch {}
693
+ }
694
+ }
695
+ return result;
696
+ };
697
+ const sendCaptureV1Batches = async (runtime, messages, libraryVersion, options = {})=>{
698
+ if (0 === messages.length) return {
699
+ statusCode: 204,
700
+ retry: [],
701
+ retryMessages: [],
702
+ drops: [],
703
+ outcomes: {}
704
+ };
705
+ const now = options.now ?? Date.now;
706
+ const elapsedNow = options.elapsedNow ?? (()=>globalThis.performance?.now() ?? Date.now());
707
+ const maxElapsedMs = Math.floor(numberOption(options.maxElapsedMs, 60000, 1));
708
+ const startedAt = safeNow(elapsedNow);
709
+ const remainingTime = ()=>maxElapsedMs - Math.max(0, safeNow(elapsedNow) - startedAt);
710
+ const partitionCreatedAt = isoNow(now);
711
+ let events;
712
+ try {
713
+ events = prepareEvents(messages);
714
+ } catch (error) {
715
+ return {
716
+ ...failedResult(messages, error),
717
+ retryMessages: messages
718
+ };
719
+ }
720
+ const maxBatchEvents = Math.floor(numberOption(options.maxBatchEvents, CAPTURE_V1_MAX_BATCH_EVENTS, 1));
721
+ const targetBatchBytes = Math.floor(numberOption(options.targetBatchBytes, CAPTURE_V1_BATCH_TARGET_BYTES, 1));
722
+ const batches = partitionEvents(events, partitionCreatedAt, maxBatchEvents, targetBatchBytes);
723
+ const aggregate = {
724
+ statusCode: 204,
725
+ retry: [],
726
+ retryMessages: [],
727
+ drops: [],
728
+ outcomes: {}
729
+ };
730
+ for(let index = 0; index < batches.length; index++){
731
+ const remaining = remainingTime();
732
+ const cancelled = !canContinue(options.canRetry) || options.signal?.aborted;
733
+ if (cancelled || remaining <= 0) {
734
+ const unsent = batches.slice(index).flat();
735
+ aggregate.retry.push(...eventIds(unsent));
736
+ aggregate.retryMessages.push(...unsent.map(({ source })=>source));
737
+ const terminalError = new Error(cancelled ? 'Capture V1 retry was cancelled' : 'Capture V1 exhausted its elapsed retry budget');
738
+ aggregate.error ??= terminalError;
739
+ aggregate.terminalError ??= terminalError;
740
+ break;
741
+ }
742
+ const batch = batches[index];
743
+ const createdAt = isoNow(now);
744
+ const result = await sendCaptureV1Batch(runtime, batch.map(({ source })=>source), libraryVersion, {
745
+ ...options,
746
+ createdAt,
747
+ prepared: batch,
748
+ maxElapsedMs: remaining
749
+ });
750
+ aggregate.statusCode = result.statusCode;
751
+ aggregate.retry.push(...result.retry);
752
+ const retryIds = new Set(result.retry);
753
+ aggregate.retryMessages.push(...batch.filter(({ uuid })=>retryIds.has(uuid)).map(({ source })=>source));
754
+ aggregate.drops.push(...result.drops);
755
+ mergeOutcomes(aggregate.outcomes, result.outcomes);
756
+ if (void 0 !== result.error) aggregate.error ??= result.error;
757
+ if (void 0 !== result.terminalError) aggregate.terminalError ??= result.terminalError;
758
+ }
759
+ return aggregate;
760
+ };
761
+ exports.CAPTURE_V1_BATCH_TARGET_BYTES = __webpack_exports__.CAPTURE_V1_BATCH_TARGET_BYTES;
762
+ exports.CAPTURE_V1_COMPRESSION_THRESHOLD_BYTES = __webpack_exports__.CAPTURE_V1_COMPRESSION_THRESHOLD_BYTES;
763
+ exports.CAPTURE_V1_MAX_BATCH_EVENTS = __webpack_exports__.CAPTURE_V1_MAX_BATCH_EVENTS;
764
+ exports.CAPTURE_V1_TEARDOWN_BUDGET_BYTES = __webpack_exports__.CAPTURE_V1_TEARDOWN_BUDGET_BYTES;
765
+ exports.buildCaptureV1Event = __webpack_exports__.buildCaptureV1Event;
766
+ exports.sendCaptureV1Batch = __webpack_exports__.sendCaptureV1Batch;
767
+ exports.sendCaptureV1Batches = __webpack_exports__.sendCaptureV1Batches;
768
+ exports.sendCaptureV1TeardownBatches = __webpack_exports__.sendCaptureV1TeardownBatches;
769
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
770
+ "CAPTURE_V1_BATCH_TARGET_BYTES",
771
+ "CAPTURE_V1_COMPRESSION_THRESHOLD_BYTES",
772
+ "CAPTURE_V1_MAX_BATCH_EVENTS",
773
+ "CAPTURE_V1_TEARDOWN_BUDGET_BYTES",
774
+ "buildCaptureV1Event",
775
+ "sendCaptureV1Batch",
776
+ "sendCaptureV1Batches",
777
+ "sendCaptureV1TeardownBatches"
778
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
779
+ Object.defineProperty(exports, '__esModule', {
780
+ value: true
781
+ });