@baukit/analytics-posthog-web 0.7.1 → 0.7.3
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.
- package/package.json +3 -2
- package/src/index.test.ts +260 -0
- package/src/index.ts +302 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baukit/analytics-posthog-web",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "PostHog browser transport for @baukit/analytics-core.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Patrick Koss",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
},
|
|
31
31
|
"files": [
|
|
32
32
|
"dist",
|
|
33
|
+
"src",
|
|
33
34
|
"README.md",
|
|
34
35
|
"LICENSE"
|
|
35
36
|
],
|
|
@@ -46,7 +47,7 @@
|
|
|
46
47
|
"typescript": "6.0.3"
|
|
47
48
|
},
|
|
48
49
|
"peerDependencies": {
|
|
49
|
-
"@baukit/analytics-core": "^0.7.
|
|
50
|
+
"@baukit/analytics-core": "^0.7.3",
|
|
50
51
|
"posthog-js": ">=1.43.1 <2"
|
|
51
52
|
}
|
|
52
53
|
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { AnalyticsClient } from '@baukit/analytics-core';
|
|
2
|
+
import type { AnalyticsContext, AnalyticsEnvelope, EventAllowlist } from '@baukit/analytics-core';
|
|
3
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
4
|
+
|
|
5
|
+
import { createPostHogWebTransport, PostHogWebTransport, type PostHogWebClient } from './index.js';
|
|
6
|
+
|
|
7
|
+
interface ProductEvent {
|
|
8
|
+
name: 'onboarding_started';
|
|
9
|
+
properties: { source: 'organic' | 'invite'; contact?: string };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const ANONYMOUS_ID = '00000000-0000-4000-8000-000000000001';
|
|
13
|
+
const USER_ID = '10000000-0000-4000-8000-000000000001';
|
|
14
|
+
const CAPTURED_AT = '2026-08-08T10:00:00.000Z';
|
|
15
|
+
|
|
16
|
+
const context: AnalyticsContext = {
|
|
17
|
+
schema_version: 1,
|
|
18
|
+
app: 'example-web',
|
|
19
|
+
app_version: '1.0.0',
|
|
20
|
+
platform: 'web',
|
|
21
|
+
environment: 'test',
|
|
22
|
+
locale: 'en-GB',
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
interface MockClient {
|
|
26
|
+
readonly client: PostHogWebClient;
|
|
27
|
+
readonly capture: ReturnType<typeof vi.fn>;
|
|
28
|
+
readonly identify: ReturnType<typeof vi.fn>;
|
|
29
|
+
readonly alias: ReturnType<typeof vi.fn>;
|
|
30
|
+
readonly reset: ReturnType<typeof vi.fn>;
|
|
31
|
+
readonly optIn: ReturnType<typeof vi.fn>;
|
|
32
|
+
readonly optOut: ReturnType<typeof vi.fn>;
|
|
33
|
+
readonly queue: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function createMockClient(): MockClient {
|
|
37
|
+
const capture = vi.fn();
|
|
38
|
+
const identify = vi.fn();
|
|
39
|
+
const alias = vi.fn();
|
|
40
|
+
const reset = vi.fn();
|
|
41
|
+
const optIn = vi.fn();
|
|
42
|
+
const optOut = vi.fn();
|
|
43
|
+
const queue: string[] = [];
|
|
44
|
+
let optedOut = true;
|
|
45
|
+
const client = {
|
|
46
|
+
capture(event: string, properties?: Readonly<Record<string, unknown>>, options?: object) {
|
|
47
|
+
capture(event, properties, options);
|
|
48
|
+
if (!optedOut) {
|
|
49
|
+
queue.push(event);
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
identify,
|
|
53
|
+
alias,
|
|
54
|
+
reset,
|
|
55
|
+
opt_in_capturing(options?: { readonly captureEventName?: string | null | false }) {
|
|
56
|
+
optIn(options);
|
|
57
|
+
optedOut = false;
|
|
58
|
+
},
|
|
59
|
+
opt_out_capturing() {
|
|
60
|
+
optOut();
|
|
61
|
+
optedOut = true;
|
|
62
|
+
},
|
|
63
|
+
_requestQueue: { _queue: queue },
|
|
64
|
+
} satisfies PostHogWebClient & { _requestQueue: { _queue: string[] } };
|
|
65
|
+
return { client, capture, identify, alias, reset, optIn, optOut, queue };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function lifecycleEnvelopes(): readonly AnalyticsEnvelope<ProductEvent>[] {
|
|
69
|
+
return [
|
|
70
|
+
{
|
|
71
|
+
type: 'capture',
|
|
72
|
+
captured_at: CAPTURED_AT,
|
|
73
|
+
anonymous_id: ANONYMOUS_ID,
|
|
74
|
+
event: {
|
|
75
|
+
...context,
|
|
76
|
+
name: 'onboarding_started',
|
|
77
|
+
properties: { source: 'organic', contact: '[redacted]' },
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
type: 'identify',
|
|
82
|
+
captured_at: CAPTURED_AT,
|
|
83
|
+
anonymous_id: ANONYMOUS_ID,
|
|
84
|
+
user_id: USER_ID,
|
|
85
|
+
traits: { plan: 'free', email: '[redacted]' },
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
type: 'alias',
|
|
89
|
+
captured_at: CAPTURED_AT,
|
|
90
|
+
anonymous_id: ANONYMOUS_ID,
|
|
91
|
+
user_id: USER_ID,
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
type: 'reset',
|
|
95
|
+
captured_at: CAPTURED_AT,
|
|
96
|
+
previous_anonymous_id: ANONYMOUS_ID,
|
|
97
|
+
previous_user_id: USER_ID,
|
|
98
|
+
},
|
|
99
|
+
];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
describe('PostHogWebTransport mapping', () => {
|
|
103
|
+
it('maps capture, identify, alias, and reset without adding properties', async () => {
|
|
104
|
+
const posthog = createMockClient();
|
|
105
|
+
const transport = new PostHogWebTransport<ProductEvent>(posthog.client);
|
|
106
|
+
|
|
107
|
+
await transport.send(lifecycleEnvelopes());
|
|
108
|
+
|
|
109
|
+
expect(posthog.capture).toHaveBeenCalledWith(
|
|
110
|
+
'onboarding_started',
|
|
111
|
+
{
|
|
112
|
+
source: 'organic',
|
|
113
|
+
contact: '[redacted]',
|
|
114
|
+
...context,
|
|
115
|
+
},
|
|
116
|
+
{ timestamp: new Date(CAPTURED_AT) },
|
|
117
|
+
);
|
|
118
|
+
expect(posthog.identify).toHaveBeenCalledWith(USER_ID, {
|
|
119
|
+
plan: 'free',
|
|
120
|
+
email: '[redacted]',
|
|
121
|
+
});
|
|
122
|
+
expect(posthog.alias).toHaveBeenCalledWith(USER_ID, ANONYMOUS_ID);
|
|
123
|
+
expect(posthog.reset).toHaveBeenCalledWith();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('contains client and diagnostic failures', async () => {
|
|
127
|
+
const posthog = createMockClient();
|
|
128
|
+
posthog.capture.mockImplementation(() => {
|
|
129
|
+
throw new Error('provider failed');
|
|
130
|
+
});
|
|
131
|
+
const transport = new PostHogWebTransport<ProductEvent>(posthog.client, () => {
|
|
132
|
+
throw new Error('diagnostic failed');
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
await expect(transport.send(lifecycleEnvelopes())).resolves.toBeUndefined();
|
|
136
|
+
expect(posthog.identify).toHaveBeenCalledOnce();
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
describe('createPostHogWebTransport', () => {
|
|
141
|
+
it('requires a self-hosted API host and API key', () => {
|
|
142
|
+
expect(() => createPostHogWebTransport({ apiKey: 'phc_key', apiHost: '' })).toThrow(
|
|
143
|
+
'apiHost must not be empty',
|
|
144
|
+
);
|
|
145
|
+
expect(() =>
|
|
146
|
+
createPostHogWebTransport({ apiKey: 'phc_key', apiHost: 'posthog.internal' }),
|
|
147
|
+
).toThrow('apiHost must be an absolute http(s) URL');
|
|
148
|
+
expect(() =>
|
|
149
|
+
createPostHogWebTransport({ apiKey: '', apiHost: 'https://posthog.example.test' }),
|
|
150
|
+
).toThrow('apiKey must not be empty');
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('initializes lazily with typed-only privacy defaults and the core anonymous ID', async () => {
|
|
154
|
+
const posthog = createMockClient();
|
|
155
|
+
const initializer = vi.fn(() => posthog.client);
|
|
156
|
+
const transport = createPostHogWebTransport<ProductEvent>({
|
|
157
|
+
apiKey: ' phc_key ',
|
|
158
|
+
apiHost: 'https://posthog.example.test/',
|
|
159
|
+
initializer,
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
expect(initializer).not.toHaveBeenCalled();
|
|
163
|
+
await transport.send(lifecycleEnvelopes().slice(0, 1));
|
|
164
|
+
|
|
165
|
+
expect(initializer).toHaveBeenCalledWith(
|
|
166
|
+
'phc_key',
|
|
167
|
+
expect.objectContaining({
|
|
168
|
+
api_host: 'https://posthog.example.test',
|
|
169
|
+
autocapture: false,
|
|
170
|
+
capture_pageview: false,
|
|
171
|
+
capture_pageleave: false,
|
|
172
|
+
capture_exceptions: false,
|
|
173
|
+
disable_session_recording: true,
|
|
174
|
+
disable_surveys: true,
|
|
175
|
+
advanced_disable_feature_flags_on_first_load: true,
|
|
176
|
+
opt_out_capturing_by_default: true,
|
|
177
|
+
opt_out_persistence_by_default: true,
|
|
178
|
+
person_profiles: 'identified_only',
|
|
179
|
+
save_campaign_params: false,
|
|
180
|
+
save_referrer: false,
|
|
181
|
+
bootstrap: { distinctID: ANONYMOUS_ID, isIdentifiedID: false },
|
|
182
|
+
}),
|
|
183
|
+
);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
describe('web adapter composed with analytics core', () => {
|
|
188
|
+
it('opts out and clears the provider request queue when consent is withdrawn', async () => {
|
|
189
|
+
const posthog = createMockClient();
|
|
190
|
+
const transport = new PostHogWebTransport<ProductEvent>(posthog.client);
|
|
191
|
+
const clearPending = vi.spyOn(transport, 'clearPending');
|
|
192
|
+
const analytics = new AnalyticsClient<ProductEvent>({
|
|
193
|
+
context,
|
|
194
|
+
allowlist: { onboarding_started: ['source'] },
|
|
195
|
+
transport,
|
|
196
|
+
uuidFactory: () => ANONYMOUS_ID,
|
|
197
|
+
flushBatchSize: 100,
|
|
198
|
+
flushIntervalMs: 60_000,
|
|
199
|
+
development: false,
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
analytics.setConsent('granted');
|
|
203
|
+
analytics.capture({ name: 'onboarding_started', properties: { source: 'organic' } });
|
|
204
|
+
await analytics.flush();
|
|
205
|
+
expect(posthog.queue).toEqual(['onboarding_started']);
|
|
206
|
+
|
|
207
|
+
analytics.setConsent('denied');
|
|
208
|
+
await vi.waitFor(() => {
|
|
209
|
+
expect(posthog.queue).toEqual([]);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
expect(clearPending).toHaveBeenCalledOnce();
|
|
213
|
+
expect(posthog.optOut).toHaveBeenCalledOnce();
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('drops before consent and transports only allowlisted, scrubbed properties after opt-in', async () => {
|
|
217
|
+
const posthog = createMockClient();
|
|
218
|
+
const allowlist = {
|
|
219
|
+
onboarding_started: ['source', 'contact'],
|
|
220
|
+
} as const satisfies EventAllowlist<ProductEvent>;
|
|
221
|
+
const analytics = new AnalyticsClient<ProductEvent>({
|
|
222
|
+
context,
|
|
223
|
+
allowlist,
|
|
224
|
+
transport: new PostHogWebTransport(posthog.client),
|
|
225
|
+
uuidFactory: () => ANONYMOUS_ID,
|
|
226
|
+
flushBatchSize: 100,
|
|
227
|
+
flushIntervalMs: 60_000,
|
|
228
|
+
development: false,
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
analytics.capture({ name: 'onboarding_started', properties: { source: 'organic' } });
|
|
232
|
+
await analytics.flush();
|
|
233
|
+
analytics.setConsent('denied');
|
|
234
|
+
analytics.capture({ name: 'onboarding_started', properties: { source: 'invite' } });
|
|
235
|
+
await analytics.flush();
|
|
236
|
+
expect(posthog.capture).not.toHaveBeenCalled();
|
|
237
|
+
|
|
238
|
+
analytics.setConsent('granted');
|
|
239
|
+
analytics.capture({
|
|
240
|
+
name: 'onboarding_started',
|
|
241
|
+
properties: {
|
|
242
|
+
source: 'organic',
|
|
243
|
+
contact: 'person@example.com',
|
|
244
|
+
unlisted: 'must not arrive',
|
|
245
|
+
},
|
|
246
|
+
} as ProductEvent);
|
|
247
|
+
await analytics.flush();
|
|
248
|
+
|
|
249
|
+
expect(posthog.capture).toHaveBeenCalledOnce();
|
|
250
|
+
expect(posthog.capture).toHaveBeenCalledWith(
|
|
251
|
+
'onboarding_started',
|
|
252
|
+
{
|
|
253
|
+
source: 'organic',
|
|
254
|
+
contact: '[redacted]',
|
|
255
|
+
...context,
|
|
256
|
+
},
|
|
257
|
+
expect.any(Object),
|
|
258
|
+
);
|
|
259
|
+
});
|
|
260
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { posthog, type PostHogConfig } from 'posthog-js';
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
AnalyticsEnvelope,
|
|
5
|
+
AnalyticsEvent,
|
|
6
|
+
CaptureEnvelope,
|
|
7
|
+
Transport,
|
|
8
|
+
} from '@baukit/analytics-core';
|
|
9
|
+
|
|
10
|
+
export interface PostHogWebClient {
|
|
11
|
+
capture(
|
|
12
|
+
event: string,
|
|
13
|
+
properties?: Readonly<Record<string, unknown>>,
|
|
14
|
+
options?: { readonly timestamp?: Date },
|
|
15
|
+
): unknown;
|
|
16
|
+
identify(distinctId: string, traits?: Readonly<Record<string, unknown>>): unknown;
|
|
17
|
+
alias(alias: string, original?: string): unknown;
|
|
18
|
+
reset(): unknown;
|
|
19
|
+
opt_in_capturing(options?: { readonly captureEventName?: string | null | false }): unknown;
|
|
20
|
+
opt_out_capturing(): unknown;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type GuardedPostHogWebOption =
|
|
24
|
+
| 'advanced_disable_feature_flags_on_first_load'
|
|
25
|
+
| 'api_host'
|
|
26
|
+
| 'autocapture'
|
|
27
|
+
| 'bootstrap'
|
|
28
|
+
| 'capture_exceptions'
|
|
29
|
+
| 'capture_pageleave'
|
|
30
|
+
| 'capture_pageview'
|
|
31
|
+
| 'disable_session_recording'
|
|
32
|
+
| 'disable_surveys'
|
|
33
|
+
| 'opt_out_capturing_by_default'
|
|
34
|
+
| 'opt_out_persistence_by_default'
|
|
35
|
+
| 'person_profiles'
|
|
36
|
+
| 'save_campaign_params'
|
|
37
|
+
| 'save_referrer';
|
|
38
|
+
|
|
39
|
+
export type PostHogWebInitOptions = Omit<Partial<PostHogConfig>, GuardedPostHogWebOption>;
|
|
40
|
+
|
|
41
|
+
export type PostHogWebInitializer = (
|
|
42
|
+
apiKey: string,
|
|
43
|
+
options: Partial<PostHogConfig>,
|
|
44
|
+
) => PostHogWebClient | Promise<PostHogWebClient>;
|
|
45
|
+
|
|
46
|
+
export interface PostHogWebTransportConfig {
|
|
47
|
+
readonly apiKey: string;
|
|
48
|
+
/** Absolute URL of the product's self-hosted PostHog instance. */
|
|
49
|
+
readonly apiHost: string;
|
|
50
|
+
readonly options?: PostHogWebInitOptions;
|
|
51
|
+
readonly initializer?: PostHogWebInitializer;
|
|
52
|
+
readonly onError?: (error: unknown) => void;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
type ClientFactory = (
|
|
56
|
+
firstEnvelope: AnalyticsEnvelope,
|
|
57
|
+
) => PostHogWebClient | Promise<PostHogWebClient>;
|
|
58
|
+
|
|
59
|
+
interface PendingQueueInternals {
|
|
60
|
+
_queue?: unknown[];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface PostHogWebInternals {
|
|
64
|
+
__request_queue?: unknown[];
|
|
65
|
+
_requestQueue?: PendingQueueInternals;
|
|
66
|
+
_retryQueue?: PendingQueueInternals;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function clearArray(value: unknown[] | undefined): void {
|
|
70
|
+
if (value !== undefined) {
|
|
71
|
+
value.length = 0;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function requireNonEmpty(name: string, value: string): string {
|
|
76
|
+
const normalized = value.trim();
|
|
77
|
+
if (normalized.length === 0) {
|
|
78
|
+
throw new TypeError(`${name} must not be empty`);
|
|
79
|
+
}
|
|
80
|
+
return normalized;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function requireApiHost(value: string): string {
|
|
84
|
+
const apiHost = requireNonEmpty('apiHost', value).replace(/\/+$/, '');
|
|
85
|
+
if (!/^https?:\/\/[^\s/]+(?:\/.*)?$/u.test(apiHost)) {
|
|
86
|
+
throw new TypeError('apiHost must be an absolute http(s) URL');
|
|
87
|
+
}
|
|
88
|
+
return apiHost;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function initialIdentity(envelope: AnalyticsEnvelope): {
|
|
92
|
+
readonly distinctID: string;
|
|
93
|
+
readonly isIdentifiedID: boolean;
|
|
94
|
+
} {
|
|
95
|
+
if (envelope.type === 'capture') {
|
|
96
|
+
return envelope.user_id === undefined
|
|
97
|
+
? { distinctID: envelope.anonymous_id, isIdentifiedID: false }
|
|
98
|
+
: { distinctID: envelope.user_id, isIdentifiedID: true };
|
|
99
|
+
}
|
|
100
|
+
if (envelope.type === 'reset') {
|
|
101
|
+
return envelope.previous_user_id === undefined
|
|
102
|
+
? { distinctID: envelope.previous_anonymous_id, isIdentifiedID: false }
|
|
103
|
+
: { distinctID: envelope.previous_user_id, isIdentifiedID: true };
|
|
104
|
+
}
|
|
105
|
+
return { distinctID: envelope.anonymous_id, isIdentifiedID: false };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function captureProperties<E extends AnalyticsEvent>(
|
|
109
|
+
envelope: CaptureEnvelope<E>,
|
|
110
|
+
): Readonly<Record<string, unknown>> {
|
|
111
|
+
return {
|
|
112
|
+
...envelope.event.properties,
|
|
113
|
+
schema_version: envelope.event.schema_version,
|
|
114
|
+
app: envelope.event.app,
|
|
115
|
+
app_version: envelope.event.app_version,
|
|
116
|
+
platform: envelope.event.platform,
|
|
117
|
+
environment: envelope.event.environment,
|
|
118
|
+
locale: envelope.event.locale,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Translates privacy-checked core envelopes to a PostHog browser client. */
|
|
123
|
+
export class PostHogWebTransport<
|
|
124
|
+
E extends AnalyticsEvent = AnalyticsEvent,
|
|
125
|
+
> implements Transport<E> {
|
|
126
|
+
readonly #clientFactory: ClientFactory;
|
|
127
|
+
readonly #onError: ((error: unknown) => void) | undefined;
|
|
128
|
+
#client: Promise<PostHogWebClient> | undefined;
|
|
129
|
+
#clearGeneration = 0;
|
|
130
|
+
#clearRequired = false;
|
|
131
|
+
#clearOperation: Promise<void> | undefined;
|
|
132
|
+
#providerOptedOut = true;
|
|
133
|
+
|
|
134
|
+
public constructor(client: PostHogWebClient | ClientFactory, onError?: (error: unknown) => void) {
|
|
135
|
+
this.#clientFactory = typeof client === 'function' ? client : () => client;
|
|
136
|
+
this.#onError = onError;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Provider failures are contained and never reject into application code. */
|
|
140
|
+
public async send(envelopes: readonly AnalyticsEnvelope<E>[]): Promise<void> {
|
|
141
|
+
if (envelopes.length === 0) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const generation = this.#clearGeneration;
|
|
146
|
+
let client: PostHogWebClient;
|
|
147
|
+
try {
|
|
148
|
+
client = await this.#getClient(envelopes[0] as AnalyticsEnvelope);
|
|
149
|
+
} catch (error: unknown) {
|
|
150
|
+
this.#reportError(error);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
await this.#clearOperation;
|
|
155
|
+
if (generation !== this.#clearGeneration) {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (this.#clearRequired) {
|
|
159
|
+
this.#purgeClient(client);
|
|
160
|
+
if (generation !== this.#clearGeneration) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
this.#clearRequired = false;
|
|
164
|
+
}
|
|
165
|
+
if (!this.#optIn(client)) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
for (const envelope of envelopes) {
|
|
170
|
+
if (generation !== this.#clearGeneration) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
await this.#dispatch(client, envelope);
|
|
175
|
+
} catch (error: unknown) {
|
|
176
|
+
this.#reportError(error);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Opts PostHog out and purges its in-memory batch and retry queues. */
|
|
182
|
+
public clearPending(): Promise<void> {
|
|
183
|
+
this.#clearGeneration += 1;
|
|
184
|
+
this.#clearRequired = true;
|
|
185
|
+
this.#providerOptedOut = true;
|
|
186
|
+
const client = this.#client;
|
|
187
|
+
if (client === undefined) {
|
|
188
|
+
return Promise.resolve();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const generation = this.#clearGeneration;
|
|
192
|
+
const operation = client
|
|
193
|
+
.then((resolvedClient) => {
|
|
194
|
+
this.#purgeClient(resolvedClient);
|
|
195
|
+
if (generation === this.#clearGeneration) {
|
|
196
|
+
this.#clearRequired = false;
|
|
197
|
+
}
|
|
198
|
+
})
|
|
199
|
+
.catch((error: unknown) => {
|
|
200
|
+
this.#reportError(error);
|
|
201
|
+
})
|
|
202
|
+
.finally(() => {
|
|
203
|
+
if (this.#clearOperation === operation) {
|
|
204
|
+
this.#clearOperation = undefined;
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
this.#clearOperation = operation;
|
|
208
|
+
return operation;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
#getClient(firstEnvelope: AnalyticsEnvelope): Promise<PostHogWebClient> {
|
|
212
|
+
this.#client ??= Promise.resolve(this.#clientFactory(firstEnvelope));
|
|
213
|
+
return this.#client;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async #dispatch(client: PostHogWebClient, envelope: AnalyticsEnvelope<E>): Promise<void> {
|
|
217
|
+
switch (envelope.type) {
|
|
218
|
+
case 'capture':
|
|
219
|
+
await Promise.resolve(
|
|
220
|
+
client.capture(envelope.event.name, captureProperties(envelope), {
|
|
221
|
+
timestamp: new Date(envelope.captured_at),
|
|
222
|
+
}),
|
|
223
|
+
);
|
|
224
|
+
break;
|
|
225
|
+
case 'identify':
|
|
226
|
+
await Promise.resolve(client.identify(envelope.user_id, envelope.traits));
|
|
227
|
+
break;
|
|
228
|
+
case 'alias':
|
|
229
|
+
await Promise.resolve(client.alias(envelope.user_id, envelope.anonymous_id));
|
|
230
|
+
break;
|
|
231
|
+
case 'reset':
|
|
232
|
+
await Promise.resolve(client.reset());
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
#optIn(client: PostHogWebClient): boolean {
|
|
238
|
+
if (!this.#providerOptedOut) {
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
try {
|
|
242
|
+
client.opt_in_capturing({ captureEventName: false });
|
|
243
|
+
this.#providerOptedOut = false;
|
|
244
|
+
return true;
|
|
245
|
+
} catch (error: unknown) {
|
|
246
|
+
this.#reportError(error);
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
#purgeClient(client: PostHogWebClient): void {
|
|
252
|
+
try {
|
|
253
|
+
client.opt_out_capturing();
|
|
254
|
+
} catch (error: unknown) {
|
|
255
|
+
this.#reportError(error);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const internals = client as PostHogWebClient & PostHogWebInternals;
|
|
259
|
+
clearArray(internals.__request_queue);
|
|
260
|
+
clearArray(internals._requestQueue?._queue);
|
|
261
|
+
clearArray(internals._retryQueue?._queue);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
#reportError(error: unknown): void {
|
|
265
|
+
try {
|
|
266
|
+
this.#onError?.(error);
|
|
267
|
+
} catch {
|
|
268
|
+
// Provider diagnostics must not affect the application journey.
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Creates a lazy, safely configured PostHog browser transport. */
|
|
274
|
+
export function createPostHogWebTransport<E extends AnalyticsEvent = AnalyticsEvent>(
|
|
275
|
+
config: PostHogWebTransportConfig,
|
|
276
|
+
): PostHogWebTransport<E> {
|
|
277
|
+
const apiKey = requireNonEmpty('apiKey', config.apiKey);
|
|
278
|
+
const apiHost = requireApiHost(config.apiHost);
|
|
279
|
+
const initializer: PostHogWebInitializer =
|
|
280
|
+
config.initializer ?? ((key, options) => posthog.init(key, options));
|
|
281
|
+
|
|
282
|
+
return new PostHogWebTransport<E>((firstEnvelope) => {
|
|
283
|
+
const options: Partial<PostHogConfig> = {
|
|
284
|
+
...config.options,
|
|
285
|
+
api_host: apiHost,
|
|
286
|
+
autocapture: false,
|
|
287
|
+
capture_pageview: false,
|
|
288
|
+
capture_pageleave: false,
|
|
289
|
+
capture_exceptions: false,
|
|
290
|
+
disable_session_recording: true,
|
|
291
|
+
disable_surveys: true,
|
|
292
|
+
advanced_disable_feature_flags_on_first_load: true,
|
|
293
|
+
opt_out_capturing_by_default: true,
|
|
294
|
+
opt_out_persistence_by_default: true,
|
|
295
|
+
person_profiles: 'identified_only',
|
|
296
|
+
save_campaign_params: false,
|
|
297
|
+
save_referrer: false,
|
|
298
|
+
bootstrap: initialIdentity(firstEnvelope),
|
|
299
|
+
};
|
|
300
|
+
return initializer(apiKey, options);
|
|
301
|
+
}, config.onError);
|
|
302
|
+
}
|