@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,507 @@
1
+ import { uuidv7 } from "../vendor/uuidv7.mjs";
2
+ import { webCompressor } from "./compression.mjs";
3
+ import { CaptureError, CaptureLossTally, describeCaptureLoss } from "./errors.mjs";
4
+ import { buildV1Body } from "./serialize.mjs";
5
+ import { canonicalizeUuid } from "./uuid.mjs";
6
+ const RETRY_BASE_DELAY_MS = 100;
7
+ const MAX_RETRY_DELAY_MS = 30000;
8
+ async function raceAbort(work, signal) {
9
+ if (!signal) return work;
10
+ let onAbort;
11
+ const aborted = new Promise((_resolve, reject)=>{
12
+ onAbort = ()=>{
13
+ const abortError = new Error('Capture V1 request aborted while compressing the body');
14
+ abortError.name = 'AbortError';
15
+ abortError.cause = signal.reason;
16
+ reject(abortError);
17
+ };
18
+ if (signal.aborted) onAbort();
19
+ else signal.addEventListener('abort', onAbort, {
20
+ once: true
21
+ });
22
+ });
23
+ try {
24
+ return await Promise.race([
25
+ work,
26
+ aborted
27
+ ]);
28
+ } finally{
29
+ signal.removeEventListener('abort', onAbort);
30
+ }
31
+ }
32
+ const COMPRESSION_TIMED_OUT = Symbol('compression timed out');
33
+ function abortableSleep(ms, signal) {
34
+ return new Promise((resolve)=>{
35
+ const onAbort = ()=>{
36
+ clearTimeout(timer);
37
+ resolve();
38
+ };
39
+ const timer = setTimeout(()=>{
40
+ signal?.removeEventListener('abort', onAbort);
41
+ resolve();
42
+ }, ms);
43
+ signal?.addEventListener('abort', onAbort, {
44
+ once: true
45
+ });
46
+ });
47
+ }
48
+ const RETRYABLE_STATUSES = new Set([
49
+ 404,
50
+ 408,
51
+ 429,
52
+ 500,
53
+ 502,
54
+ 503,
55
+ 504
56
+ ]);
57
+ const FOLLOWED_REDIRECT_STATUSES = new Set([
58
+ 307,
59
+ 308
60
+ ]);
61
+ const MAX_REDIRECTS = 5;
62
+ const timeoutErrors = new WeakSet();
63
+ const DUPLICATE_EVENT_UUID = 'duplicate_event_uuid';
64
+ class V1CaptureSender {
65
+ constructor(config, hooks){
66
+ this.config = config;
67
+ this.hostOrigin = originOf(config.host);
68
+ this.fetchFn = hooks.fetch;
69
+ this.onError = hooks.onError;
70
+ this.now = hooks.now ?? Date.now;
71
+ this.sleep = hooks.sleep ?? abortableSleep;
72
+ this.generateRequestId = hooks.generateRequestId ?? uuidv7;
73
+ this.random = hooks.random ?? Math.random;
74
+ this.compress = hooks.compress ?? webCompressor.compress;
75
+ }
76
+ async send(events, options = {}) {
77
+ if (0 === events.length) return [];
78
+ const { signal, keepUnsent = false, onDeferred, retryOf } = options;
79
+ const requestId = retryOf?.requestId ?? this.generateRequestId();
80
+ const createdAt = retryOf?.createdAt ?? new Date(this.now()).toISOString();
81
+ const attemptsBefore = retryOf?.attempt ?? 0;
82
+ let lastAttempt = attemptsBefore;
83
+ const url = `${this.config.host}${this.config.path}`;
84
+ const drops = [];
85
+ const loss = new CaptureLossTally();
86
+ let pending = events;
87
+ const unsent = (cause, failure)=>{
88
+ if (keepUnsent) {
89
+ this.surfacePartialDrops(requestId, drops, loss);
90
+ const timedOut = cause instanceof Error && timeoutErrors.has(cause);
91
+ onDeferred?.({
92
+ reason: failure,
93
+ tooLarge: false,
94
+ ...timedOut ? {
95
+ timedOut
96
+ } : {},
97
+ request: {
98
+ requestId,
99
+ createdAt,
100
+ attempt: lastAttempt
101
+ }
102
+ });
103
+ return pending;
104
+ }
105
+ this.surfaceBatchFailure(requestId, drops, pending, cause, loss, failure);
106
+ return [];
107
+ };
108
+ const deferred = (kept, deferral)=>{
109
+ this.surfacePartialDrops(requestId, drops, loss);
110
+ onDeferred?.({
111
+ ...deferral,
112
+ request: {
113
+ requestId,
114
+ createdAt,
115
+ attempt: lastAttempt
116
+ }
117
+ });
118
+ return kept;
119
+ };
120
+ const { maxRetries } = this.config;
121
+ const maxAttempts = (Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 0) + 1;
122
+ for(let attempt = 1; attempt <= maxAttempts; attempt++){
123
+ if (signal?.aborted) return unsent(signal.reason, 'not sent: aborted');
124
+ const isLastAttempt = attempt === maxAttempts;
125
+ const payload = buildV1Body(pending, {
126
+ createdAt,
127
+ historicalMigration: this.config.historicalMigration
128
+ });
129
+ let captureAttempt;
130
+ let retryDelayMs;
131
+ try {
132
+ lastAttempt = attemptsBefore + attempt;
133
+ captureAttempt = await this.sendOnce(url, payload, lastAttempt, requestId, signal);
134
+ const { response, signal: attemptSignal, redirectFailure } = captureAttempt;
135
+ const { status } = response;
136
+ if (void 0 !== redirectFailure) {
137
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
138
+ const failure = `failed on a redirect it does not follow (HTTP ${status})`;
139
+ this.surfaceBatchFailure(requestId, drops, pending, new Error(redirectFailure), loss, failure);
140
+ return [];
141
+ }
142
+ if (status < 200 || status >= 300) {
143
+ const tooLarge = 413 === status && pending.length > 1;
144
+ if (onDeferred && (tooLarge || isLastAttempt && RETRYABLE_STATUSES.has(status))) {
145
+ const retryAfterMs = this.parseRetryAfter(response);
146
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
147
+ return deferred(pending, {
148
+ reason: `HTTP ${status}`,
149
+ retryAfterMs,
150
+ tooLarge
151
+ });
152
+ }
153
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
154
+ const retryAfterMs = this.parseRetryAfter(response);
155
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
156
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
157
+ } else {
158
+ const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);
159
+ this.surfaceBatchFailure(requestId, drops, pending, httpError, loss, `failed with HTTP ${status}`);
160
+ return [];
161
+ }
162
+ } else {
163
+ let parsed;
164
+ try {
165
+ parsed = await captureAttempt.waitFor(this.parseResponse(response));
166
+ } catch (error) {
167
+ if (attemptSignal.aborted) throw error;
168
+ this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`), loss, `failed with an unreadable response (HTTP ${status})`);
169
+ return [];
170
+ }
171
+ const dropsBefore = drops.length;
172
+ const retryable = this.classify(pending, parsed, drops);
173
+ for (const drop of drops.slice(dropsBefore)){
174
+ const cause = drop.details === DUPLICATE_EVENT_UUID ? 'dropped as duplicate uuids' : 'dropped by the server';
175
+ loss.add(`${cause} (HTTP ${status})`, 1);
176
+ }
177
+ if (0 === retryable.length) {
178
+ this.surfacePartialDrops(requestId, drops, loss);
179
+ return [];
180
+ }
181
+ if (isLastAttempt && onDeferred) return deferred(retryable, {
182
+ reason: 'the server asked to retry them',
183
+ retryAfterMs: this.parseRetryAfter(response),
184
+ tooLarge: false
185
+ });
186
+ if (isLastAttempt) {
187
+ loss.add(`still marked for retry after ${maxAttempts} attempt(s) (HTTP ${status})`, retryable.length);
188
+ this.report(this.captureError({
189
+ requestId,
190
+ drops,
191
+ retryExhausted: retryable.map((event)=>event.uuid)
192
+ }), loss);
193
+ return [];
194
+ }
195
+ pending = retryable;
196
+ const retryAfterMs = this.parseRetryAfter(response);
197
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
198
+ }
199
+ } catch (transportError) {
200
+ if (captureAttempt && !captureAttempt.signal.aborted) throw transportError;
201
+ if (isLastAttempt || signal?.aborted) return unsent(transportError, this.describeTransportFailure(transportError, signal));
202
+ retryDelayMs = this.backoffDelay(attempt);
203
+ } finally{
204
+ captureAttempt?.cleanup();
205
+ }
206
+ if (void 0 !== retryDelayMs) await this.sleepUnlessAborted(retryDelayMs, signal);
207
+ }
208
+ return [];
209
+ }
210
+ async sleepUnlessAborted(ms, signal) {
211
+ if (!signal) return this.sleep(ms);
212
+ if (signal.aborted) return;
213
+ let onAbort;
214
+ const aborted = new Promise((resolve)=>{
215
+ onAbort = resolve;
216
+ signal.addEventListener('abort', onAbort, {
217
+ once: true
218
+ });
219
+ });
220
+ try {
221
+ await Promise.race([
222
+ this.sleep(ms, signal),
223
+ aborted
224
+ ]);
225
+ } finally{
226
+ signal.removeEventListener('abort', onAbort);
227
+ }
228
+ }
229
+ async sendOnce(url, payload, attempt, requestId, externalSignal) {
230
+ const { body, contentEncoding } = await this.encodeBody(payload, externalSignal);
231
+ const headers = this.buildHeaders(attempt, requestId);
232
+ if (contentEncoding) headers['Content-Encoding'] = contentEncoding;
233
+ const controller = new AbortController();
234
+ let timeoutPhase = 'waiting for response headers';
235
+ let timer;
236
+ let onExternalAbort;
237
+ const stopListening = ()=>{
238
+ if (onExternalAbort) externalSignal?.removeEventListener('abort', onExternalAbort);
239
+ };
240
+ const deadline = new Promise((_resolve, reject)=>{
241
+ const abortWith = (error)=>{
242
+ reject(error);
243
+ controller.abort(error);
244
+ };
245
+ timer = setTimeout(()=>{
246
+ const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);
247
+ timeoutError.name = 'AbortError';
248
+ timeoutErrors.add(timeoutError);
249
+ abortWith(timeoutError);
250
+ }, this.config.requestTimeoutMs);
251
+ if (externalSignal) {
252
+ onExternalAbort = ()=>{
253
+ const abortError = new Error(`Capture V1 request aborted ${timeoutPhase}`);
254
+ abortError.name = 'AbortError';
255
+ abortError.cause = externalSignal.reason;
256
+ abortWith(abortError);
257
+ };
258
+ if (externalSignal.aborted) onExternalAbort();
259
+ else externalSignal.addEventListener('abort', onExternalAbort, {
260
+ once: true
261
+ });
262
+ }
263
+ });
264
+ deadline.catch(()=>{});
265
+ try {
266
+ const fetchPromise = this.fetchFollowingRedirects(url, headers, body, controller.signal);
267
+ let responseAccepted = false;
268
+ fetchPromise.then((late)=>{
269
+ if (controller.signal.aborted && !responseAccepted) this.cancelBody(late.response);
270
+ }).catch(()=>{});
271
+ const { response, redirectFailure } = await Promise.race([
272
+ fetchPromise,
273
+ deadline
274
+ ]);
275
+ responseAccepted = true;
276
+ timeoutPhase = 'while reading the response body';
277
+ let cleanedUp = false;
278
+ let cancellation;
279
+ const cancelBody = ()=>cancellation ??= this.cancelBody(response);
280
+ return {
281
+ response,
282
+ redirectFailure,
283
+ signal: controller.signal,
284
+ waitFor: (operation)=>Promise.race([
285
+ operation,
286
+ deadline
287
+ ]),
288
+ cancelBody,
289
+ cleanup: ()=>{
290
+ if (cleanedUp) return;
291
+ cleanedUp = true;
292
+ clearTimeout(timer);
293
+ stopListening();
294
+ if (controller.signal.aborted) cancelBody();
295
+ }
296
+ };
297
+ } catch (error) {
298
+ clearTimeout(timer);
299
+ stopListening();
300
+ throw error;
301
+ }
302
+ }
303
+ async fetchFollowingRedirects(url, headers, body, signal) {
304
+ let target = url;
305
+ for(let redirects = 0;; redirects++){
306
+ const response = await this.fetchFn(target, {
307
+ method: 'POST',
308
+ headers,
309
+ body: 'string' == typeof body ? body : body.slice(),
310
+ signal,
311
+ redirect: 'manual'
312
+ });
313
+ const { status } = response;
314
+ if (status < 300 || status >= 400) return {
315
+ response
316
+ };
317
+ if (!FOLLOWED_REDIRECT_STATUSES.has(status)) return {
318
+ response,
319
+ redirectFailure: `Capture V1 request got an HTTP ${status} redirect, which it does not follow`
320
+ };
321
+ if (redirects === MAX_REDIRECTS) return {
322
+ response,
323
+ redirectFailure: `Capture V1 request was redirected more than ${MAX_REDIRECTS} times`
324
+ };
325
+ const next = resolveLocation(response.headers?.get('Location'), target);
326
+ if (void 0 === next || originOf(next) !== this.hostOrigin) return {
327
+ response,
328
+ redirectFailure: `Capture V1 request got an HTTP ${status} redirect away from the configured host`
329
+ };
330
+ this.cancelBody(response);
331
+ if (signal.aborted) throw signal.reason;
332
+ target = next;
333
+ }
334
+ }
335
+ async encodeBody(payload, signal) {
336
+ const codec = this.config.compression;
337
+ if ('none' === codec) return {
338
+ body: payload
339
+ };
340
+ let timer;
341
+ try {
342
+ const compression = this.compress(payload, codec);
343
+ compression.catch(()=>{});
344
+ const timedOut = new Promise((resolve)=>{
345
+ timer = setTimeout(()=>resolve(COMPRESSION_TIMED_OUT), this.config.requestTimeoutMs);
346
+ });
347
+ const compressed = await raceAbort(Promise.race([
348
+ compression,
349
+ timedOut
350
+ ]), signal);
351
+ if (compressed === COMPRESSION_TIMED_OUT) {
352
+ if (this.config.isDebug) console.error(`Capture request body ${codec} compression took over ${this.config.requestTimeoutMs}ms, sending it uncompressed`);
353
+ } else if (null !== compressed) return {
354
+ body: compressed,
355
+ contentEncoding: codec
356
+ };
357
+ } catch (error) {
358
+ if (signal?.aborted) throw error;
359
+ if (this.config.isDebug) console.error(`Failed to ${codec} compress the capture request body`, error);
360
+ } finally{
361
+ clearTimeout(timer);
362
+ }
363
+ return {
364
+ body: payload
365
+ };
366
+ }
367
+ buildHeaders(attempt, requestId) {
368
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
369
+ const headers = {
370
+ 'Content-Type': 'application/json',
371
+ Authorization: `Bearer ${this.config.projectToken ?? this.config.apiKey}`,
372
+ 'PostHog-Sdk-Info': sdkInfo,
373
+ 'PostHog-Attempt': String(attempt),
374
+ 'PostHog-Request-Id': requestId,
375
+ 'PostHog-Request-Timestamp': new Date(this.now()).toISOString()
376
+ };
377
+ if (this.config.userAgent) headers['User-Agent'] = this.config.userAgent;
378
+ const extraHeaders = this.config.extraHeaders;
379
+ if (extraHeaders) {
380
+ const reserved = new Set([
381
+ 'user-agent',
382
+ 'content-encoding',
383
+ ...Object.keys(headers).map((name)=>name.toLowerCase())
384
+ ]);
385
+ for (const [name, value] of Object.entries(extraHeaders))if (!reserved.has(name.toLowerCase())) headers[name] = value;
386
+ }
387
+ return headers;
388
+ }
389
+ classify(pending, parsed, drops) {
390
+ const results = new Map();
391
+ for (const [uuid, result] of Object.entries(parsed.results))results.set(canonicalizeUuid(uuid) ?? uuid, result);
392
+ const retryable = [];
393
+ let copiesSeen;
394
+ for (const event of pending){
395
+ const result = results.get(event.uuid);
396
+ if (!result) continue;
397
+ const duplicates = result.duplicates_dropped;
398
+ if ('number' == typeof duplicates && Number.isSafeInteger(duplicates) && duplicates > 0) {
399
+ copiesSeen ??= new Map();
400
+ const copy = copiesSeen.get(event.uuid) ?? 0;
401
+ copiesSeen.set(event.uuid, copy + 1);
402
+ if (copy >= 1 && copy <= duplicates) {
403
+ drops.push({
404
+ uuid: event.uuid,
405
+ details: DUPLICATE_EVENT_UUID
406
+ });
407
+ continue;
408
+ }
409
+ }
410
+ if ('drop' === result.result) drops.push({
411
+ uuid: event.uuid,
412
+ details: result.details ?? void 0
413
+ });
414
+ else if ('retry' === result.result) retryable.push(event);
415
+ }
416
+ return retryable;
417
+ }
418
+ backoffDelay(attempt, retryAfterMs) {
419
+ const jitter = 0.75 + 0.5 * this.random();
420
+ const backoff = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1) * jitter, MAX_RETRY_DELAY_MS);
421
+ if (void 0 === retryAfterMs) return backoff;
422
+ return Math.max(backoff, Math.min(retryAfterMs, MAX_RETRY_DELAY_MS));
423
+ }
424
+ parseRetryAfter(response) {
425
+ const raw = response.headers?.get('Retry-After');
426
+ if (!raw) return;
427
+ const trimmed = raw.trim();
428
+ if (/^\d+$/.test(trimmed)) {
429
+ const seconds = parseInt(trimmed, 10);
430
+ return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : void 0;
431
+ }
432
+ const dateMs = Date.parse(trimmed);
433
+ if (Number.isNaN(dateMs)) return;
434
+ const delta = dateMs - this.now();
435
+ return delta > 0 ? delta : void 0;
436
+ }
437
+ async parseResponse(response) {
438
+ const text = await response.text();
439
+ const parsed = JSON.parse(text);
440
+ if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');
441
+ const results = parsed.results;
442
+ if ('object' != typeof results || null === results || Array.isArray(results)) throw new Error('unexpected results shape');
443
+ return {
444
+ results: results
445
+ };
446
+ }
447
+ async buildHttpError(response, status, waitFor) {
448
+ let bodyText = '';
449
+ try {
450
+ bodyText = (await waitFor(response.text())).slice(0, 512);
451
+ } catch {}
452
+ const suffix = bodyText ? `: ${bodyText}` : '';
453
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
454
+ }
455
+ surfaceBatchFailure(requestId, drops, pending, cause, loss, failure) {
456
+ loss.add(failure, pending.length);
457
+ this.report(this.captureError({
458
+ requestId,
459
+ drops,
460
+ retryExhausted: pending.map((event)=>event.uuid),
461
+ cause
462
+ }), loss);
463
+ }
464
+ surfacePartialDrops(requestId, drops, loss) {
465
+ if (drops.length > 0) this.report(this.captureError({
466
+ requestId,
467
+ drops,
468
+ retryExhausted: []
469
+ }), loss);
470
+ }
471
+ report(error, loss) {
472
+ this.onError(error, describeCaptureLoss(this.config.path, loss));
473
+ }
474
+ describeTransportFailure(error, signal) {
475
+ if (error instanceof Error && timeoutErrors.has(error)) return 'failed: request timed out';
476
+ if (signal?.aborted) return 'failed: request aborted';
477
+ const name = error instanceof Error && /^\w{1,64}$/.test(error.name) ? error.name : 'unknown';
478
+ return `failed with a network error (${name})`;
479
+ }
480
+ captureError(params) {
481
+ return new CaptureError({
482
+ endpoint: this.config.path,
483
+ ...params
484
+ });
485
+ }
486
+ async cancelBody(response) {
487
+ try {
488
+ await response.body?.cancel();
489
+ } catch {}
490
+ }
491
+ }
492
+ function originOf(url) {
493
+ try {
494
+ return new URL(url).origin;
495
+ } catch {
496
+ return;
497
+ }
498
+ }
499
+ function resolveLocation(location, base) {
500
+ if (!location) return;
501
+ try {
502
+ return new URL(location, base).href;
503
+ } catch {
504
+ return;
505
+ }
506
+ }
507
+ export { DUPLICATE_EVENT_UUID, MAX_RETRY_DELAY_MS, RETRY_BASE_DELAY_MS, V1CaptureSender };
@@ -0,0 +1,30 @@
1
+ import type { PostHogEventProperties } from '../types';
2
+ /** UTF-8 size of `value`. */
3
+ export declare function utf8Length(value: string): number;
4
+ /** One wire event, serialized once and reused verbatim in every request body that carries it. */
5
+ export interface SerializedV1Event {
6
+ uuid: string;
7
+ json: string;
8
+ /** UTF-8 size of `json`. */
9
+ bytes: number;
10
+ /** UTF-8 size of the serialized `properties` object alone, which is what the AI endpoint limits. */
11
+ propertiesBytes: number;
12
+ }
13
+ /**
14
+ * Why capture would reject this event, or undefined when it can be sent. A name must be a non-empty string, the
15
+ * distinct id a string, and the name and ids well-formed Unicode: a broken id is never repaired, because two broken ids
16
+ * could collapse into one.
17
+ */
18
+ export declare function wireProblem(message: PostHogEventProperties): string | undefined;
19
+ export declare function serializeV1Event(message: PostHogEventProperties): SerializedV1Event;
20
+ /**
21
+ * The Capture V1 batch envelope, built from already-serialized events. Unlike v0 there is no
22
+ * `api_key` (Bearer auth) and no `sent_at`. `historical_migration` is omitted when false.
23
+ */
24
+ export declare function buildV1Body(events: readonly {
25
+ json: string;
26
+ }[], { createdAt, historicalMigration }: {
27
+ createdAt: string;
28
+ historicalMigration: boolean;
29
+ }): string;
30
+ //# sourceMappingURL=serialize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serialize.d.ts","sourceRoot":"","sources":["../../src/capture-v1/serialize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAA;AAUtD,6BAA6B;AAC7B,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD;AA6BD,iGAAiG;AACjG,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,4BAA4B;IAC5B,KAAK,EAAE,MAAM,CAAA;IACb,oGAAoG;IACpG,eAAe,EAAE,MAAM,CAAA;CACxB;AAQD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,sBAAsB,GAAG,MAAM,GAAG,SAAS,CAe/E;AAQD,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,sBAAsB,GAAG,iBAAiB,CAcnF;AAED;;;GAGG;AACH,wBAAgB,WAAW,CACzB,MAAM,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,EACnC,EAAE,SAAS,EAAE,mBAAmB,EAAE,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,mBAAmB,EAAE,OAAO,CAAA;CAAE,GACtF,MAAM,CAGR"}
@@ -0,0 +1,106 @@
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
+ buildV1Body: ()=>buildV1Body,
32
+ serializeV1Event: ()=>serializeV1Event,
33
+ utf8Length: ()=>utf8Length,
34
+ wireProblem: ()=>wireProblem
35
+ });
36
+ const string_utils_js_namespaceObject = require("../utils/string-utils.js");
37
+ const external_transform_js_namespaceObject = require("./transform.js");
38
+ const encoder = "u" < typeof TextEncoder ? void 0 : new TextEncoder();
39
+ function utf8Length(value) {
40
+ return encoder ? encoder.encode(value).length : countUtf8Bytes(value);
41
+ }
42
+ function countUtf8Bytes(value) {
43
+ let bytes = 0;
44
+ for(let index = 0; index < value.length; index++){
45
+ const code = value.charCodeAt(index);
46
+ if (code < 0x80) bytes += 1;
47
+ else if (code < 0x800) bytes += 2;
48
+ else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) {
49
+ const next = value.charCodeAt(index + 1);
50
+ if (next >= 0xdc00 && next <= 0xdfff) {
51
+ bytes += 4;
52
+ index++;
53
+ } else bytes += 3;
54
+ } else bytes += 3;
55
+ }
56
+ return bytes;
57
+ }
58
+ const PROPERTIES_KEY = ',"properties":';
59
+ const PROPERTIES_KEY_BYTES = utf8Length(PROPERTIES_KEY);
60
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
61
+ const LONE_SURROGATE_ESCAPE = /\\\\|\\u[dD][89a-fA-F][0-9a-fA-F]{2}/g;
62
+ function wireProblem(message) {
63
+ const { event, distinct_id: distinctId, properties } = message;
64
+ if ('string' != typeof event || '' === event) return 'event name is missing, empty or not a string';
65
+ if ('string' != typeof distinctId) return 'distinct id is missing or not a string';
66
+ const props = properties ?? {};
67
+ const ids = [
68
+ event,
69
+ distinctId,
70
+ props.$session_id,
71
+ props.$window_id
72
+ ];
73
+ if (ids.some((value)=>'string' == typeof value && LONE_SURROGATE.test(value))) return 'event name or id is not well-formed Unicode';
74
+ }
75
+ function repairLoneSurrogates(json) {
76
+ return json.includes('\\ud') || json.includes('\\uD') ? json.replace(LONE_SURROGATE_ESCAPE, (match)=>2 === match.length ? match : '\\ufffd') : json;
77
+ }
78
+ function serializeV1Event(message) {
79
+ const { properties, ...rest } = (0, external_transform_js_namespaceObject.buildV1Event)(message);
80
+ const restJson = repairLoneSurrogates((0, string_utils_js_namespaceObject.safeJsonStringify)(rest));
81
+ const propertiesJson = repairLoneSurrogates((0, string_utils_js_namespaceObject.safeJsonStringify)(properties));
82
+ const propertiesBytes = utf8Length(propertiesJson);
83
+ return {
84
+ uuid: rest.uuid,
85
+ json: `${restJson.slice(0, -1)}${PROPERTIES_KEY}${propertiesJson}}`,
86
+ bytes: utf8Length(restJson) + PROPERTIES_KEY_BYTES + propertiesBytes,
87
+ propertiesBytes
88
+ };
89
+ }
90
+ function buildV1Body(events, { createdAt, historicalMigration }) {
91
+ const migration = historicalMigration ? ',"historical_migration":true' : '';
92
+ return `{"created_at":${JSON.stringify(createdAt)}${migration},"batch":[${events.map((event)=>event.json).join(',')}]}`;
93
+ }
94
+ exports.buildV1Body = __webpack_exports__.buildV1Body;
95
+ exports.serializeV1Event = __webpack_exports__.serializeV1Event;
96
+ exports.utf8Length = __webpack_exports__.utf8Length;
97
+ exports.wireProblem = __webpack_exports__.wireProblem;
98
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
99
+ "buildV1Body",
100
+ "serializeV1Event",
101
+ "utf8Length",
102
+ "wireProblem"
103
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
104
+ Object.defineProperty(exports, '__esModule', {
105
+ value: true
106
+ });