posthog-node 5.40.0 → 5.41.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 (41) hide show
  1. package/LICENSE +2 -2
  2. package/dist/capture-v1/config.d.ts +11 -0
  3. package/dist/capture-v1/config.d.ts.map +1 -0
  4. package/dist/capture-v1/config.js +42 -0
  5. package/dist/capture-v1/config.mjs +8 -0
  6. package/dist/capture-v1/errors.d.ts +32 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +49 -0
  9. package/dist/capture-v1/errors.mjs +15 -0
  10. package/dist/capture-v1/routing.d.ts +21 -0
  11. package/dist/capture-v1/routing.d.ts.map +1 -0
  12. package/dist/capture-v1/routing.js +47 -0
  13. package/dist/capture-v1/routing.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +70 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +222 -0
  17. package/dist/capture-v1/sender.mjs +188 -0
  18. package/dist/capture-v1/transform.d.ts +34 -0
  19. package/dist/capture-v1/transform.d.ts.map +1 -0
  20. package/dist/capture-v1/transform.js +142 -0
  21. package/dist/capture-v1/transform.mjs +99 -0
  22. package/dist/capture-v1/types.d.ts +50 -0
  23. package/dist/capture-v1/types.d.ts.map +1 -0
  24. package/dist/capture-v1/types.js +18 -0
  25. package/dist/capture-v1/types.mjs +0 -0
  26. package/dist/client.d.ts +22 -1
  27. package/dist/client.d.ts.map +1 -1
  28. package/dist/client.js +42 -0
  29. package/dist/client.mjs +43 -1
  30. package/dist/version.d.ts +1 -1
  31. package/dist/version.js +1 -1
  32. package/dist/version.mjs +1 -1
  33. package/package.json +2 -2
  34. package/src/capture-v1/config.ts +18 -0
  35. package/src/capture-v1/errors.ts +52 -0
  36. package/src/capture-v1/routing.ts +28 -0
  37. package/src/capture-v1/sender.ts +298 -0
  38. package/src/capture-v1/transform.ts +159 -0
  39. package/src/capture-v1/types.ts +55 -0
  40. package/src/client.ts +77 -0
  41. package/src/version.ts +1 -1
package/LICENSE CHANGED
@@ -327,12 +327,12 @@ SOFTWARE.
327
327
 
328
328
  ---
329
329
 
330
- Some files in this codebase contain code from MCPCat/mcpcat-typescript-sdk.
330
+ Some files in this codebase contain code from agentcathq/agentcat-typescript-sdk (formerly MCPCat/mcpcat-typescript-sdk).
331
331
  In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases.
332
332
 
333
333
  MIT License
334
334
 
335
- Copyright (c) 2025 MCPcat
335
+ Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat)
336
336
 
337
337
  Permission is hereby granted, free of charge, to any person obtaining a copy
