@funnelsgrove/analytics 0.1.93 → 0.1.96

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.
@@ -0,0 +1,4 @@
1
+ export declare const sanitizeAnalyticsUrl: (value: unknown, sensitiveKeys?: RegExp) => string | undefined;
2
+ export declare const analyticsUrlSanitizerSource: string;
3
+ /** Snapshot before filtering so custom toJSON values cannot bypass the export policy. */
4
+ export declare const sanitizeAnalyticsExport: (value: unknown) => unknown;
@@ -0,0 +1,48 @@
1
+ const sensitiveKey = /^(?:authorization|cookie|setcookie|password|passwd|secret|clientsecret|token|accesstoken|refreshtoken|idtoken|apikey|publishablekey|privatekey|email|emailaddress|customeremail|fullname|firstname|lastname|name|phone|phonenumber|ipaddress)$/;
2
+ // Keep this function self-contained: the head bootstrap embeds the same implementation.
3
+ export const sanitizeAnalyticsUrl = (value, sensitiveKeys = sensitiveKey) => {
4
+ var _a;
5
+ if (typeof value !== 'string' || !value.trim())
6
+ return undefined;
7
+ const input = value.trim();
8
+ // Accept absolute HTTP(S) URLs and explicit relative paths, not arbitrary free text.
9
+ if (!/^(https?:\/\/|\/|\.\.?\/)/i.test(input))
10
+ return undefined;
11
+ try {
12
+ const url = new URL(input, typeof window !== 'undefined' ? (_a = window.location) === null || _a === void 0 ? void 0 : _a.origin : undefined);
13
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
14
+ return undefined;
15
+ url.username = '';
16
+ url.password = '';
17
+ url.hash = '';
18
+ for (const key of Array.from(url.searchParams.keys())) {
19
+ if (sensitiveKeys.test(key.toLowerCase().replace(/[^a-z0-9]/g, '')))
20
+ url.searchParams.delete(key);
21
+ }
22
+ return url.href;
23
+ }
24
+ catch (_b) {
25
+ return undefined;
26
+ }
27
+ };
28
+ export const analyticsUrlSanitizerSource = `function(value) { return (${sanitizeAnalyticsUrl.toString()})(value, ${sensitiveKey.toString()}); }`;
29
+ /** Snapshot before filtering so custom toJSON values cannot bypass the export policy. */
30
+ export const sanitizeAnalyticsExport = (value) => {
31
+ const json = JSON.stringify(value);
32
+ if (!json || new TextEncoder().encode(json).length > 16 * 1024) {
33
+ throw new Error('Invalid analytics event');
34
+ }
35
+ const project = (candidate, depth) => {
36
+ if (depth > 12)
37
+ throw new Error('Analytics event nesting limit');
38
+ if (Array.isArray(candidate))
39
+ return candidate.map((item) => project(item, depth + 1));
40
+ if (!candidate || typeof candidate !== 'object')
41
+ return candidate;
42
+ return Object.fromEntries(Object.entries(candidate).filter(([key]) => !sensitiveKey.test(key.toLowerCase().replace(/[^a-z0-9]/g, ''))).map(([key, item]) => [key,
43
+ /(?:url$|^(?:pagelocation|referrer|referer)$)/.test(key.toLowerCase().replace(/[^a-z0-9]/g, ''))
44
+ ? sanitizeAnalyticsUrl(item) : project(item, depth + 1),
45
+ ]).filter(([, item]) => item !== undefined));
46
+ };
47
+ return project(JSON.parse(json), 0);
48
+ };
@@ -18,7 +18,7 @@ declare global {
18
18
  __funnelsgroveGoogleTagHeadReady?: boolean;
19
19
  __funnelsgroveGoogleTagPageLocation?: string;
20
20
  __funnelsgroveGoogleTagServiceReady?: boolean;
21
- __funnelsgroveSanitizeGoogleTagUrl?: (value: string) => string;
21
+ __funnelsgroveSanitizeGoogleTagUrl?: (value: string) => string | undefined;
22
22
  dataLayer?: unknown[];
23
23
  gtag?: (...args: unknown[]) => void;
24
24
  }
@@ -1,54 +1,8 @@
1
+ import { analyticsUrlSanitizerSource, sanitizeAnalyticsExport, sanitizeAnalyticsUrl } from './analytics-export.js';
1
2
  import { GOOGLE_TAG_CONFIG_IDS, GOOGLE_TAG_ENABLED, GOOGLE_TAG_LEAD_VALUE, GOOGLE_TAG_LEAD_SEND_TO, GOOGLE_TAG_MANAGER_ID, GOOGLE_TAG_PURCHASE_SEND_TO, GOOGLE_TAG_SCRIPT_ID, } from './runtime-api.config.js';
2
3
  import { buildBrowserPurchaseAnalyticsAttributes, buildPurchaseAnalyticsAttributes, currentBrowserPurchaseUrl, } from './purchase-attributes.service.js';
