@funnelsgrove/analytics 0.1.9 → 0.1.11

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.
@@ -1,4 +1,4 @@
1
- type GoogleTagEventName = 'purchase';
1
+ type GoogleTagEventName = 'begin_checkout' | 'purchase';
2
2
  export type GoogleTagHeadScript = {
3
3
  id: string;
4
4
  src?: string;
@@ -13,6 +13,13 @@ export type AnalyticsEventForGoogleTag = {
13
13
  eventType: string;
14
14
  metadata?: Record<string, unknown>;
15
15
  };
16
+ type GoogleTagMetaPixelQueue = ((...args: unknown[]) => void) & {
17
+ callMethod?: (...args: unknown[]) => void;
18
+ loaded?: boolean;
19
+ push?: GoogleTagMetaPixelQueue;
20
+ queue?: unknown[][];
21
+ version?: string;
22
+ };
16
23
  declare global {
17
24
  interface Window {
18
25
  __funnelsgroveGoogleTagHeadReady?: boolean;
@@ -20,7 +27,9 @@ declare global {
20
27
  __funnelsgroveGoogleTagServiceReady?: boolean;
21
28
  __funnelsgroveSanitizeGoogleTagUrl?: (value: string) => string;
22
29
  dataLayer?: unknown[];
30
+ fbq?: GoogleTagMetaPixelQueue;
23
31
  gtag?: (...args: unknown[]) => void;
32
+ _fbq?: GoogleTagMetaPixelQueue;
24
33
  }
25
34
  }
26
35
  export declare const buildGoogleTagHeadScripts: () => GoogleTagHeadScript[];
@@ -32,6 +41,7 @@ export declare class GoogleTagService {
32
41
  private isConfigured;
33
42
  private ensureInitialized;
34
43
  private ensureDataLayer;
44
+ private ensureMetaPixelQueue;
35
45
  private installScript;
36
46
  }
37
47
  export declare const googleTagService: GoogleTagService;
@@ -1,3 +1,14 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
1
12
  import { GOOGLE_ANALYTICS_ID, GOOGLE_TAG_ENABLED, GOOGLE_TAG_EVENT_TARGET, GOOGLE_TAG_MANAGER_ID, } from './runtime-api.config.js';
2
13
  import { buildBrowserPurchaseAnalyticsAttributes } from './purchase-attributes.service.js';
3
14
  const normalizeEventTarget = (value) => {
@@ -82,6 +93,7 @@ export const buildGoogleTagHeadScripts = () => {
82
93
  : []),
83
94
  ...(GOOGLE_TAG_MANAGER_ID
84
95
  ? [
96
+ 'if (!window.fbq) { window.fbq = function(){ window.fbq.callMethod ? window.fbq.callMethod.apply(window.fbq, arguments) : window.fbq.queue.push(arguments); }; window._fbq = window._fbq || window.fbq; window.fbq.push = window.fbq; window.fbq.loaded = true; window.fbq.version = "2.0"; window.fbq.queue = []; }',
85
97
  'window.dataLayer.push({"gtm.start": Date.now(), event: "gtm.js"});',
86
98
  ]
87
99
  : []),
@@ -109,14 +121,35 @@ export const buildGoogleTagHeadScripts = () => {
109
121
  : []),
110
122
  ];
111
123
  };
124
+ const toGoogleTagString = (value) => {
125
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
126
+ };
127
+ const toGoogleTagNumber = (value) => {
128
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
129
+ };
130
+ const buildGoogleTagItem = (parameters) => {
131
+ const itemId = toGoogleTagString(parameters.provider_plan_id) || toGoogleTagString(parameters.plan_id);
132
+ if (!itemId) {
133
+ return undefined;
134
+ }
135
+ return {
136
+ item_id: itemId,
137
+ item_name: toGoogleTagString(parameters.plan_id) || itemId,
138
+ price: toGoogleTagNumber(parameters.value),
139
+ quantity: 1,
140
+ };
141
+ };
112
142
  export const mapAnalyticsEventToGoogleTagEvent = (event) => {
113
143
  var _a;
114
144
  switch (event.eventType) {
115
- case 'checkout_completed':
145
+ case 'checkout_started': {
146
+ const _b = buildBrowserPurchaseAnalyticsAttributes((_a = event.metadata) !== null && _a !== void 0 ? _a : {}), { transaction_id: _transactionId } = _b, baseParameters = __rest(_b, ["transaction_id"]);
147
+ const item = buildGoogleTagItem(baseParameters);
116
148
  return {
117
- eventName: 'purchase',
118
- parameters: sanitizeGoogleTagParameters(buildBrowserPurchaseAnalyticsAttributes(Object.assign(Object.assign({}, ((_a = event.metadata) !== null && _a !== void 0 ? _a : {})), { transactionId: event.eventId }))),
149
+ eventName: 'begin_checkout',
150
+ parameters: sanitizeGoogleTagParameters(Object.assign(Object.assign({}, baseParameters), (item ? { items: [item] } : {}))),
119
151
  };
152
+ }
120
153
  default:
121
154
  return null;
122
155
  }
@@ -170,6 +203,7 @@ export class GoogleTagService {
170
203
  });
171
204
  }
