@funnelsgrove/analytics 0.1.9 → 0.1.10

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;
@@ -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) => {
@@ -109,14 +120,35 @@ export const buildGoogleTagHeadScripts = () => {
109
120
  : []),
110
121
  ];
111
122
  };
123
+ const toGoogleTagString = (value) => {
124
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
125
+ };
126
+ const toGoogleTagNumber = (value) => {
127
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
128
+ };
129
+ const buildGoogleTagItem = (parameters) => {
130
+ const itemId = toGoogleTagString(parameters.provider_plan_id) || toGoogleTagString(parameters.plan_id);
131
+ if (!itemId) {
132
+ return undefined;
133
+ }
134
+ return {
135
+ item_id: itemId,
136
+ item_name: toGoogleTagString(parameters.plan_id) || itemId,
137
+ price: toGoogleTagNumber(parameters.value),
138
+ quantity: 1,
139
+ };
140
+ };
112
141
  export const mapAnalyticsEventToGoogleTagEvent = (event) => {
113
142
  var _a;
114
143
  switch (event.eventType) {
115
- case 'checkout_completed':
144
+ case 'checkout_started': {
145
+ const _b = buildBrowserPurchaseAnalyticsAttributes((_a = event.metadata) !== null && _a !== void 0 ? _a : {}), { transaction_id: _transactionId } = _b, baseParameters = __rest(_b, ["transaction_id"]);
146
+ const item = buildGoogleTagItem(baseParameters);
116
147
  return {
117
- eventName: 'purchase',
118
- parameters: sanitizeGoogleTagParameters(buildBrowserPurchaseAnalyticsAttributes(Object.assign(Object.assign({}, ((_a = event.metadata) !== null && _a !== void 0 ? _a : {})), { transactionId: event.eventId }))),
148
+ eventName: 'begin_checkout',
149
+ parameters: sanitizeGoogleTagParameters(Object.assign(Object.assign({}, baseParameters), (item ? { items: [item] } : {}))),
119
150
  };
151
+ }
120
152
  default:
121
153
  return null;
122
154
  }
@@ -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.10",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",