3
- const SENSITIVE_GOOGLE_TAG_PARAMETER_KEYS = new Set([
4
- 'customerEmail',
5
- 'customer_email',
6
- 'email',
7
- 'fullName',
8
- 'full_name',
9
- 'ipAddress',
10
- 'ip_address',
11
- 'name',
12
- 'phone',
13
- 'phoneNumber',
14
- 'phone_number',
15
- 'userAgent',
16
- 'user_agent',
17
- ]);
18
- const SENSITIVE_GOOGLE_TAG_QUERY_KEYS = new Set([
19
- 'customeremail',
20
- 'customer_email',
21
- 'email',
22
- 'fullname',
23
- 'full_name',
24
- 'name',
25
- 'phone',
26
- 'phonenumber',
27
- 'phone_number',
28
- ]);
29
4
  const buildGoogleAnalyticsScriptSrc = (googleAnalyticsId) => `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(googleAnalyticsId)}`;
30
5
  const buildGoogleTagManagerScriptSrc = (googleTagManagerId) => `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(googleTagManagerId)}`;
31
- const sanitizeUrlForGoogleTag = (value) => {
32
- if (typeof value !== 'string') {
33
- return undefined;
34
- }
35
- const trimmed = value.trim();
36
- if (!trimmed) {
37
- return undefined;
38
- }
39
- try {
40
- const parsed = new URL(trimmed, typeof window !== 'undefined' ? window.location.origin : 'https://example.invalid');
41
- for (const key of Array.from(parsed.searchParams.keys())) {
42
- if (SENSITIVE_GOOGLE_TAG_QUERY_KEYS.has(key.trim().toLowerCase())) {
43
- parsed.searchParams.delete(key);
44
- }
45
- }
46
- return parsed.toString();
47
- }
48
- catch (_a) {
49
- return trimmed;
50
- }
51
- };
52
6
  const asString = (value) => {
53
7
  if (typeof value !== 'string') {
54
8
  return undefined;
@@ -73,20 +27,14 @@ const buildDefinedRecord = (value) => {
73
27
  return Object.fromEntries(Object.entries(value).filter(([, candidate]) => candidate !== undefined && candidate !== null && candidate !== ''));
74
28
  };
75
29
  const sanitizeGoogleTagParameters = (parameters) => {
76
- return Object.fromEntries(Object.entries(parameters).flatMap(([key, value]) => {
77
- if (SENSITIVE_GOOGLE_TAG_PARAMETER_KEYS.has(key)) {
78
- return [];
79
- }
80
- if (key === 'url') {
81
- const sanitizedUrl = sanitizeUrlForGoogleTag(value);
82
- return sanitizedUrl ? [[key, sanitizedUrl]] : [];
83
- }
84
- if (key === 'page_location') {
85
- const sanitizedUrl = sanitizeUrlForGoogleTag(value);
86
- return sanitizedUrl ? [[key, sanitizedUrl]] : [];
87
- }
88
- return [[key, value]];
89
- }));
30
+ try {
31
+ // Preserve Google's existing additional exclusion of user-agent parameters.
32
+ const filtered = Object.fromEntries(Object.entries(parameters).filter(([key]) => key.toLowerCase().replace(/[^a-z0-9]/g, '') !== 'useragent'));
33
+ return sanitizeAnalyticsExport(filtered);
34
+ }
35
+ catch (_a) {
36
+ return {};
37
+ }
90
38
  };
91
39
  const buildStepParameters = (event, options = {}) => {
92
40
  var _a;
@@ -120,7 +68,7 @@ export const buildGoogleTagHeadScripts = () => {
120
68
  const bootstrapLines = [
121
69
  'window.dataLayer = window.dataLayer || [];',
122
70
  'window.gtag = window.gtag || function(){ window.dataLayer.push(arguments); };',
123
- 'window.__funnelsgroveSanitizeGoogleTagUrl = window.__funnelsgroveSanitizeGoogleTagUrl || function(value){ try { var url = new URL(value, window.location.origin); ["customeremail","customer_email","email","fullname","full_name","name","phone","phonenumber","phone_number"].forEach(function(key){ url.searchParams.delete(key); }); return url.href; } catch (error) { return value; } };',
71
+ `window.__funnelsgroveSanitizeGoogleTagUrl = ${analyticsUrlSanitizerSource};`,
124
72
  'window.__funnelsgroveGoogleTagPageLocation = window.__funnelsgroveSanitizeGoogleTagUrl(window.location.href);',
125
73
  'window.__funnelsgroveGoogleTagHeadReady = true;',
126
74
  ...(GOOGLE_TAG_CONFIG_IDS.length > 0
@@ -283,7 +231,7 @@ export class GoogleTagService {
283
231
  (_a = window.gtag) === null || _a === void 0 ? void 0 : _a.call(window, 'js', new Date());
284
232
  for (const googleTagConfigId of GOOGLE_TAG_CONFIG_IDS) {
285
233
  (_b = window.gtag) === null || _b === void 0 ? void 0 : _b.call(window, 'config', googleTagConfigId, {
286
- page_location: sanitizeUrlForGoogleTag((_c = window.location) === null || _c === void 0 ? void 0 : _c.href),
234
+ page_location: sanitizeAnalyticsUrl((_c = window.location) === null || _c === void 0 ? void 0 : _c.href),
287
235
  send_page_view: false,
288
236
  });
289
237
  }
@@ -0,0 +1,22 @@
1
+ export type PostHogDeliveryOptions = {
2
+ batchSize: number;
3
+ flushIntervalMs: number;
4
+ };
5
+ /** Owns a bounded, in-memory, best-effort delivery queue; it is not a durable outbox. */
6
+ export declare class PostHogDelivery {
7
+ private readonly batchSize;
8
+ private readonly flushIntervalMs;
9
+ private queue;
10
+ private queuedBytes;
11
+ private sendingCount;
12
+ private sendingBytes;
13
+ private timer;
14
+ private inFlight;
15
+ constructor(options: Partial<PostHogDeliveryOptions>);
16
+ enqueue(event: unknown): boolean;
17
+ flush(): Promise<number>;
18
+ private trim;
19
+ private schedule;
20
+ private drain;
21
+ private send;
22
+ }
@@ -0,0 +1,181 @@
1
+ import { canUseDom } from './sdk-user-id.storage.js';
2
+ import { sanitizeAnalyticsExport } from './analytics-export.js';
3
+ import { hasPostHogRuntimeConfig, POSTHOG_API_HOST, POSTHOG_PROJECT_API_KEY } from './runtime-api.config.js';
4
+ const MAX_EVENTS = 200;
5
+ const MAX_BYTES = 512 * 1024;
6
+ const MAX_EVENT_BYTES = 16 * 1024;
7
+ const MAX_BATCH_BYTES = 48 * 1024;
8
+ const MAX_AGE_MS = 5 * 60000;
9
+ const FLUSH_BUDGET_MS = 2000;
10
+ const RETRY_DELAY_MS = 1500;
11
+ const encoder = new TextEncoder();
12
+ const boundedOption = (value, fallback, maximum) => value !== undefined && Number.isFinite(value) && value > 0 ? Math.min(Math.floor(value) || 1, maximum) : fallback;
13
+ const retryDelay = (response) => {
14
+ var _a, _b;
15
+ const value = (_b = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get('retry-after')) === null || _b === void 0 ? void 0 : _b.trim();
16
+ if (!value)
17
+ return RETRY_DELAY_MS;
18
+ if (/^\d+$/.test(value))
19
+ return Math.max(RETRY_DELAY_MS, Number(value) * 1000);
20
+ const date = Date.parse(value);
21
+ return Number.isFinite(date) ? Math.max(RETRY_DELAY_MS, date - Date.now()) : RETRY_DELAY_MS;
22
+ };
23
+ /** Owns a bounded, in-memory, best-effort delivery queue; it is not a durable outbox. */
24
+ export class PostHogDelivery {
25
+ constructor(options) {
26
+ this.queue = [];
27
+ this.queuedBytes = 0;
28
+ this.sendingCount = 0;
29
+ this.sendingBytes = 0;
30
+ this.timer = null;
31
+ this.inFlight = null;
32
+ this.batchSize = boundedOption(options.batchSize, 20, 200);
33
+ this.flushIntervalMs = boundedOption(options.flushIntervalMs, 1500, 60000);
34
+ }
35
+ enqueue(event) {
36
+ if (!hasPostHogRuntimeConfig())
37
+ return true;
38
+ let json;
39
+ try {
40
+ json = JSON.stringify(sanitizeAnalyticsExport(event));
41
+ }
42
+ catch (_a) {
43
+ return false;
44
+ }
45
+ if (!json)
46
+ return false;
47
+ const bytes = encoder.encode(json).length;
48
+ if (bytes > MAX_EVENT_BYTES)
49
+ return false;
50
+ const now = performance.now();
51
+ this.queue.push({ json, bytes, createdAt: now, attempts: 0, notBefore: now });
52
+ this.trim(now);
53
+ if (this.queue.length >= this.batchSize)
54
+ void this.flush();
55
+ else
56
+ this.schedule();
57
+ return true;
58
+ }
59
+ flush() {
60
+ if (this.inFlight)
61
+ return this.inFlight;
62
+ if (this.timer !== null) {
63
+ if (canUseDom())
64
+ window.clearTimeout(this.timer);
65
+ this.timer = null;
66
+ }
67
+ this.inFlight = this.drain().finally(() => {
68
+ this.inFlight = null;
69
+ this.schedule();
70
+ });
71
+ return this.inFlight;
72
+ }
73
+ trim(now) {
74
+ this.queue = this.queue.filter((event) => now - event.createdAt < MAX_AGE_MS && event.attempts < 3
75
+ && event.notBefore - event.createdAt < MAX_AGE_MS);
76
+ this.queuedBytes = this.queue.reduce((total, event) => total + event.bytes, 0);
77
+ while (this.queue.length + this.sendingCount > MAX_EVENTS || this.queuedBytes + this.sendingBytes > MAX_BYTES) {
78
+ const removed = this.queue.shift();
79
+ if (!removed)
80
+ break;
81
+ this.queuedBytes -= removed.bytes;
82
+ }
83
+ }
84
+ schedule() {
85
+ if (!canUseDom() || this.timer !== null || this.inFlight || this.queue.length === 0)
86
+ return;
87
+ const now = performance.now();
88
+ const nextAttempt = Math.min(...this.queue.map((event) => event.notBefore));
89
+ const nextExpiry = Math.min(...this.queue.map((event) => event.createdAt + MAX_AGE_MS));
90
+ const delay = Math.max(0, Math.min(Math.max(this.flushIntervalMs, nextAttempt - now), nextExpiry - now));
91
+ this.timer = window.setTimeout(() => { this.timer = null; void this.flush(); }, delay);
92
+ }
93
+ async drain() {
94
+ var _a;
95
+ this.trim(performance.now());
96
+ const deadline = performance.now() + FLUSH_BUDGET_MS;
97
+ const available = this.queue.length;
98
+ let processed = 0;
99
+ let accepted = 0;
100
+ const prefix = `{"api_key":${JSON.stringify(POSTHOG_PROJECT_API_KEY)},"batch":[`;
101
+ while (processed < available && performance.now() < deadline) {
102
+ const batch = [];
103
+ let bytes = encoder.encode(prefix).length + 2;
104
+ for (let index = 0; index < this.queue.length && batch.length < this.batchSize && processed + batch.length < available;) {
105
+ const event = this.queue[index];
106
+ if (event.notBefore > performance.now()) {
107
+ index++;
108
+ continue;
109
+ }
110
+ const addedBytes = event.bytes + (batch.length ? 1 : 0);
111
+ if (bytes + addedBytes > MAX_BATCH_BYTES)
112
+ break;
113
+ this.queue.splice(index, 1);
114
+ this.queuedBytes -= event.bytes;
115
+ batch.push(event);
116
+ bytes += addedBytes;
117
+ }
118
+ if (batch.length === 0)
119
+ break;
120
+ this.sendingCount = batch.length;
121
+ this.sendingBytes = batch.reduce((sum, event) => sum + event.bytes, 0);
122
+ const result = await this.send(`${prefix}${batch.map((event) => event.json).join(',')}]}`, deadline - performance.now());
123
+ this.sendingCount = 0;
124
+ this.sendingBytes = 0;
125
+ processed += batch.length;
126
+ if (result.kind === 'accepted')
127
+ accepted += batch.length;
128
+ if (result.kind === 'retry') {
129
+ const notBefore = performance.now() + ((_a = result.retryDelayMs) !== null && _a !== void 0 ? _a : RETRY_DELAY_MS);
130
+ for (const event of batch) {
131
+ event.attempts++;
132
+ event.notBefore = notBefore;
133
+ }
134
+ this.queue.unshift(...batch);
135
+ }
136
+ this.trim(performance.now());
137
+ }
138
+ return accepted;
139
+ }
140
+ async send(payload, budgetMs) {
141
+ const endpoint = `${POSTHOG_API_HOST}/batch/`;
142
+ if (canUseDom() && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
143
+ try {
144
+ if (navigator.sendBeacon(endpoint, new Blob([payload], { type: 'application/json' })))
145
+ return { kind: 'accepted' };
146
+ }
147
+ catch ( /* A rejected beacon can still use the bounded fetch path. */_a) { /* A rejected beacon can still use the bounded fetch path. */ }
148
+ }
149
+ const controller = new AbortController();
150
+ let timer;
151
+ const timedOut = new Promise((resolve) => {
152
+ timer = setTimeout(() => {
153
+ controller.abort();
154
+ resolve({ kind: 'retry' });
155
+ }, Math.max(0, budgetMs));
156
+ });
157
+ const request = async () => {
158
+ var _a;
159
+ try {
160
+ const response = await fetch(endpoint, {
161
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload,
162
+ keepalive: true, signal: controller.signal,
163
+ });
164
+ await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());
165
+ if (response.ok)
166
+ return { kind: 'accepted' };
167
+ return [408, 429, 500, 502, 503, 504].includes(response.status)
168
+ ? { kind: 'retry', retryDelayMs: retryDelay(response) } : { kind: 'drop' };
169
+ }
170
+ catch (_b) {
171
+ return { kind: 'retry' };
172
+ }
173
+ };
174
+ try {
175
+ return await Promise.race([request(), timedOut]);
176
+ }
177
+ finally {
178
+ clearTimeout(timer);
179
+ }
180
+ }
181
+ }
@@ -1,3 +1,4 @@
1
+ import { type PostHogDeliveryOptions } from './posthog-delivery.js';
1
2
  import { type FunnelStepExitReason, type FunnelStepType } from '@funnelsgrove/runtime';
2
3
  export type PublicSdkTrackEventInput = {
3
4
  eventType: string;
@@ -101,20 +102,14 @@ export type PublicSdkIdentifyInput = {
101
102
  fullName?: string;
102
103
  metadata?: Record<string, unknown>;
103
104
  };
104
- export type PublicAnalyticsSdkOptions = {
105
- batchSize: number;
106
- flushIntervalMs: number;
107
- };
105
+ export type PublicAnalyticsSdkOptions = PostHogDeliveryOptions;
108
106
  export type PublicSdkAnalyticsEnvironment = 'test' | 'live';
109
107
  type SecureBootstrapCrypto = Pick<Crypto, 'getRandomValues'> & {
110
108
  randomUUID?: () => `${string}-${string}-${string}-${string}-${string}` | string;
111
109
  };
112
110
  export declare const createBootstrapIdempotencyKey: (secureCrypto?: SecureBootstrapCrypto) => string;
113
111
  export declare class PublicAnalyticsSdkService {
114
- private readonly options;
115
- private readonly eventQueue;
116
- private flushTimerId;
117
- private inFlightFlush;
112
+ private readonly delivery;
118
113
  private userId;
119
114
  constructor(options?: Partial<PublicAnalyticsSdkOptions>);
120
115
  getCurrentUserId(): string;
@@ -150,10 +145,7 @@ export declare class PublicAnalyticsSdkService {
150
145
  flush(): Promise<number>;
151
146
  private ensureUserId;
152
147
  private resolveBootstrapUserId;
153
- private scheduleFlush;
154
- private clearFlushTimer;
155
- private flushQueue;
156
- private sendBatch;
148
+ private toPostHogEvent;
157
149
  }
158
150
  export declare const publicAnalyticsSdk: PublicAnalyticsSdkService;
159
151
  export {};
@@ -1,14 +1,10 @@
1
- import { FUNNEL_ANALYTICS_EVENT_CONTRACTS, FUNNEL_STEP_CONTRACTS, } from '@funnelsgrove/runtime';
2
- import { buildMainApiUrl, buildSdkHeaders, FUNNEL_ID, FUNNEL_VERSION_ID, getFunnelSdkPublishableKey, hasPostHogRuntimeConfig, POSTHOG_API_HOST, POSTHOG_PROJECT_API_KEY, PROJECT_ID, } from './runtime-api.config.js';
1
+ import { PostHogDelivery } from './posthog-delivery.js';
2
+ import { FUNNEL_ANALYTICS_EVENT_CONTRACTS, funnelSdkService, FUNNEL_STEP_CONTRACTS, } from '@funnelsgrove/runtime';
3
+ import { APP_DEALS_API_BASE_URL, FUNNEL_ID, FUNNEL_VERSION_ID, getFunnelSdkPublishableKey, PROJECT_ID, } from './runtime-api.config.js';
3
4
  import { canUseDom, getOrCreateUserId, persistUserId, readStoredUserId, } from './sdk-user-id.storage.js';
4
5
  import { mapAnalyticsEventToMetaPixelEvent, metaPixelService, } from './meta-pixel.service.js';
5
6
  import { googleTagService, mapAnalyticsEventToGoogleTagEvents, } from './google-tag.service.js';
6
7
  import { currentBrowserPurchaseUrl, sanitizePurchaseUrl, } from './purchase-attributes.service.js';
7
- const DEFAULT_OPTIONS = {
8
- batchSize: 20,
9
- flushIntervalMs: 1500,
10
- };
11
- const POSTHOG_BATCH_ENDPOINT = '/batch/';
12
8
  const DEFAULT_FUNNEL_DOMAIN_SIGNAL = 'funnelsgrove';
13
9
  const RESERVED_ANALYTICS_EVENT_TYPES = new Set(Object.values(FUNNEL_ANALYTICS_EVENT_CONTRACTS).flatMap((contract) => [
14
10
  contract.rawName,
@@ -173,45 +169,16 @@ export const createBootstrapIdempotencyKey = (secureCrypto = globalThis.crypto)
173
169
  const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
174
170
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
175
171
  };
176
- const SDK_DEPENDENCY_UNAVAILABLE = 'SDK_DEPENDENCY_UNAVAILABLE';
177
- const DEFAULT_BOOTSTRAP_RETRY_DELAY_MS = 1000;
178
- const MAX_BOOTSTRAP_RETRY_DELAY_MS = 5000;
179
- const retryAfterMilliseconds = (response) => {
180
- var _a;
181
- const retryAfter = (_a = response.headers.get('retry-after')) === null || _a === void 0 ? void 0 : _a.trim();
182
- if (!retryAfter) {
183
- return DEFAULT_BOOTSTRAP_RETRY_DELAY_MS;
184
- }
185
- if (/^\d+$/.test(retryAfter)) {
186
- return Math.min(Number(retryAfter) * 1000, MAX_BOOTSTRAP_RETRY_DELAY_MS);
187
- }
188
- const retryAt = Date.parse(retryAfter);
189
- return Number.isNaN(retryAt)
190
- ? DEFAULT_BOOTSTRAP_RETRY_DELAY_MS
191
- : Math.min(Math.max(0, retryAt - Date.now()), MAX_BOOTSTRAP_RETRY_DELAY_MS);
192
- };
193
- const isRetryableBootstrapDependencyFailure = async (response) => {
194
- if (response.status !== 503) {
195
- return false;
196
- }
197
- try {
198
- const payload = asRecord(await response.clone().json());
199
- return payload.code === SDK_DEPENDENCY_UNAVAILABLE && payload.retryable === true;
200
- }
201
- catch (_a) {
202
- return false;
203
- }
204
- };
205
- const delay = (milliseconds) => new Promise((resolve) => {
206
- setTimeout(resolve, milliseconds);
172
+ const analyticsRuntimeConfig = (publishableKey) => ({
173
+ apiBaseUrl: APP_DEALS_API_BASE_URL,
174
+ funnelId: FUNNEL_ID,
175
+ funnelVersionId: FUNNEL_VERSION_ID,
176
+ funnelSdkPublishableKey: publishableKey,
207
177
  });
208
178
  export class PublicAnalyticsSdkService {
209
179
  constructor(options = {}) {
210
- this.options = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
211
- this.eventQueue = [];
212
- this.flushTimerId = null;
213
- this.inFlightFlush = null;
214
180
  this.userId = null;
181
+ this.delivery = new PostHogDelivery(options);
215
182
  googleTagService.initialize();
216
183
  }
217
184
  getCurrentUserId() {
@@ -227,32 +194,14 @@ export class PublicAnalyticsSdkService {
227
194
  }
228
195
  try {
229
196
  const idempotencyKey = createBootstrapIdempotencyKey();
230
- const requestBootstrap = () => fetch(buildMainApiUrl('/sdk/public/users/bootstrap'), {
231
- method: 'POST',
232
- headers: buildSdkHeaders({
233
- 'Content-Type': 'application/json',
234
- }),
235
- body: JSON.stringify({
236
- publishableKey,
237
- funnelId: FUNNEL_ID || undefined,
238
- funnelVersionId: FUNNEL_VERSION_ID || undefined,
239
- user_id: userId,
240
- idempotencyKey,
241
- email: asString(input.email) || undefined,
242
- fullName: asString(input.fullName) || undefined,
243
- metadata: Object.assign({ environment: resolveAnalyticsEnvironment() }, asRecord(input.metadata)),
244
- }),
197
+ const payload = await funnelSdkService.bootstrapUser({
198
+ userId,
199
+ idempotencyKey,
200
+ email: asString(input.email),
201
+ fullName: asString(input.fullName),
202
+ metadata: Object.assign({ environment: resolveAnalyticsEnvironment() }, asRecord(input.metadata)),
203
+ runtimeConfig: analyticsRuntimeConfig(publishableKey),
245
204
  });
246
- let response = await requestBootstrap();
247
- if (await isRetryableBootstrapDependencyFailure(response)) {
248
- await delay(retryAfterMilliseconds(response));
249
- response = await requestBootstrap();
250
- }
251
- if (!response.ok) {
252
- this.userId = userId;
253
- return userId;
254
- }
255
- const payload = (await response.json());
256
205
  const persistedUserId = persistUserId(asString((_a = payload.user) === null || _a === void 0 ? void 0 : _a.user_id) ||
257
206
  asString(payload.user_id) ||
258
207
  userId, FUNNEL_ID) || userId;
@@ -274,17 +223,9 @@ export class PublicAnalyticsSdkService {
274
223
  return null;
275
224
  }
276
225
  try {
277
- const url = new URL(buildMainApiUrl('/sdk/public/users/me'));
278
- url.searchParams.set('funnelId', FUNNEL_ID);
279
- url.searchParams.set('user_id', userId);
280
- const response = await fetch(url.toString(), {
281
- method: 'GET',
282
- headers: buildSdkHeaders({}),
226
+ const payload = await funnelSdkService.getCurrentUser({
227
+ userId, runtimeConfig: analyticsRuntimeConfig(publishableKey),
283
228
  });
284
- if (!response.ok) {
285
- return null;
286
- }
287
- const payload = (await response.json());
288
229
  return {
289
230
  user: payload.user || null,
290
231
  events: Array.isArray(payload.events) ? payload.events : [],
@@ -372,13 +313,7 @@ export class PublicAnalyticsSdkService {
372
313
  metadata,
373
314
  featureFlags: normalizeFeatureFlags(event.featureFlags),
374
315
  };
375
- this.eventQueue.push(envelope);
376
- if (this.eventQueue.length >= this.options.batchSize) {
377
- void this.flush();
378
- return envelope.eventId;
379
- }
380
- this.scheduleFlush();
381
- return envelope.eventId;
316
+ return this.delivery.enqueue(this.toPostHogEvent(envelope)) ? envelope.eventId : null;
382
317
  }
383
318
  trackContractCallback(eventName, input) {
384
319
  const contract = FUNNEL_ANALYTICS_EVENT_CONTRACTS[eventName];
@@ -579,15 +514,8 @@ export class PublicAnalyticsSdkService {
579
514
  featureFlags: input.featureFlags,
580
515
  });
581
516
  }
582
- async flush() {
583
- if (this.inFlightFlush) {
584
- return this.inFlightFlush;
585
- }
586
- this.clearFlushTimer();
587
- this.inFlightFlush = this.flushQueue().finally(() => {
588
- this.inFlightFlush = null;
589
- });
590
- return this.inFlightFlush;
517
+ flush() {
518
+ return this.delivery.flush();
591
519
  }
592
520
  ensureUserId() {
593
521
  if (this.userId) {
@@ -616,80 +544,17 @@ export class PublicAnalyticsSdkService {
616
544
  const validatedUserId = asString((_a = existingUserState === null || existingUserState === void 0 ? void 0 : existingUserState.user) === null || _a === void 0 ? void 0 : _a.user_id);
617
545
  return persistUserId(validatedUserId || fallbackUserId, FUNNEL_ID);
618
546
  }
619
- scheduleFlush() {
620
- if (!canUseDom() || this.flushTimerId !== null || this.eventQueue.length === 0) {
621
- return;
622
- }
623
- this.flushTimerId = window.setTimeout(() => {
624
- this.flushTimerId = null;
625
- void this.flush();
626
- }, this.options.flushIntervalMs);
627
- }
628
- clearFlushTimer() {
629
- if (!canUseDom() || this.flushTimerId === null) {
630
- return;
631
- }
632
- window.clearTimeout(this.flushTimerId);
633
- this.flushTimerId = null;
634
- }
635
- async flushQueue() {
636
- let sentEvents = 0;
637
- while (this.eventQueue.length > 0) {
638
- const batch = this.eventQueue.splice(0, this.options.batchSize);
639
- const delivered = await this.sendBatch(batch);
640
- if (!delivered) {
641
- this.eventQueue.unshift(...batch);
642
- break;
643
- }
644
- sentEvents += batch.length;
645
- }
646
- if (this.eventQueue.length > 0) {
647
- this.scheduleFlush();
648
- }
649
- return sentEvents;
650
- }
651
- async sendBatch(events) {
652
- if (events.length === 0) {
653
- return true;
654
- }
655
- if (!getFunnelSdkPublishableKey() || !hasPostHogRuntimeConfig()) {
656
- return true;
657
- }
547
+ toPostHogEvent(event) {
548
+ var _a, _b, _c;
658
549
  const analyticsEnvironment = resolveAnalyticsEnvironment();
659
- const batch = events.map((event) => {
660
- var _a, _b, _c;
661
- const eventEnvironment = event.environment || analyticsEnvironment;
662
- return {
663
- event: toPostHogEventName(event.eventType),
664
- properties: buildDefinedRecord(Object.assign(Object.assign({ distinct_id: event.userId || this.ensureUserId(), $groups: {
665
- project: PROJECT_ID,
666
- }, $insert_id: event.eventId, project_id: PROJECT_ID, funnel_id: FUNNEL_ID || undefined, funnel_version_id: FUNNEL_VERSION_ID || undefined, environment: eventEnvironment, test: eventEnvironment === 'test' || undefined, step_id: event.stepId || undefined, step_name: event.stepName || undefined, step_type: event.stepType || undefined, started_at: event.startedAt || undefined, ended_at: event.endedAt || undefined, duration_ms: (_a = event.durationMs) !== null && _a !== void 0 ? _a : undefined, exit_reason: event.exitReason || undefined, step_contract_version: (_b = event.stepContractVersion) !== null && _b !== void 0 ? _b : undefined, engagement_threshold_ms: (_c = event.engagementThresholdMs) !== null && _c !== void 0 ? _c : undefined, user_agent: currentBrowserUserAgent(), event_source: 'client' }, buildFeatureFlagProperties(event.featureFlags)), { selected: Object.keys(event.selected).length > 0 ? event.selected : undefined, payload: Object.keys(event.payload).length > 0 ? event.payload : undefined, context: Object.keys(event.context).length > 0 ? event.context : undefined, metadata: Object.keys(event.metadata).length > 0 ? event.metadata : undefined })),
667
- timestamp: event.occurredAt,
668
- };
669
- });
670
- const payload = JSON.stringify({
671
- api_key: POSTHOG_PROJECT_API_KEY,
672
- batch,
673
- });
674
- const endpoint = `${POSTHOG_API_HOST}${POSTHOG_BATCH_ENDPOINT}`;
675
- if (canUseDom() && typeof navigator.sendBeacon === 'function') {
676
- const accepted = navigator.sendBeacon(endpoint, new Blob([payload], { type: 'application/json' }));
677
- if (accepted) {
678
- return true;
679
- }
680
- }
681
- try {
682
- const response = await fetch(endpoint, {
683
- method: 'POST',
684
- headers: { 'Content-Type': 'application/json' },
685
- body: payload,
686
- keepalive: true,
687
- });
688
- return response.ok;
689
- }
690
- catch (_a) {
691
- return false;
692
- }
550
+ const eventEnvironment = event.environment || analyticsEnvironment;
551
+ return {
552
+ event: toPostHogEventName(event.eventType),
553
+ properties: buildDefinedRecord(Object.assign(Object.assign({ distinct_id: event.userId || this.ensureUserId(), $groups: {
554
+ project: PROJECT_ID,
555
+ }, $insert_id: event.eventId, project_id: PROJECT_ID, funnel_id: FUNNEL_ID || undefined, funnel_version_id: FUNNEL_VERSION_ID || undefined, environment: eventEnvironment, test: eventEnvironment === 'test' || undefined, step_id: event.stepId || undefined, step_name: event.stepName || undefined, step_type: event.stepType || undefined, started_at: event.startedAt || undefined, ended_at: event.endedAt || undefined, duration_ms: (_a = event.durationMs) !== null && _a !== void 0 ? _a : undefined, exit_reason: event.exitReason || undefined, step_contract_version: (_b = event.stepContractVersion) !== null && _b !== void 0 ? _b : undefined, engagement_threshold_ms: (_c = event.engagementThresholdMs) !== null && _c !== void 0 ? _c : undefined, user_agent: currentBrowserUserAgent(), event_source: 'client' }, buildFeatureFlagProperties(event.featureFlags)), { selected: Object.keys(event.selected).length > 0 ? event.selected : undefined, payload: Object.keys(event.payload).length > 0 ? event.payload : undefined, context: Object.keys(event.context).length > 0 ? event.context : undefined, metadata: Object.keys(event.metadata).length > 0 ? event.metadata : undefined })),
556
+ timestamp: event.occurredAt,
557
+ };
693
558
  }
694
559
  }
695
560
  export const publicAnalyticsSdk = new PublicAnalyticsSdkService();
@@ -1,16 +1,6 @@
1
+ import { sanitizeAnalyticsUrl } from './analytics-export.js';
1
2
  const STRIPE_METADATA_KEY_MAX_LENGTH = 40;
2
3
  const STRIPE_METADATA_VALUE_MAX_LENGTH = 500;
3
- const SENSITIVE_PURCHASE_URL_QUERY_KEYS = new Set([
4
- 'customeremail',
5
- 'customer_email',
6
- 'email',
7
- 'fullname',
8
- 'full_name',
9
- 'name',
10
- 'phone',
11
- 'phonenumber',
12
- 'phone_number',
13
- ]);
14
4
  const FLAT_ATTRIBUTION_KEYS = new Set([
15
5
  '_fbc',
16
6
  '_fbp',
@@ -119,24 +109,7 @@ const resolveLastNonOrganicTouch = (input, attribution) => {
119
109
  .map(asRecord)
120
110
  .find((candidate) => Object.keys(candidate).length > 0) || {};
121
111
  };
122
- export const sanitizePurchaseUrl = (value) => {
123
- const normalized = toString(value);
124
- if (!normalized) {
125
- return undefined;
126
- }
127
- try {
128
- const parsed = new URL(normalized, typeof window !== 'undefined' ? window.location.origin : 'https://example.invalid');
129
- for (const key of Array.from(parsed.searchParams.keys())) {
130
- if (SENSITIVE_PURCHASE_URL_QUERY_KEYS.has(key.trim().toLowerCase())) {
131
- parsed.searchParams.delete(key);
132
- }
133
- }
134
- return parsed.toString();
135
- }
136
- catch (_a) {
137
- return normalized;
138
- }
139
- };
112
+ export const sanitizePurchaseUrl = (value) => sanitizeAnalyticsUrl(value);
140
113
  export const currentBrowserPurchaseUrl = () => {
141
114
  var _a;
142
115
  if (typeof window === 'undefined') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/analytics",
3
- "version": "0.1.93",
3
+ "version": "0.1.96",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/The-Solid-Grove/funnelsgrove.git",
@@ -36,7 +36,7 @@
36
36
  "test:run": "vitest run --passWithNoTests"
37
37
  },
38
38
  "dependencies": {
39
- "@funnelsgrove/runtime": "0.11.8"
39
+ "@funnelsgrove/runtime": "0.11.10"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/node": "^20",