172
205
  if (GOOGLE_TAG_MANAGER_ID) {
206
+ this.ensureMetaPixelQueue();
173
207
  (_d = window.dataLayer) === null || _d === void 0 ? void 0 : _d.push({
174
208
  'gtm.start': Date.now(),
175
209
  event: 'gtm.js',
@@ -184,6 +218,25 @@ export class GoogleTagService {
184
218
  (_a = window.dataLayer) === null || _a === void 0 ? void 0 : _a.push(args);
185
219
  });
186
220
  }
221
+ ensureMetaPixelQueue() {
222
+ if (window.fbq) {
223
+ return;
224
+ }
225
+ const fbq = ((...args) => {
226
+ var _a;
227
+ if (fbq.callMethod) {
228
+ fbq.callMethod(...args);
229
+ return;
230
+ }
231
+ (_a = fbq.queue) === null || _a === void 0 ? void 0 : _a.push(args);
232
+ });
233
+ window._fbq = window._fbq || fbq;
234
+ fbq.push = fbq;
235
+ fbq.loaded = true;
236
+ fbq.version = '2.0';
237
+ fbq.queue = [];
238
+ window.fbq = fbq;
239
+ }
187
240
  installScript(src) {
188
241
  var _a;
189
242
  if (typeof document === 'undefined') {
@@ -11,15 +11,24 @@ export type AnalyticsEventForMetaPixel = {
11
11
  };
12
12
  declare global {
13
13
  interface Window {
14
- fbq?: (...args: unknown[]) => void;
14
+ fbq?: MetaPixelQueue;
15
+ _fbq?: MetaPixelQueue;
15
16
  }
16
17
  }
18
+ type MetaPixelQueue = ((...args: unknown[]) => void) & {
19
+ callMethod?: (...args: unknown[]) => void;
20
+ loaded?: boolean;
21
+ push?: MetaPixelQueue;
22
+ queue?: unknown[][];
23
+ version?: string;
24
+ };
17
25
  export declare const mapAnalyticsEventToMetaPixelEvent: (event: AnalyticsEventForMetaPixel) => MetaPixelTrackInput | null;
18
26
  export declare class MetaPixelService {
19
27
  private initialized;
20
28
  track(input: MetaPixelTrackInput): void;
21
29
  private isConfigured;
22
30
  private ensureInitialized;
31
+ private installQueue;
23
32
  private installScript;
24
33
  }
25
34
  export declare const metaPixelService: MetaPixelService;
@@ -73,19 +73,43 @@ export class MetaPixelService {
73
73
  return Boolean(META_PIXEL_ENABLED && META_PIXEL_ID && typeof window !== 'undefined');
74
74
  }
75
75
  ensureInitialized() {
76
- var _a, _b;
77
76
  if (this.initialized) {
78
77
  return;
79
78
  }
80
79
  this.initialized = true;
80
+ this.installQueue();
81
81
  this.installScript();
82
- (_a = window.fbq) === null || _a === void 0 ? void 0 : _a.call(window, 'init', META_PIXEL_ID);
83
- (_b = window.fbq) === null || _b === void 0 ? void 0 : _b.call(window, 'track', 'PageView');
82
+ const fbq = window.fbq;
83
+ fbq === null || fbq === void 0 ? void 0 : fbq('init', META_PIXEL_ID);
84
+ fbq === null || fbq === void 0 ? void 0 : fbq('track', 'PageView');
85
+ }
86
+ installQueue() {
87
+ if (window.fbq) {
88
+ return;
89
+ }
90
+ const fbq = ((...args) => {
91
+ var _a;
92
+ if (fbq.callMethod) {
93
+ fbq.callMethod(...args);
94
+ return;
95
+ }
96
+ (_a = fbq.queue) === null || _a === void 0 ? void 0 : _a.push(args);
97
+ });
98
+ window._fbq = window._fbq || fbq;
99
+ fbq.push = fbq;
100
+ fbq.loaded = true;
101
+ fbq.version = '2.0';
102
+ fbq.queue = [];
103
+ window.fbq = fbq;
84
104
  }
85
105
  installScript() {
106
+ var _a;
86
107
  if (typeof document === 'undefined') {
87
108
  return;
88
109
  }
110
+ if ((_a = document.querySelector) === null || _a === void 0 ? void 0 : _a.call(document, 'script[src="https://connect.facebook.net/en_US/fbevents.js"]')) {
111
+ return;
112
+ }
89
113
  const firstScript = document.getElementsByTagName('script')[0];
90
114
  const parent = firstScript === null || firstScript === void 0 ? void 0 : firstScript.parentNode;
91
115
  if (!parent) {
@@ -8,6 +8,55 @@ const DEFAULT_OPTIONS = {
8
8
  flushIntervalMs: 1500,
9
9
  };
10
10
  const POSTHOG_BATCH_ENDPOINT = '/batch/';
11
+ const DEFAULT_FUNNEL_DOMAIN_SIGNAL = 'funnelsgrove';
12
+ const normalizeEnvironment = (value) => {
13
+ if (typeof value !== 'string') {
14
+ return null;
15
+ }
16
+ const normalized = value.trim().toLowerCase();
17
+ if (normalized === 'test') {
18
+ return 'test';
19
+ }
20
+ if (normalized === 'live' || normalized === 'prod' || normalized === 'production') {
21
+ return 'live';
22
+ }
23
+ return null;
24
+ };
25
+ const readCookieValue = (name) => {
26
+ var _a, _b;
27
+ if (!canUseDom() || typeof document === 'undefined') {
28
+ return null;
29
+ }
30
+ return (((_b = (_a = document.cookie) === null || _a === void 0 ? void 0 : _a.split(';').map((part) => part.trim()).find((part) => part.startsWith(`${name}=`))) === null || _b === void 0 ? void 0 : _b.slice(name.length + 1)) || null);
31
+ };
32
+ const resolveAnalyticsEnvironment = () => {
33
+ var _a, _b, _c, _d;
34
+ if (!canUseDom()) {
35
+ return 'live';
36
+ }
37
+ try {
38
+ const queryMode = normalizeEnvironment(new URLSearchParams(((_a = window.location) === null || _a === void 0 ? void 0 : _a.search) || '').get('mode'));
39
+ if (queryMode) {
40
+ return queryMode;
41
+ }
42
+ const cookieMode = normalizeEnvironment(readCookieValue('funnel-mode'));
43
+ if (cookieMode) {
44
+ return cookieMode;
45
+ }
46
+ const hostname = ((_c = (_b = window.location) === null || _b === void 0 ? void 0 : _b.hostname) === null || _c === void 0 ? void 0 : _c.trim().toLowerCase()) || '';
47
+ if (hostname.includes(DEFAULT_FUNNEL_DOMAIN_SIGNAL)) {
48
+ return 'test';
49
+ }
50
+ const storageMode = normalizeEnvironment((_d = window.localStorage) === null || _d === void 0 ? void 0 : _d.getItem('funnel-mode'));
51
+ if (storageMode) {
52
+ return storageMode;
53
+ }
54
+ }
55
+ catch (_e) {
56
+ return 'live';
57
+ }
58
+ return 'live';
59
+ };
11
60
  const asRecord = (value) => {
12
61
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
13
62
  return {};
@@ -120,7 +169,7 @@ export class PublicAnalyticsSdkService {
120
169
  user_id: userId,
121
170
  email: asString(input.email) || undefined,
122
171
  fullName: asString(input.fullName) || undefined,
123
- metadata: asRecord(input.metadata),
172
+ metadata: Object.assign({ environment: resolveAnalyticsEnvironment() }, asRecord(input.metadata)),
124
173
  }),
125
174
  });
126
175
  if (!response.ok) {
@@ -402,7 +451,7 @@ export class PublicAnalyticsSdkService {
402
451
  event: toPostHogEventName(event.eventType),
403
452
  properties: buildDefinedRecord(Object.assign(Object.assign({ distinct_id: this.ensureUserId(), $groups: {
404
453
  project: PROJECT_ID,
405
- }, $insert_id: event.eventId, project_id: PROJECT_ID, funnel_id: FUNNEL_ID || undefined, funnel_version_id: FUNNEL_VERSION_ID || undefined, step_id: event.stepId || undefined, step_name: event.stepName || undefined, started_at: event.startedAt || undefined, ended_at: event.endedAt || undefined, duration_ms: (_a = event.durationMs) !== null && _a !== void 0 ? _a : undefined, engagement_threshold_ms: (_b = event.engagementThresholdMs) !== null && _b !== void 0 ? _b : undefined, 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 })),
454
+ }, $insert_id: event.eventId, project_id: PROJECT_ID, funnel_id: FUNNEL_ID || undefined, funnel_version_id: FUNNEL_VERSION_ID || undefined, environment: resolveAnalyticsEnvironment(), step_id: event.stepId || undefined, step_name: event.stepName || undefined, started_at: event.startedAt || undefined, ended_at: event.endedAt || undefined, duration_ms: (_a = event.durationMs) !== null && _a !== void 0 ? _a : undefined, engagement_threshold_ms: (_b = event.engagementThresholdMs) !== null && _b !== void 0 ? _b : undefined, 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 })),
406
455
  timestamp: event.occurredAt,
407
456
  });