338
338
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,11 @@
1
+ /** Capture submission mode: `v0` is the legacy `/batch/` endpoint, `v1` is `/i/v1/analytics/events`. */
2
+ export type CaptureMode = 'v0' | 'v1';
3
+ /**
4
+ * Resolve the effective capture mode from the `POSTHOG_CAPTURE_MODE` environment
5
+ * variable (guarded for edge / no-`process` runtimes). The default is `v0`, so
6
+ * existing users are unaffected unless they explicitly opt in. Capture V1 is
7
+ * intentionally env-var-only during the transition — there is no public option,
8
+ * so nothing on the API surface has to be removed when v1 becomes the default.
9
+ */
10
+ export declare function resolveCaptureMode(): CaptureMode;
11
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/capture-v1/config.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,MAAM,MAAM,WAAW,GAAG,IAAI,GAAG,IAAI,CAAA;AAMrC;;;;;;GAMG;AACH,wBAAgB,kBAAkB,IAAI,WAAW,CAGhD"}
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ resolveCaptureMode: ()=>resolveCaptureMode
28
+ });
29
+ function isCaptureMode(value) {
30
+ return 'v0' === value || 'v1' === value;
31
+ }
32
+ function resolveCaptureMode() {
33
+ const envMode = 'undefined' != typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;
34
+ return isCaptureMode(envMode) ? envMode : 'v0';
35
+ }
36
+ exports.resolveCaptureMode = __webpack_exports__.resolveCaptureMode;
37
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
38
+ "resolveCaptureMode"
39
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
40
+ Object.defineProperty(exports, '__esModule', {
41
+ value: true
42
+ });
@@ -0,0 +1,8 @@
1
+ function isCaptureMode(value) {
2
+ return 'v0' === value || 'v1' === value;
3
+ }
4
+ function resolveCaptureMode() {
5
+ const envMode = 'undefined' != typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;
6
+ return isCaptureMode(envMode) ? envMode : 'v0';
7
+ }
8
+ export { resolveCaptureMode };
@@ -0,0 +1,32 @@
1
+ /** A single event the server explicitly rejected (`drop`). */
2
+ export interface V1DroppedEvent {
3
+ uuid: string;
4
+ details?: string;
5
+ }
6
+ export interface CaptureV1ErrorParams {
7
+ requestId: string;
8
+ /** Events the server rejected outright (billing/validation). */
9
+ drops: V1DroppedEvent[];
10
+ /** UUIDs of events still pending `retry` after the attempt budget was exhausted, or lost to a batch-level failure. */
11
+ retryExhausted: string[];
12
+ /** The underlying transport/HTTP/parse failure, when the whole batch failed. */
13
+ cause?: unknown;
14
+ }
15
+ /**
16
+ * Surfaced on the client error channel whenever a Capture V1 batch did not
17
+ * fully deliver: some events were `drop`ped, some `retry` events outlived the
18
+ * attempt budget, or the batch hit a terminal transport/HTTP/parse failure.
19
+ *
20
+ * A 2xx with drops is still a partial failure and is reported here — a
21
+ * successful HTTP status does not mean every event was accepted.
22
+ */
23
+ export declare class CaptureV1Error extends Error {
24
+ name: string;
25
+ readonly requestId: string;
26
+ readonly drops: V1DroppedEvent[];
27
+ readonly retryExhausted: string[];
28
+ cause?: unknown;
29
+ constructor({ requestId, drops, retryExhausted, cause }: CaptureV1ErrorParams);
30
+ private static buildMessage;
31
+ }
32
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/capture-v1/errors.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,oBAAoB;IACnC,SAAS,EAAE,MAAM,CAAA;IACjB,gEAAgE;IAChE,KAAK,EAAE,cAAc,EAAE,CAAA;IACvB,sHAAsH;IACtH,cAAc,EAAE,MAAM,EAAE,CAAA;IACxB,gFAAgF;IAChF,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB;AAED;;;;;;;GAOG;AACH,qBAAa,cAAe,SAAQ,KAAK;IACvC,IAAI,SAAmB;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,KAAK,EAAE,cAAc,EAAE,CAAA;IAChC,QAAQ,CAAC,cAAc,EAAE,MAAM,EAAE,CAAA;IACjC,KAAK,CAAC,EAAE,OAAO,CAAA;gBAEH,EAAE,SAAS,EAAE,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,EAAE,oBAAoB;IAQ7E,OAAO,CAAC,MAAM,CAAC,YAAY;CAY5B"}
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ CaptureV1Error: ()=>CaptureV1Error
28
+ });
29
+ class CaptureV1Error extends Error {
30
+ constructor({ requestId, drops, retryExhausted, cause }){
31
+ super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = 'CaptureV1Error';
32
+ this.requestId = requestId;
33
+ this.drops = drops;
34
+ this.retryExhausted = retryExhausted;
35
+ this.cause = cause;
36
+ }
37
+ static buildMessage(requestId, drops, retryExhausted, cause) {
38
+ let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;
39
+ if (cause instanceof Error) message += ` (${cause.message})`;
40
+ return message;
41
+ }
42
+ }
43
+ exports.CaptureV1Error = __webpack_exports__.CaptureV1Error;
44
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
45
+ "CaptureV1Error"
46
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
47
+ Object.defineProperty(exports, '__esModule', {
48
+ value: true
49
+ });
@@ -0,0 +1,15 @@
1
+ class CaptureV1Error extends Error {
2
+ constructor({ requestId, drops, retryExhausted, cause }){
3
+ super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = 'CaptureV1Error';
4
+ this.requestId = requestId;
5
+ this.drops = drops;
6
+ this.retryExhausted = retryExhausted;
7
+ this.cause = cause;
8
+ }
9
+ static buildMessage(requestId, drops, retryExhausted, cause) {
10
+ let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;
11
+ if (cause instanceof Error) message += ` (${cause.message})`;
12
+ return message;
13
+ }
14
+ }
15
+ export { CaptureV1Error };
@@ -0,0 +1,21 @@
1
+ import type { PostHogEventProperties } from '@posthog/core';
2
+ /**
3
+ * Queue route for events eligible for Capture V1 (everything except `$ai_*`). Its queue is the
4
+ * historical {@link PostHogPersistedProperty.Queue}, so v0 mode is byte-identical to before.
5
+ */
6
+ export declare const ANALYTICS_ROUTE = "analytics";
7
+ /**
8
+ * Queue route for `$ai_*` events, kept on the legacy (v0) transport in v1 mode and isolated on
9
+ * its own queue so a v0 failure can't re-send events already accepted on the V1 route. This route
10
+ * will later host a dedicated v1 AI-events transport once that endpoint exists — segregating it
11
+ * now means no re-plumbing then.
12
+ */
13
+ export declare const AI_ROUTE = "ai";
14
+ /**
15
+ * True for events that must keep using the legacy (v0) submitter even when the
16
+ * client is in v1 mode. Today that is only `$ai_*` events: the dedicated AI
17
+ * ingestion path has no v1 form, so they stay on v0 until AI v1 is designed.
18
+ * The check runs on the post-`before_send` event name.
19
+ */
20
+ export declare function isLegacyOnlyEvent(message: PostHogEventProperties): boolean;
21
+ //# sourceMappingURL=routing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing.d.ts","sourceRoot":"","sources":["../../src/capture-v1/routing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAA;AAK3D;;;GAGG;AACH,eAAO,MAAM,eAAe,cAAc,CAAA;AAE1C;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,OAAO,CAAA;AAE5B;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAE1E"}
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ AI_ROUTE: ()=>AI_ROUTE,
28
+ ANALYTICS_ROUTE: ()=>ANALYTICS_ROUTE,
29
+ isLegacyOnlyEvent: ()=>isLegacyOnlyEvent
30
+ });
31
+ const AI_EVENT_PREFIX = '$ai_';
32
+ const ANALYTICS_ROUTE = 'analytics';
33
+ const AI_ROUTE = 'ai';
34
+ function isLegacyOnlyEvent(message) {
35
+ return 'string' == typeof message.event && message.event.startsWith(AI_EVENT_PREFIX);
36
+ }
37
+ exports.AI_ROUTE = __webpack_exports__.AI_ROUTE;
38
+ exports.ANALYTICS_ROUTE = __webpack_exports__.ANALYTICS_ROUTE;
39
+ exports.isLegacyOnlyEvent = __webpack_exports__.isLegacyOnlyEvent;
40
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
41
+ "AI_ROUTE",
42
+ "ANALYTICS_ROUTE",
43
+ "isLegacyOnlyEvent"
44
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
45
+ Object.defineProperty(exports, '__esModule', {
46
+ value: true
47
+ });
@@ -0,0 +1,7 @@
1
+ const AI_EVENT_PREFIX = '$ai_';
2
+ const ANALYTICS_ROUTE = 'analytics';
3
+ const AI_ROUTE = 'ai';
4
+ function isLegacyOnlyEvent(message) {
5
+ return 'string' == typeof message.event && message.event.startsWith(AI_EVENT_PREFIX);
6
+ }
7
+ export { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent };
@@ -0,0 +1,70 @@
1
+ import { type FetchLike, type PostHogEventProperties } from '@posthog/core';
2
+ export interface V1CaptureSenderConfig {
3
+ host: string;
4
+ apiKey: string;
5
+ /** Canonical `$lib` identity, materialized by the server from `PostHog-Sdk-Info`. */
6
+ libraryId: string;
7
+ libraryVersion: string;
8
+ /** Value for the `User-Agent` header, if the runtime allows setting it. */
9
+ userAgent?: string;
10
+ historicalMigration: boolean;
11
+ /** When true, the body is gzip-compressed (falling back to uncompressed on failure). */
12
+ compressionEnabled: boolean;
13
+ requestTimeoutMs: number;
14
+ /** Total attempts, including the first (1 initial + N retries). */
15
+ maxAttempts: number;
16
+ /** Base exponential backoff, doubled each retry and capped at `maxBackoffMs`. */
17
+ initialRetryDelayMs: number;
18
+ /** Single ceiling for both the backoff schedule and the `Retry-After` clamp. */
19
+ maxBackoffMs?: number;
20
+ isDebug?: boolean;
21
+ }
22
+ export interface V1CaptureSenderHooks {
23
+ fetch: FetchLike;
24
+ /** Surfaces partial/terminal delivery failures on the client error channel. */
25
+ onError: (error: Error) => void;
26
+ now?: () => number;
27
+ sleep?: (ms: number) => Promise<void>;
28
+ generateRequestId?: () => string;
29
+ compress?: (payload: string, isDebug?: boolean) => Promise<Blob | null>;
30
+ }
31
+ /**
32
+ * Sends already-normalized events to the Capture V1 endpoint
33
+ * (`POST /i/v1/analytics/events`), owning the full attempt loop: per-event
34
+ * partial retry, exponential backoff clamped against `Retry-After`, v1 status
35
+ * classification, and surfacing drops / undelivered events on the error
36
+ * channel. Used by both the batched and immediate send paths.
37
+ *
38
+ * Never throws for a handled outcome: after exhausting its own attempt budget it
39
+ * reports the failure via `onError` and resolves, so the caller's queue treats
40
+ * the batch as consumed (the internal budget replaces v0's queue-level retry).
41
+ */
42
+ export declare class V1CaptureSender {
43
+ private readonly config;
44
+ private readonly maxBackoffMs;
45
+ private readonly fetchFn;
46
+ private readonly onError;
47
+ private readonly now;
48
+ private readonly sleep;
49
+ private readonly generateRequestId;
50
+ private readonly compress;
51
+ constructor(config: V1CaptureSenderConfig, hooks: V1CaptureSenderHooks);
52
+ sendV1Batch(messages: PostHogEventProperties[]): Promise<void>;
53
+ private sendOnce;
54
+ private buildHeaders;
55
+ /**
56
+ * Partition the pending events against a 2xx result map: `drop` accumulates as
57
+ * a terminal failure, `retry` is returned for the next attempt, and
58
+ * `ok`/`warning`/unknown/absent are terminal successes.
59
+ */
60
+ private classify;
61
+ private backoffDelay;
62
+ /** Parse `Retry-After` (delta-seconds or HTTP-date). Non-positive/past values are ignored. */
63
+ private parseRetryAfter;
64
+ private parseResponse;
65
+ private buildHttpError;
66
+ private surfaceBatchFailure;
67
+ private surfacePartialDrops;
68
+ private cancelBody;
69
+ }
70
+ //# sourceMappingURL=sender.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sender.d.ts","sourceRoot":"","sources":["../../src/capture-v1/sender.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,SAAS,EACd,KAAK,sBAAsB,EAO5B,MAAM,eAAe,CAAA;AAYtB,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,MAAM,CAAA;IACd,qFAAqF;IACrF,SAAS,EAAE,MAAM,CAAA;IACjB,cAAc,EAAE,MAAM,CAAA;IACtB,2EAA2E;IAC3E,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,mBAAmB,EAAE,OAAO,CAAA;IAC5B,wFAAwF;IACxF,kBAAkB,EAAE,OAAO,CAAA;IAC3B,gBAAgB,EAAE,MAAM,CAAA;IACxB,mEAAmE;IACnE,WAAW,EAAE,MAAM,CAAA;IACnB,iFAAiF;IACjF,mBAAmB,EAAE,MAAM,CAAA;IAC3B,gFAAgF;IAChF,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB;AAED,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,SAAS,CAAA;IAChB,+EAA+E;IAC/E,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;IAC/B,GAAG,CAAC,EAAE,MAAM,MAAM,CAAA;IAClB,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACrC,iBAAiB,CAAC,EAAE,MAAM,MAAM,CAAA;IAChC,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAAA;CACxE;AAED;;;;;;;;;;GAUG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuB;IAC9C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAQ;IACrC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAW;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwB;IAChD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAc;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA+B;IACrD,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAc;IAChD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA8D;gBAE3E,MAAM,EAAE,qBAAqB,EAAE,KAAK,EAAE,oBAAoB;IAWhE,WAAW,CAAC,QAAQ,EAAE,sBAAsB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;YAkFtD,QAAQ;IA0BtB,OAAO,CAAC,YAAY;IAiBpB;;;;OAIG;IACH,OAAO,CAAC,QAAQ;IAkBhB,OAAO,CAAC,YAAY;IASpB,8FAA8F;IAC9F,OAAO,CAAC,eAAe;YAkBT,aAAa;YAab,cAAc;IAW5B,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,mBAAmB;YAMb,UAAU;CAGzB"}
@@ -0,0 +1,222 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ V1CaptureSender: ()=>V1CaptureSender
28
+ });
29
+ const core_namespaceObject = require("@posthog/core");
30
+ const external_errors_js_namespaceObject = require("./errors.js");
31
+ const external_transform_js_namespaceObject = require("./transform.js");
32
+ const V1_ANALYTICS_PATH = '/i/v1/analytics/events';
33
+ const DEFAULT_MAX_BACKOFF_MS = 30000;
34
+ const RETRYABLE_STATUSES = new Set([
35
+ 408,
36
+ 500,
37
+ 502,
38
+ 503,
39
+ 504
40
+ ]);
41
+ class V1CaptureSender {
42
+ constructor(config, hooks){
43
+ this.config = config;
44
+ this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
45
+ this.fetchFn = hooks.fetch;
46
+ this.onError = hooks.onError;
47
+ this.now = hooks.now ?? Date.now;
48
+ this.sleep = hooks.sleep ?? ((ms)=>new Promise((resolve)=>(0, core_namespaceObject.safeSetTimeout)(resolve, ms)));
49
+ this.generateRequestId = hooks.generateRequestId ?? core_namespaceObject.uuidv7;
50
+ this.compress = hooks.compress ?? core_namespaceObject.gzipCompress;
51
+ }
52
+ async sendV1Batch(messages) {
53
+ if (0 === messages.length) return;
54
+ const requestId = this.generateRequestId();
55
+ const createdAt = new Date(this.now()).toISOString();
56
+ const { batch } = (0, external_transform_js_namespaceObject.buildV1Batch)(messages, {
57
+ createdAt,
58
+ historicalMigration: this.config.historicalMigration
59
+ });
60
+ const url = `${this.config.host}${V1_ANALYTICS_PATH}`;
61
+ const drops = [];
62
+ let pending = batch;
63
+ const maxAttempts = Math.max(1, this.config.maxAttempts);
64
+ for(let attempt = 1; attempt <= maxAttempts; attempt++){
65
+ const isLastAttempt = attempt === maxAttempts;
66
+ const payload = (0, core_namespaceObject.safeJsonStringify)({
67
+ created_at: createdAt,
68
+ ...this.config.historicalMigration ? {
69
+ historical_migration: true
70
+ } : {},
71
+ batch: pending
72
+ });
73
+ let response;
74
+ try {
75
+ response = await this.sendOnce(url, payload, attempt, requestId);
76
+ } catch (transportError) {
77
+ if (isLastAttempt) return this.surfaceBatchFailure(requestId, drops, pending, transportError);
78
+ await this.sleep(this.backoffDelay(attempt));
79
+ continue;
80
+ }
81
+ const { status } = response;
82
+ if (status < 200 || status >= 300) {
83
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
84
+ const retryAfterMs = this.parseRetryAfter(response);
85
+ await this.cancelBody(response);
86
+ await this.sleep(this.backoffDelay(attempt, retryAfterMs));
87
+ continue;
88
+ }
89
+ const httpError = await this.buildHttpError(response, status);
90
+ return this.surfaceBatchFailure(requestId, drops, pending, httpError);
91
+ }
92
+ let parsed;
93
+ try {
94
+ parsed = await this.parseResponse(response);
95
+ } catch {
96
+ return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));
97
+ }
98
+ const retryable = this.classify(pending, parsed, drops);
99
+ if (0 === retryable.length) return this.surfacePartialDrops(requestId, drops);
100
+ if (isLastAttempt) return void this.onError(new external_errors_js_namespaceObject.CaptureV1Error({
101
+ requestId,
102
+ drops,
103
+ retryExhausted: retryable.map((event)=>event.uuid)
104
+ }));
105
+ pending = retryable;
106
+ const retryAfterMs = this.parseRetryAfter(response);
107
+ await this.sleep(this.backoffDelay(attempt, retryAfterMs));
108
+ }
109
+ }
110
+ async sendOnce(url, payload, attempt, requestId) {
111
+ const headers = this.buildHeaders(attempt, requestId);
112
+ let body = payload;
113
+ if (this.config.compressionEnabled) {
114
+ const compressed = await this.compress(payload, this.config.isDebug);
115
+ if (null !== compressed) {
116
+ body = compressed;
117
+ headers['Content-Encoding'] = 'gzip';
118
+ }
119
+ }
120
+ const controller = new AbortController();
121
+ const timer = (0, core_namespaceObject.safeSetTimeout)(()=>controller.abort(), this.config.requestTimeoutMs);
122
+ try {
123
+ return await this.fetchFn(url, {
124
+ method: 'POST',
125
+ headers,
126
+ body,
127
+ signal: controller.signal
128
+ });
129
+ } finally{
130
+ clearTimeout(timer);
131
+ }
132
+ }
133
+ buildHeaders(attempt, requestId) {
134
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
135
+ const headers = {
136
+ 'Content-Type': 'application/json',
137
+ Authorization: `Bearer ${this.config.apiKey}`,
138
+ 'PostHog-Sdk-Info': sdkInfo,
139
+ 'PostHog-Attempt': String(attempt),
140
+ 'PostHog-Request-Id': requestId,
141
+ 'PostHog-Request-Timestamp': new Date(this.now()).toISOString()
142
+ };
143
+ if (this.config.userAgent) headers['User-Agent'] = this.config.userAgent;
144
+ return headers;
145
+ }
146
+ classify(pending, parsed, drops) {
147
+ const results = parsed.results ?? {};
148
+ const retryable = [];
149
+ for (const event of pending){
150
+ const result = results[event.uuid];
151
+ if (result) {
152
+ if ('drop' === result.result) drops.push({
153
+ uuid: event.uuid,
154
+ details: result.details ?? void 0
155
+ });
156
+ else if ('retry' === result.result) retryable.push(event);
157
+ }
158
+ }
159
+ return retryable;
160
+ }
161
+ backoffDelay(attempt, retryAfterMs) {
162
+ const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);
163
+ if (void 0 === retryAfterMs) return exponential;
164
+ return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));
165
+ }
166
+ parseRetryAfter(response) {
167
+ const raw = response.headers?.get('Retry-After');
168
+ if (!raw) return;
169
+ const trimmed = raw.trim();
170
+ if (/^\d+$/.test(trimmed)) {
171
+ const seconds = parseInt(trimmed, 10);
172
+ return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : void 0;
173
+ }
174
+ const dateMs = Date.parse(trimmed);
175
+ if (Number.isNaN(dateMs)) return;
176
+ const delta = dateMs - this.now();
177
+ return delta > 0 ? delta : void 0;
178
+ }
179
+ async parseResponse(response) {
180
+ const text = await response.text();
181
+ const parsed = JSON.parse(text);
182
+ if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');
183
+ const results = parsed.results;
184
+ if (void 0 !== results && ('object' != typeof results || null === results || Array.isArray(results))) throw new Error('unexpected results shape');
185
+ return {
186
+ results: results ?? {}
187
+ };
188
+ }
189
+ async buildHttpError(response, status) {
190
+ let bodyText = '';
191
+ try {
192
+ bodyText = (await response.text()).slice(0, 512);
193
+ } catch {}
194
+ const suffix = bodyText ? `: ${bodyText}` : '';
195
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
196
+ }
197
+ surfaceBatchFailure(requestId, drops, pending, cause) {
198
+ this.onError(new external_errors_js_namespaceObject.CaptureV1Error({
199
+ requestId,
200
+ drops,
201
+ retryExhausted: pending.map((event)=>event.uuid),
202
+ cause
203
+ }));
204
+ }
205
+ surfacePartialDrops(requestId, drops) {
206
+ if (drops.length > 0) this.onError(new external_errors_js_namespaceObject.CaptureV1Error({
207
+ requestId,
208
+ drops,
209
+ retryExhausted: []
210
+ }));
211
+ }
212
+ async cancelBody(response) {
213
+ await response.body?.cancel()?.catch(()=>{});
214
+ }
215
+ }
216
+ exports.V1CaptureSender = __webpack_exports__.V1CaptureSender;
217
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
218
+ "V1CaptureSender"
219
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
220
+ Object.defineProperty(exports, '__esModule', {
221
+ value: true
222
+ });