@funnelsgrove/analytics 0.21.0 → 0.22.0

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.
@@ -6,6 +6,7 @@ export type GoogleTagHeadScript = {
6
6
  };
7
7
  export type GoogleTagTrackInput = {
8
8
  eventName: GoogleTagEventName;
9
+ environment?: 'test' | 'live';
9
10
  parameters?: Record<string, unknown>;
10
11
  };
11
12
  export type AnalyticsEventForGoogleTag = {
@@ -1,5 +1,6 @@
1
1
  import { analyticsUrlSanitizerSource, sanitizeAnalyticsExport, sanitizeAnalyticsUrl } from './analytics-export.js';
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
+ 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, STRIPE_ACTIVE_MODE, } from './runtime-api.config.js';
3
+ import { isNonLiveAnalyticsRuntime, nonLiveBrowserLocationSource } from './non-live-runtime.js';
3
4
  import { buildBrowserPurchaseAnalyticsAttributes, buildPurchaseAnalyticsAttributes, currentBrowserPurchaseUrl, } from './purchase-attributes.service.js';
4
5
  const buildGoogleAnalyticsScriptSrc = (googleAnalyticsId) => `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(googleAnalyticsId)}`;
5
6
  const buildGoogleTagManagerScriptSrc = (googleTagManagerId) => `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(googleTagManagerId)}`;
@@ -62,10 +63,20 @@ const buildGoogleAdsConversionParameters = (parameters, sendTo) => {
62
63
  return sanitizeGoogleTagParameters(buildDefinedRecord(Object.assign(Object.assign({}, parameters), { send_to: sendTo })));
63
64
  };
64
65
  export const buildGoogleTagHeadScripts = () => {
65
- if (!GOOGLE_TAG_ENABLED || (!GOOGLE_TAG_SCRIPT_ID && !GOOGLE_TAG_MANAGER_ID)) {
66
+ if (!GOOGLE_TAG_ENABLED || (!GOOGLE_TAG_SCRIPT_ID && !GOOGLE_TAG_MANAGER_ID) || STRIPE_ACTIVE_MODE === 'test') {
66
67
  return [];
67
68
  }
69
+ const scripts = [
70
+ ...(GOOGLE_TAG_SCRIPT_ID
71
+ ? [{ id: 'funnelsgrove-google-analytics', src: buildGoogleAnalyticsScriptSrc(GOOGLE_TAG_SCRIPT_ID) }]
72
+ : []),
73
+ ...(GOOGLE_TAG_MANAGER_ID
74
+ ? [{ id: 'funnelsgrove-google-tag-manager', src: buildGoogleTagManagerScriptSrc(GOOGLE_TAG_MANAGER_ID) }]
75
+ : []),
76
+ ];
77
+ // Previews and test mode share the live build, so the browser decides before anything loads.
68
78
  const bootstrapLines = [
79
+ `if (!(${nonLiveBrowserLocationSource})()) {`,
69
80
  'window.dataLayer = window.dataLayer || [];',
70
81
  'window.gtag = window.gtag || function(){ window.dataLayer.push(arguments); };',
71
82
  `window.__funnelsgroveSanitizeGoogleTagUrl = ${analyticsUrlSanitizerSource};`,
@@ -83,28 +94,14 @@ export const buildGoogleTagHeadScripts = () => {
83
94
  'window.dataLayer.push({"gtm.start": Date.now(), event: "gtm.js"});',
84
95
  ]
85
96
  : []),
97
+ ...scripts.map((script) => `(function(s){ s.id = ${JSON.stringify(script.id)}; s.async = true; s.src = ${JSON.stringify(script.src)}; document.head.appendChild(s); })(document.createElement("script"));`),
98
+ '}',
86
99
  ];
87
100
  return [
88
101
  {
89
102
  id: 'funnelsgrove-google-tag-bootstrap',
90
103
  content: bootstrapLines.join('\n'),
91
104
  },
92
- ...(GOOGLE_TAG_SCRIPT_ID
93
- ? [
94
- {
95
- id: 'funnelsgrove-google-analytics',
96
- src: buildGoogleAnalyticsScriptSrc(GOOGLE_TAG_SCRIPT_ID),
97
- },
98
- ]
99
- : []),
100
- ...(GOOGLE_TAG_MANAGER_ID
101
- ? [
102
- {
103
- id: 'funnelsgrove-google-tag-manager',
104
- src: buildGoogleTagManagerScriptSrc(GOOGLE_TAG_MANAGER_ID),
105
- },
106
- ]
107
- : []),
108
105
  ];
109
106
  };