408
457
  });
@@ -1,16 +1,26 @@
1
1
  export type PurchaseAnalyticsAttributesInput = {
2
2
  amountCents?: unknown;
3
3
  attribution?: unknown;
4
+ checkoutSessionId?: unknown;
5
+ checkout_session_id?: unknown;
4
6
  couponId?: unknown;
5
7
  currency?: unknown;
6
8
  environment?: unknown;
9
+ fallbackTransactionId?: unknown;
10
+ fallback_transaction_id?: unknown;
7
11
  funnelId?: unknown;
8
12
  funnelUserDocument?: unknown;
9
13
  funnelVersion?: unknown;
10
14
  funnelVersionId?: unknown;
15
+ gaClientId?: unknown;
16
+ ga_client_id?: unknown;
11
17
  geoCity?: unknown;
12
18
  geoCountry?: unknown;
19
+ googleAnalyticsClientId?: unknown;
20
+ google_analytics_client_id?: unknown;
13
21
  ipAddress?: unknown;
22
+ paymentIntentId?: unknown;
23
+ payment_intent_id?: unknown;
14
24
  planId?: unknown;
15
25
  projectId?: unknown;
16
26
  providerPlanId?: unknown;
@@ -23,6 +33,7 @@ export type PurchaseAnalyticsAttributesInput = {
23
33
  };
24
34
  export declare const sanitizePurchaseUrl: (value: unknown) => string | undefined;
25
35
  export declare const currentBrowserPurchaseUrl: () => string | undefined;
36
+ export declare const currentGoogleAnalyticsClientId: () => string | undefined;
26
37
  export declare const buildPurchaseAnalyticsAttributes: (input?: PurchaseAnalyticsAttributesInput & Record<string, unknown>, options?: {
27
38
  includeUrl?: boolean;
28
39
  }) => Record<string, unknown>;
@@ -125,6 +125,36 @@ export const currentBrowserPurchaseUrl = () => {
125
125
  }
126
126
  return sanitizePurchaseUrl((_a = window.location) === null || _a === void 0 ? void 0 : _a.href);
127
127
  };
