posthog-node 6.4.1 → 6.4.2

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