110
107
  export const mapAnalyticsEventToGoogleTagEvent = (event) => {
@@ -195,14 +192,14 @@ export class GoogleTagService {
195
192
  this.initialized = false;
196
193
  }
197
194
  initialize() {
198
- if (!this.isConfigured()) {
195
+ if (!this.isConfigured() || isNonLiveAnalyticsRuntime()) {
199
196
  return;
200
197
  }
201
198
  this.ensureInitialized();
202
199
  }
203
200
  track(input) {
204
201
  var _a, _b, _c;
205
- if (!this.isConfigured()) {
202
+ if (input.environment === 'test' || !this.isConfigured() || isNonLiveAnalyticsRuntime()) {
206
203
  return;
207
204
  }
208
205
  this.initialize();
@@ -1,5 +1,5 @@
1
- import { isSystemPreviewHostname } from '@funnelsgrove/runtime';
2
- import { META_LEAD_EVENT_NAME, META_PIXEL_ENABLED, META_PIXEL_ID, STRIPE_ACTIVE_MODE } from './runtime-api.config.js';
1
+ import { META_LEAD_EVENT_NAME, META_PIXEL_ENABLED, META_PIXEL_ID } from './runtime-api.config.js';
2
+ import { isNonLiveAnalyticsRuntime } from './non-live-runtime.js';
3
3
  import { buildPurchaseAnalyticsAttributes } from './purchase-attributes.service.js';
4
4
  const toNumber = (value) => {
5
5
  if (typeof value !== 'number' || !Number.isFinite(value)) {
@@ -23,27 +23,6 @@ const buildCommerceCustomData = (metadata = {}) => {
23
23
  }
24
24
  return customData;
25
25
  };
26
- const isNonLiveRuntime = () => {
27
- var _a, _b, _c, _d, _e, _f, _g, _h;
28
- if (STRIPE_ACTIVE_MODE === 'test') {
29
- return true;
30
- }
31
- try {
32
- const params = new URLSearchParams(((_a = window.location) === null || _a === void 0 ? void 0 : _a.search) || '');
33
- const hostname = ((_c = (_b = window.location) === null || _b === void 0 ? void 0 : _b.hostname) === null || _c === void 0 ? void 0 : _c.toLowerCase().replace(/\.+$/, '')) || '';
34
- const cookieMode = typeof document === 'undefined' ? undefined : (_e = (_d = document.cookie) === null || _d === void 0 ? void 0 : _d.split(';').map((part) => part.trim()).find((part) => part.startsWith('funnel-mode='))) === null || _e === void 0 ? void 0 : _e.slice('funnel-mode='.length);
35
- return params.get('previewFrame') === '1'
36
- || ((_f = params.get('mode')) === null || _f === void 0 ? void 0 : _f.trim().toLowerCase()) === 'test'
37
- || (cookieMode === null || cookieMode === void 0 ? void 0 : cookieMode.trim().toLowerCase()) === 'test'
38
- || ((_h = (_g = window.localStorage) === null || _g === void 0 ? void 0 : _g.getItem('funnel-mode')) === null || _h === void 0 ? void 0 : _h.trim().toLowerCase()) === 'test'
39
- || isSystemPreviewHostname(hostname)
40
- || hostname === 'preview.funnelsgrove.dev'
41
- || hostname.endsWith('.preview.funnelsgrove.dev');
42
- }
43
- catch (_j) {
44
- return true;
45
- }
46
- };
47
26
  export const mapAnalyticsEventToMetaPixelEvent = (event) => {
48
27
  switch (event.eventType) {
49
28
  case 'first_step_viewed':
@@ -82,7 +61,7 @@ export class MetaPixelService {
82
61
  }
83
62
  track(input) {
84
63
  var _a, _b;
85
- if (input.environment === 'test' || !this.isConfigured() || isNonLiveRuntime()) {
64
+ if (input.environment === 'test' || !this.isConfigured() || isNonLiveAnalyticsRuntime()) {
86
65
  return;
87
66
  }
88
67
  this.ensureInitialized();
@@ -0,0 +1,3 @@
1
+ export declare const nonLiveBrowserLocationSource: string;
2
+ /** Browser ad/analytics tags stay silent in previews, test mode and Stripe test deployments. */
3
+ export declare const isNonLiveAnalyticsRuntime: () => boolean;
@@ -0,0 +1,30 @@
1
+ import { STRIPE_ACTIVE_MODE } from './runtime-api.config.js';
2
+ // Keep this function self-contained: the Google tag head bootstrap embeds the same implementation.
3
+ // Preview hostnames mirror isSystemPreviewHostname from @funnelsgrove/runtime plus the preview suffix.
4
+ const isNonLiveBrowserLocation = () => {
5
+ var _a, _b, _c, _d, _e, _f, _g;
6
+ try {
7
+ const params = new URLSearchParams(((_a = window.location) === null || _a === void 0 ? void 0 : _a.search) || '');
8
+ const hostname = (((_b = window.location) === null || _b === void 0 ? void 0 : _b.hostname) || '').trim().toLowerCase().replace(/^\[|\]$/g, '').replace(/\.+$/, '');
9
+ const cookieMode = typeof document === 'undefined' ? undefined : (_d = (_c = document.cookie) === null || _c === void 0 ? void 0 : _c.split(';').map((part) => part.trim()).find((part) => part.startsWith('funnel-mode='))) === null || _d === void 0 ? void 0 : _d.slice('funnel-mode='.length);
10
+ const ipv4Loopback = /^127((?:\.\d{1,3}){3})$/.exec(hostname);
11
+ const mappedIpv4 = /^::ffff:([0-9a-f]{1,4}):[0-9a-f]{1,4}$/.exec(hostname);
12
+ const mappedIpv4High = mappedIpv4 ? Number.parseInt(mappedIpv4[1], 16) : 0;
13
+ return params.get('previewFrame') === '1'
14
+ || ((_e = params.get('mode')) === null || _e === void 0 ? void 0 : _e.trim().toLowerCase()) === 'test'
15
+ || (cookieMode === null || cookieMode === void 0 ? void 0 : cookieMode.trim().toLowerCase()) === 'test'
16
+ || ((_g = (_f = window.localStorage) === null || _f === void 0 ? void 0 : _f.getItem('funnel-mode')) === null || _g === void 0 ? void 0 : _g.trim().toLowerCase()) === 'test'
17
+ || hostname === 'localhost'
18
+ || hostname.endsWith('.localhost')
19
+ || hostname === '::1'
20
+ || Boolean(ipv4Loopback && ipv4Loopback[1].slice(1).split('.').every((octet) => Number(octet) <= 255))
21
+ || (mappedIpv4High >= 0x7f00 && mappedIpv4High <= 0x7fff)
22
+ || ['funnelsgrove.org', 'funnelsgrove.com', 'preview.funnelsgrove.dev'].some((domain) => hostname === domain || hostname.endsWith(`.${domain}`));
23
+ }
24
+ catch (_h) {
25
+ return true;
26
+ }
27
+ };
28
+ export const nonLiveBrowserLocationSource = isNonLiveBrowserLocation.toString();
29
+ /** Browser ad/analytics tags stay silent in previews, test mode and Stripe test deployments. */
30
+ export const isNonLiveAnalyticsRuntime = () => STRIPE_ACTIVE_MODE === 'test' || isNonLiveBrowserLocation();
@@ -269,7 +269,7 @@ export class PublicAnalyticsSdkService {
269
269
  });
270
270
  for (const googleTagEvent of googleTagEvents) {
271
271
  try {
272
- googleTagService.track(googleTagEvent);
272
+ googleTagService.track(Object.assign(Object.assign({}, googleTagEvent), { environment }));
273
273
  }
274
274
  catch (_b) {
275
275
  // Browser destinations are best effort and independent.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/analytics",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/The-Solid-Grove/funnelsgrove.git",