128
+ const readBrowserCookie = (name) => {
129
+ if (typeof document === 'undefined') {
130
+ return undefined;
131
+ }
132
+ const prefix = `${name}=`;
133
+ const cookie = document.cookie
134
+ .split(';')
135
+ .map((value) => value.trim())
136
+ .find((value) => value.startsWith(prefix));
137
+ if (!cookie) {
138
+ return undefined;
139
+ }
140
+ try {
141
+ return decodeURIComponent(cookie.slice(prefix.length));
142
+ }
143
+ catch (_a) {
144
+ return cookie.slice(prefix.length);
145
+ }
146
+ };
147
+ export const currentGoogleAnalyticsClientId = () => {
148
+ const gaCookie = readBrowserCookie('_ga');
149
+ if (!gaCookie) {
150
+ return undefined;
151
+ }
152
+ const parts = gaCookie.split('.');
153
+ if (parts.length >= 4 && /^GA\d+$/.test(parts[0])) {
154
+ return parts.slice(-2).join('.');
155
+ }
156
+ return gaCookie.trim() || undefined;
157
+ };
128
158
  export const buildPurchaseAnalyticsAttributes = (input = {}, options = {}) => {
129
159
  var _a, _b;
130
160
  const document = asRecord(input.funnelUserDocument);
@@ -134,7 +164,7 @@ export const buildPurchaseAnalyticsAttributes = (input = {}, options = {}) => {
134
164
  const transactionInfo = asRecord(document.transactionInfo);
135
165
  const amountCents = toNumber(input.amountCents);
136
166
  const value = (_b = toNumber(input.value)) !== null && _b !== void 0 ? _b : (amountCents === undefined ? undefined : amountCents / 100);
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
167
+ 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, input.checkoutSessionId, input.checkout_session_id, input.paymentIntentId, input.payment_intent_id, input.fallbackTransactionId, input.fallback_transaction_id), url: options.includeUrl
138
168
  ? sanitizePurchaseUrl(firstString(input.url, currentBrowserPurchaseUrl()))
139
169
  : undefined }));
140
170
  };
@@ -159,5 +189,5 @@ export const toStripeMetadata = (attributes) => {
159
189
  }));
160
190
  };
161
191
  export const buildStripePurchaseMetadata = (input = {}) => {
162
- return toStripeMetadata(buildPurchaseAnalyticsAttributes(input, { includeUrl: false }));
192
+ return toStripeMetadata(Object.assign(Object.assign({}, buildPurchaseAnalyticsAttributes(input, { includeUrl: false })), { ga_client_id: firstString(input.gaClientId, input.ga_client_id, input.googleAnalyticsClientId, input.google_analytics_client_id, currentGoogleAnalyticsClientId()) }));
163
193
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/analytics",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",