@funnelsgrove/analytics 0.1.7 → 0.1.9

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.
@@ -16,7 +16,9 @@ export type AnalyticsEventForGoogleTag = {
16
16
  declare global {
17
17
  interface Window {
18
18
  __funnelsgroveGoogleTagHeadReady?: boolean;
19
+ __funnelsgroveGoogleTagPageLocation?: string;
19
20
  __funnelsgroveGoogleTagServiceReady?: boolean;
21
+ __funnelsgroveSanitizeGoogleTagUrl?: (value: string) => string;
20
22
  dataLayer?: unknown[];
21
23
  gtag?: (...args: unknown[]) => void;
22
24
  }
@@ -3,8 +3,67 @@ import { buildBrowserPurchaseAnalyticsAttributes } from './purchase-attributes.s
3
3
  const normalizeEventTarget = (value) => {
4
4
  return value === 'dataLayer' || value === 'gtag' || value === 'both' ? value : 'both';
5
5
  };
6
+ const SENSITIVE_GOOGLE_TAG_PARAMETER_KEYS = new Set([
7
+ 'customerEmail',
8
+ 'customer_email',
9
+ 'email',
10
+ 'fullName',
11
+ 'full_name',
12
+ 'ipAddress',
13
+ 'ip_address',
14
+ 'name',
15
+ 'phone',
16
+ 'phoneNumber',
17
+ 'phone_number',
18
+ 'userAgent',
19
+ 'user_agent',
20
+ ]);
21
+ const SENSITIVE_GOOGLE_TAG_QUERY_KEYS = new Set([
22
+ 'customeremail',
23
+ 'customer_email',
24
+ 'email',
25
+ 'fullname',
26
+ 'full_name',
27
+ 'name',
28
+ 'phone',
29
+ 'phonenumber',
30
+ 'phone_number',
31
+ ]);
6
32
  const buildGoogleAnalyticsScriptSrc = (googleAnalyticsId) => `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(googleAnalyticsId)}`;
7
33
  const buildGoogleTagManagerScriptSrc = (googleTagManagerId) => `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(googleTagManagerId)}`;
34
+ const sanitizeUrlForGoogleTag = (value) => {
35
+ if (typeof value !== 'string') {
36
+ return undefined;
37
+ }
38
+ const trimmed = value.trim();
39
+ if (!trimmed) {
40
+ return undefined;
41
+ }
42
+ try {
43
+ const parsed = new URL(trimmed, typeof window !== 'undefined' ? window.location.origin : 'https://example.invalid');
44
+ for (const key of Array.from(parsed.searchParams.keys())) {
45
+ if (SENSITIVE_GOOGLE_TAG_QUERY_KEYS.has(key.trim().toLowerCase())) {
46
+ parsed.searchParams.delete(key);
47
+ }
48
+ }
49
+ return parsed.toString();
50
+ }
51
+ catch (_a) {
52
+ return trimmed;
53
+ }
54
+ };
55
+ const sanitizeGoogleTagParameters = (parameters) => {
56
+ return Object.fromEntries(Object.entries(parameters).flatMap(([key, value]) => {
57
+ if (SENSITIVE_GOOGLE_TAG_PARAMETER_KEYS.has(key)) {
58
+ return [];
59
+ }
60
+ if (key === 'url') {
61
+ const sanitizedUrl = sanitizeUrlForGoogleTag(value);
62
+ return sanitizedUrl ? [[key, sanitizedUrl]] : [];
63
+ }
64
+ return [[key, value]];
65
+ }));
66
+ };
8
67
  export const buildGoogleTagHeadScripts = () => {
9
68
  if (!GOOGLE_TAG_ENABLED || (!GOOGLE_ANALYTICS_ID && !GOOGLE_TAG_MANAGER_ID)) {
10
69
  return [];
@@ -12,11 +71,13 @@ export const buildGoogleTagHeadScripts = () => {
12
71
  const bootstrapLines = [
13
72
  'window.dataLayer = window.dataLayer || [];',
14
73
  'window.gtag = window.gtag || function(){ window.dataLayer.push(arguments); };',
74
+ '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; } };',
75
+ 'window.__funnelsgroveGoogleTagPageLocation = window.__funnelsgroveSanitizeGoogleTagUrl(window.location.href);',
15
76
  'window.__funnelsgroveGoogleTagHeadReady = true;',
16
77
  ...(GOOGLE_ANALYTICS_ID
17
78
  ? [
18
79
  'window.gtag("js", new Date());',
19
- `window.gtag("config", ${JSON.stringify(GOOGLE_ANALYTICS_ID)});`,
80
+ `window.gtag("config", ${JSON.stringify(GOOGLE_ANALYTICS_ID)}, { page_location: window.__funnelsgroveGoogleTagPageLocation });`,
20
81
  ]
21
82
  : []),
22
83
  ...(GOOGLE_TAG_MANAGER_ID
@@ -54,7 +115,7 @@ export const mapAnalyticsEventToGoogleTagEvent = (event) => {
54
115
  case 'checkout_completed':
55
116
  return {
56
117
  eventName: 'purchase',
57
- parameters: buildBrowserPurchaseAnalyticsAttributes(Object.assign(Object.assign({}, ((_a = event.metadata) !== null && _a !== void 0 ? _a : {})), { transactionId: event.eventId })),
118
+ parameters: sanitizeGoogleTagParameters(buildBrowserPurchaseAnalyticsAttributes(Object.assign(Object.assign({}, ((_a = event.metadata) !== null && _a !== void 0 ? _a : {})), { transactionId: event.eventId }))),
58
119
  };
59
120
  default:
60
121
  return null;
@@ -76,7 +137,7 @@ export class GoogleTagService {
76
137
  return;
77
138
  }
78
139
  this.initialize();
79
- const parameters = (_a = input.parameters) !== null && _a !== void 0 ? _a : {};
140
+ const parameters = sanitizeGoogleTagParameters((_a = input.parameters) !== null && _a !== void 0 ? _a : {});
80
141
  const eventTarget = normalizeEventTarget(GOOGLE_TAG_EVENT_TARGET);
81
142
  if (eventTarget === 'dataLayer' || eventTarget === 'both') {
82
143
  (_b = window.dataLayer) === null || _b === void 0 ? void 0 : _b.push(Object.assign({ event: input.eventName }, parameters));
@@ -91,7 +152,7 @@ export class GoogleTagService {
91
152
  typeof window !== 'undefined');
92
153
  }
93
154
  ensureInitialized() {
94
- var _a, _b, _c;
155
+ var _a, _b, _c, _d;
95
156
  if (this.initialized) {
96
157
  return;
97
158
  }
@@ -104,10 +165,12 @@ export class GoogleTagService {
104
165
  if (GOOGLE_ANALYTICS_ID) {
105
166
  this.installScript(buildGoogleAnalyticsScriptSrc(GOOGLE_ANALYTICS_ID));
106
167
  (_a = window.gtag) === null || _a === void 0 ? void 0 : _a.call(window, 'js', new Date());
107
- (_b = window.gtag) === null || _b === void 0 ? void 0 : _b.call(window, 'config', GOOGLE_ANALYTICS_ID);
168
+ (_b = window.gtag) === null || _b === void 0 ? void 0 : _b.call(window, 'config', GOOGLE_ANALYTICS_ID, {
169
+ page_location: sanitizeUrlForGoogleTag((_c = window.location) === null || _c === void 0 ? void 0 : _c.href),
170
+ });
108
171
  }
109
172
  if (GOOGLE_TAG_MANAGER_ID) {
110
- (_c = window.dataLayer) === null || _c === void 0 ? void 0 : _c.push({
173
+ (_d = window.dataLayer) === null || _d === void 0 ? void 0 : _d.push({
111
174
  'gtm.start': Date.now(),
112
175
  event: 'gtm.js',
113
176
  });
@@ -2,6 +2,7 @@ import { buildMainApiUrl, buildSdkHeaders, FUNNEL_ID, FUNNEL_VERSION_ID, getFunn
2
2
  import { canUseDom, getOrCreateUserId, persistUserId, readStoredUserId, } from './sdk-user-id.storage.js';
3
3
  import { mapAnalyticsEventToMetaPixelEvent, metaPixelService, } from './meta-pixel.service.js';
4
4
  import { googleTagService, mapAnalyticsEventToGoogleTagEvent, } from './google-tag.service.js';
5
+ import { currentBrowserPurchaseUrl, sanitizePurchaseUrl, } from './purchase-attributes.service.js';
5
6
  const DEFAULT_OPTIONS = {
6
7
  batchSize: 20,
7
8
  flushIntervalMs: 1500,
@@ -79,6 +80,13 @@ const normalizeFeatureFlags = (featureFlags) => {
79
80
  const buildFeatureFlagProperties = (featureFlags) => {
80
81
  return Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [`$feature/${key}`, value]));
81
82
  };
83
+ const buildEventMetadata = (eventType, metadata) => {
84
+ if (eventType !== 'checkout_completed') {
85
+ return metadata;
86
+ }
87
+ const checkoutUrl = sanitizePurchaseUrl(metadata.url) || currentBrowserPurchaseUrl();
88
+ return checkoutUrl ? Object.assign(Object.assign({}, metadata), { url: checkoutUrl }) : metadata;
89
+ };
82
90
  export class PublicAnalyticsSdkService {
83
91
  constructor(options = {}) {
84
92
  this.options = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
@@ -170,10 +178,11 @@ export class PublicAnalyticsSdkService {
170
178
  return null;
171
179
  }
172
180
  const eventId = asString(event.eventId) || buildEventId();
181
+ const metadata = buildEventMetadata(eventType, asRecord(event.metadata));
173
182
  const metaPixelEvent = mapAnalyticsEventToMetaPixelEvent({
174
183
  eventType,
175
184
  eventId,
176
- metadata: asRecord(event.metadata),
185
+ metadata,
177
186
  });
178
187
  if (metaPixelEvent) {
179
188
  metaPixelService.track(metaPixelEvent);
@@ -181,7 +190,7 @@ export class PublicAnalyticsSdkService {
181
190
  const googleTagEvent = mapAnalyticsEventToGoogleTagEvent({
182
191
  eventType,
183
192
  eventId,
184
- metadata: asRecord(event.metadata),
193
+ metadata,
185
194
  });
186
195
  if (googleTagEvent) {
187
196
  googleTagService.track(googleTagEvent);
@@ -202,7 +211,7 @@ export class PublicAnalyticsSdkService {
202
211
  selected: asRecord(event.selected),
203
212
  payload: asRecord(event.payload),
204
213
  context: asRecord(event.context),
205
- metadata: asRecord(event.metadata),
214
+ metadata,
206
215
  featureFlags: normalizeFeatureFlags(event.featureFlags),
207
216
  };
208
217
  this.eventQueue.push(envelope);
@@ -21,6 +21,8 @@ export type PurchaseAnalyticsAttributesInput = {
21
21
  userId?: unknown;
22
22
  value?: unknown;
23
23
  };
24
+ export declare const sanitizePurchaseUrl: (value: unknown) => string | undefined;
25
+ export declare const currentBrowserPurchaseUrl: () => string | undefined;
24
26
  export declare const buildPurchaseAnalyticsAttributes: (input?: PurchaseAnalyticsAttributesInput & Record<string, unknown>, options?: {
25
27
  includeUrl?: boolean;
26
28
  }) => Record<string, unknown>;
@@ -1,5 +1,32 @@
1
1
  const STRIPE_METADATA_KEY_MAX_LENGTH = 40;
2
2
  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
+ const FLAT_ATTRIBUTION_KEYS = new Set([
15
+ '_fbc',
16
+ '_fbp',
17
+ 'epik',
18
+ 'fbc',
19
+ 'fbclid',
20
+ 'fbp',
21
+ 'gbraid',
22
+ 'gclid',
23
+ 'li_fat_id',
24
+ 'msclkid',
25
+ 'scclid',
26
+ 'ttclid',
27
+ 'twclid',
28
+ 'wbraid',
29
+ ]);
3
30
  const isRecord = (value) => {
4
31
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
5
32
  };
@@ -59,12 +86,44 @@ const normalizeAttributionTouch = (value) => {
59
86
  return [[normalizedKey, normalizedValue]];
60
87
  }));
61
88
  };
62
- const currentBrowserUrl = () => {
89
+ const isFlatAttributionKey = (key) => {
90
+ const normalizedKey = key.trim().toLowerCase();
91
+ return normalizedKey.startsWith('utm_') || FLAT_ATTRIBUTION_KEYS.has(normalizedKey);
92
+ };
93
+ const normalizeFlatAttributionTouch = (value) => {
94
+ return Object.fromEntries(Object.entries(value).flatMap(([key, candidate]) => {
95
+ const normalizedKey = key.trim();
96
+ if (!normalizedKey || !isFlatAttributionKey(normalizedKey)) {
97
+ return [];
98
+ }
99
+ const normalizedValue = toScalar(candidate);
100
+ return normalizedValue === undefined ? [] : [[normalizedKey, normalizedValue]];
101
+ }));
102
+ };
103
+ export const sanitizePurchaseUrl = (value) => {
104
+ const normalized = toString(value);
105
+ if (!normalized) {
106
+ return undefined;
107
+ }
108
+ try {
109
+ const parsed = new URL(normalized, typeof window !== 'undefined' ? window.location.origin : 'https://example.invalid');
110
+ for (const key of Array.from(parsed.searchParams.keys())) {
111
+ if (SENSITIVE_PURCHASE_URL_QUERY_KEYS.has(key.trim().toLowerCase())) {
112
+ parsed.searchParams.delete(key);
113
+ }
114
+ }
115
+ return parsed.toString();
116
+ }
117
+ catch (_a) {
118
+ return normalized;
119
+ }
120
+ };
121
+ export const currentBrowserPurchaseUrl = () => {
63
122
  var _a;
64
123
  if (typeof window === 'undefined') {
65
124
  return undefined;
66
125
  }
67
- return toString((_a = window.location) === null || _a === void 0 ? void 0 : _a.href);
126
+ return sanitizePurchaseUrl((_a = window.location) === null || _a === void 0 ? void 0 : _a.href);
68
127
  };
69
128
  export const buildPurchaseAnalyticsAttributes = (input = {}, options = {}) => {
70
129
  var _a, _b;
@@ -75,7 +134,9 @@ export const buildPurchaseAnalyticsAttributes = (input = {}, options = {}) => {
75
134
  const transactionInfo = asRecord(document.transactionInfo);
76
135
  const amountCents = toNumber(input.amountCents);
77
136
  const value = (_b = toNumber(input.value)) !== null && _b !== void 0 ? _b : (amountCents === undefined ? undefined : amountCents / 100);
78
- return buildDefinedRecord(Object.assign(Object.assign({}, normalizeAttributionTouch(attribution.firstTouch)), { currency: toCurrency(input.currency), value, plan_id: firstString(input.planId, input.plan_id), provider_plan_id: firstString(input.providerPlanId, input.provider_plan_id), coupon_id: firstString(input.couponId, input.coupon_id), environment: firstString(input.environment), user_id: firstString(input.userId, input.user_id), project_id: firstString(input.projectId, input.project_id), funnel_id: firstString(input.funnelId, input.funnel_id), funnel_version: firstString(input.funnelVersion, input.funnelVersionId, input.funnel_version), ip_address: firstString(input.ipAddress, input.ip_address, transactionInfo.ipAddress, transactionInfo.ip_address), user_agent: firstString(input.userAgent, input.user_agent, attributionContext.userAgent), timezone: firstString(input.timezone, input.time_zone, progressAttributes.timezone, progressAttributes.time_zone, document.timezone, document.time_zone, attributionContext.timezone, attributionContext.time_zone), geo_city: firstString(input.geoCity, input.geo_city, progressAttributes.geo_city, progressAttributes.geoCity, document.geo_city, document.geoCity, asRecord(document.geo).city, attributionContext.geo_city, attributionContext.geoCity, attributionContext.cityName, attributionContext.city), geo_country: firstString(input.geoCountry, input.geo_country, progressAttributes.geo_country, progressAttributes.geoCountry, document.geo_country, document.geoCountry, asRecord(document.geo).country, attributionContext.geo_country, attributionContext.geoCountry, attributionContext.countryName, attributionContext.countryCode, attributionContext.country), transaction_id: firstString(input.transactionId, input.transaction_id), url: options.includeUrl ? firstString(input.url, currentBrowserUrl()) : undefined }));
137
+ return buildDefinedRecord(Object.assign(Object.assign(Object.assign({}, normalizeFlatAttributionTouch(input)), normalizeAttributionTouch(attribution.firstTouch)), { currency: toCurrency(input.currency), value, plan_id: firstString(input.planId, input.plan_id), provider_plan_id: firstString(input.providerPlanId, input.provider_plan_id), coupon_id: firstString(input.couponId, input.coupon_id), environment: firstString(input.environment), user_id: firstString(input.userId, input.user_id), project_id: firstString(input.projectId, input.project_id), funnel_id: firstString(input.funnelId, input.funnel_id), funnel_version: firstString(input.funnelVersion, input.funnelVersionId, input.funnel_version), ip_address: firstString(input.ipAddress, input.ip_address, transactionInfo.ipAddress, transactionInfo.ip_address), user_agent: firstString(input.userAgent, input.user_agent, attributionContext.userAgent), timezone: firstString(input.timezone, input.time_zone, progressAttributes.timezone, progressAttributes.time_zone, document.timezone, document.time_zone, attributionContext.timezone, attributionContext.time_zone), geo_city: firstString(input.geoCity, input.geo_city, progressAttributes.geo_city, progressAttributes.geoCity, document.geo_city, document.geoCity, asRecord(document.geo).city, attributionContext.geo_city, attributionContext.geoCity, attributionContext.cityName, attributionContext.city), geo_country: firstString(input.geoCountry, input.geo_country, progressAttributes.geo_country, progressAttributes.geoCountry, document.geo_country, document.geoCountry, asRecord(document.geo).country, attributionContext.geo_country, attributionContext.geoCountry, attributionContext.countryName, attributionContext.countryCode, attributionContext.country), transaction_id: firstString(input.transactionId, input.transaction_id), url: options.includeUrl
138
+ ? sanitizePurchaseUrl(firstString(input.url, currentBrowserPurchaseUrl()))
139
+ : undefined }));
79
140
  };
80
141
  export const buildBrowserPurchaseAnalyticsAttributes = (input = {}) => {
81
142
  return buildPurchaseAnalyticsAttributes(input, { includeUrl: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/analytics",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",