ninetwo-user-tracking 1.0.12 → 1.0.14

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.
package/dist/index.js CHANGED
@@ -33,32 +33,66 @@ var import_react3 = require("react");
33
33
  var import_react = require("react");
34
34
 
35
35
  // src/utils/gtm.ts
36
- var pushToDataLayer = (props) => {
36
+ var ATTRIBUTION_KEYS = [
37
+ "utm_source",
38
+ "utm_medium",
39
+ "utm_campaign",
40
+ "utm_term",
41
+ "utm_content",
42
+ "gclid",
43
+ // Google Ads ID
44
+ "fbclid",
45
+ // Facebook Click ID
46
+ "ttclid"
47
+ // TikTok Click ID
48
+ ];
49
+ var captureAttribution = () => {
37
50
  if (typeof window === "undefined")
38
51
  return;
39
- const { event, category, label, type, ...rest } = props;
40
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
41
- const params = {
42
- event_category: category,
43
- event_label: label,
44
- event_type: type,
45
- interaction_time: timestamp,
46
- ...rest
47
- // permite enviar dados extras
48
- };
49
- if (typeof window.gtag === "function") {
50
- try {
51
- window.gtag("event", event, params);
52
- return;
53
- } catch (err) {
54
- console.warn("[NineTwo Tracking] gtag falhou, fallback para dataLayer", err);
52
+ const urlParams = new URLSearchParams(window.location.search);
53
+ let hasNewData = false;
54
+ ATTRIBUTION_KEYS.forEach((key) => {
55
+ const value = urlParams.get(key);
56
+ if (value) {
57
+ sessionStorage.setItem(`nt_attr_${key}`, value);
58
+ hasNewData = true;
59
+ }
60
+ });
61
+ if (!sessionStorage.getItem("nt_attr_utm_source") && document.referrer) {
62
+ const referrerUrl = new URL(document.referrer);
63
+ if (referrerUrl.hostname !== window.location.hostname) {
64
+ sessionStorage.setItem("nt_attr_utm_source", "referral");
65
+ sessionStorage.setItem("nt_attr_utm_medium", referrerUrl.hostname);
55
66
  }
56
67
  }
57
- window.dataLayer = window.dataLayer || [];
58
- window.dataLayer.push({
59
- event,
60
- ...params
68
+ };
69
+ var getPersistedAttribution = () => {
70
+ if (typeof window === "undefined")
71
+ return {};
72
+ const attributionData = {};
73
+ ATTRIBUTION_KEYS.forEach((key) => {
74
+ const val = sessionStorage.getItem(`nt_attr_${key}`);
75
+ if (val)
76
+ attributionData[key] = val;
61
77
  });
78
+ return attributionData;
79
+ };
80
+ var pushToDataLayer = (props) => {
81
+ if (typeof window === "undefined")
82
+ return;
83
+ const dataLayer = window.dataLayer || [];
84
+ const payload = {
85
+ ...getPersistedAttribution(),
86
+ // <--- A MÁGICA ACONTECE AQUI
87
+ event: props.event,
88
+ event_category: props.category,
89
+ event_label: props.label,
90
+ event_type: props.type,
91
+ interaction_time: (/* @__PURE__ */ new Date()).toISOString(),
92
+ ...props
93
+ // Permite sobrescrever se necessário
94
+ };
95
+ dataLayer.push(payload);
62
96
  };
63
97
 
64
98
  // src/hooks/useAutoTrackClick.ts
@@ -133,79 +167,46 @@ var TrackingProvider = ({
133
167
  useAutoTrackClick(true);
134
168
  useAutoTrackSubmit(true);
135
169
  (0, import_react3.useEffect)(() => {
136
- if (!gtmId || typeof window === "undefined") {
137
- if (debug && !gtmId) {
138
- console.warn("[NineTwo Tracking] Nenhum ID fornecido.");
170
+ captureAttribution();
171
+ if (debug) {
172
+ const source = typeof sessionStorage !== "undefined" ? sessionStorage.getItem("nt_attr_utm_source") : null;
173
+ if (source) {
174
+ console.log(`[NineTwo Tracking] \u{1F517} Origem capturada: ${source}`);
139
175
  }
140
- return;
141
176
  }
142
- const isGA4 = gtmId.startsWith("G-");
143
- const isGTM = gtmId.startsWith("GTM-");
144
- if (!isGA4 && !isGTM) {
145
- console.warn("[NineTwo Tracking] ID inv\xE1lido:", gtmId);
177
+ }, [debug]);
178
+ (0, import_react3.useEffect)(() => {
179
+ if (typeof window === "undefined")
180
+ return;
181
+ if (!gtmId) {
182
+ if (debug)
183
+ console.warn("[NineTwo Tracking] \u26A0\uFE0F GTM ID n\xE3o fornecido.");
146
184
  return;
147
185
  }
148
- const existing = document.querySelector(
149
- `script[data-ninetwo-tracking="${gtmId}"]`
150
- );
151
- if (existing) {
152
- if (debug) {
153
- console.log("[NineTwo Tracking] Script j\xE1 carregado:", gtmId);
154
- }
186
+ const scriptId = "ninetwo-gtm-script";
187
+ if (document.getElementById(scriptId)) {
188
+ if (debug)
189
+ console.log("[NineTwo Tracking] \u2139\uFE0F Script GTM j\xE1 existente. Ignorando reinje\xE7\xE3o.");
155
190
  return;
156
191
  }
157
192
  window.dataLayer = window.dataLayer || [];
158
- if (isGA4) {
159
- if (debug) {
160
- console.log("[NineTwo Tracking] Inicializando GA4:", gtmId);
161
- }
162
- const gtagScript = document.createElement("script");
163
- gtagScript.async = true;
164
- gtagScript.src = `https://www.googletagmanager.com/gtag/js?id=${gtmId}`;
165
- gtagScript.setAttribute("data-ninetwo-tracking", gtmId);
166
- gtagScript.onload = () => {
167
- if (debug) {
168
- console.log("[NineTwo Tracking] gtag.js carregado com sucesso");
169
- }
170
- };
171
- gtagScript.onerror = () => {
172
- console.error("[NineTwo Tracking] Erro ao carregar gtag.js");
173
- };
174
- document.head.appendChild(gtagScript);
175
- const inlineScript = document.createElement("script");
176
- inlineScript.setAttribute("data-ninetwo-tracking", `${gtmId}-inline`);
177
- inlineScript.innerHTML = `
178
- window.dataLayer = window.dataLayer || [];
179
- function gtag(){dataLayer.push(arguments);}
180
- gtag('js', new Date());
181
- gtag('config', '${gtmId}', {
182
- send_page_view: true
183
- });
184
- `;
185
- document.head.appendChild(inlineScript);
186
- }
187
- if (isGTM) {
188
- if (debug) {
189
- console.log("[NineTwo Tracking] Inicializando GTM:", gtmId);
190
- }
191
- window.dataLayer.push({
192
- "gtm.start": (/* @__PURE__ */ new Date()).getTime(),
193
- event: "gtm.js"
194
- });
195
- const gtmScript = document.createElement("script");
196
- gtmScript.async = true;
197
- gtmScript.src = `https://www.googletagmanager.com/gtm.js?id=${gtmId}`;
198
- gtmScript.setAttribute("data-ninetwo-tracking", gtmId);
199
- gtmScript.onload = () => {
200
- if (debug) {
201
- console.log("[NineTwo Tracking] GTM carregado com sucesso");
202
- }
203
- };
204
- gtmScript.onerror = () => {
205
- console.error("[NineTwo Tracking] Erro ao carregar GTM");
206
- };
207
- document.head.appendChild(gtmScript);
208
- }
193
+ window.dataLayer.push({
194
+ "gtm.start": (/* @__PURE__ */ new Date()).getTime(),
195
+ event: "gtm.js"
196
+ });
197
+ const script = document.createElement("script");
198
+ script.id = scriptId;
199
+ script.async = true;
200
+ script.src = `https://www.googletagmanager.com/gtm.js?id=${gtmId}`;
201
+ script.onload = () => {
202
+ if (debug)
203
+ console.log(`[NineTwo Tracking] \u2705 GTM carregado com sucesso! (${gtmId})`);
204
+ };
205
+ script.onerror = () => {
206
+ if (debug)
207
+ console.error("[NineTwo Tracking] \u274C Erro ao carregar script do GTM. Verifique AdBlockers.");
208
+ };
209
+ document.head.appendChild(script);
209
210
  }, [gtmId, debug]);
210
211
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
211
212
  };
@@ -245,7 +246,7 @@ var TrackView = ({
245
246
  if (!hasTriggeredRead) {
246
247
  timerRef.current = window.setTimeout(() => {
247
248
  pushToDataLayer({
248
- event: `${eventName}_read_confirmation`,
249
+ event: `read_confirmation`,
249
250
  category,
250
251
  label,
251
252
  type: "read_confirmation"
package/dist/index.mjs CHANGED
@@ -5,32 +5,66 @@ import { useEffect as useEffect3 } from "react";
5
5
  import { useEffect } from "react";
6
6
 
7
7
  // src/utils/gtm.ts
8
- var pushToDataLayer = (props) => {
8
+ var ATTRIBUTION_KEYS = [
9
+ "utm_source",
10
+ "utm_medium",
11
+ "utm_campaign",
12
+ "utm_term",
13
+ "utm_content",
14
+ "gclid",
15
+ // Google Ads ID
16
+ "fbclid",
17
+ // Facebook Click ID
18
+ "ttclid"
19
+ // TikTok Click ID
20
+ ];
21
+ var captureAttribution = () => {
9
22
  if (typeof window === "undefined")
10
23
  return;
11
- const { event, category, label, type, ...rest } = props;
12
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
13
- const params = {
14
- event_category: category,
15
- event_label: label,
16
- event_type: type,
17
- interaction_time: timestamp,
18
- ...rest
19
- // permite enviar dados extras
20
- };
21
- if (typeof window.gtag === "function") {
22
- try {
23
- window.gtag("event", event, params);
24
- return;
25
- } catch (err) {
26
- console.warn("[NineTwo Tracking] gtag falhou, fallback para dataLayer", err);
24
+ const urlParams = new URLSearchParams(window.location.search);
25
+ let hasNewData = false;
26
+ ATTRIBUTION_KEYS.forEach((key) => {
27
+ const value = urlParams.get(key);
28
+ if (value) {
29
+ sessionStorage.setItem(`nt_attr_${key}`, value);
30
+ hasNewData = true;
31
+ }
32
+ });
33
+ if (!sessionStorage.getItem("nt_attr_utm_source") && document.referrer) {
34
+ const referrerUrl = new URL(document.referrer);
35
+ if (referrerUrl.hostname !== window.location.hostname) {
36
+ sessionStorage.setItem("nt_attr_utm_source", "referral");
37
+ sessionStorage.setItem("nt_attr_utm_medium", referrerUrl.hostname);
27
38
  }
28
39
  }
29
- window.dataLayer = window.dataLayer || [];
30
- window.dataLayer.push({
31
- event,
32
- ...params
40
+ };
41
+ var getPersistedAttribution = () => {
42
+ if (typeof window === "undefined")
43
+ return {};
44
+ const attributionData = {};
45
+ ATTRIBUTION_KEYS.forEach((key) => {
46
+ const val = sessionStorage.getItem(`nt_attr_${key}`);
47
+ if (val)
48
+ attributionData[key] = val;
33
49
  });
50
+ return attributionData;
51
+ };
52
+ var pushToDataLayer = (props) => {
53
+ if (typeof window === "undefined")
54
+ return;
55
+ const dataLayer = window.dataLayer || [];
56
+ const payload = {
57
+ ...getPersistedAttribution(),
58
+ // <--- A MÁGICA ACONTECE AQUI
59
+ event: props.event,
60
+ event_category: props.category,
61
+ event_label: props.label,
62
+ event_type: props.type,
63
+ interaction_time: (/* @__PURE__ */ new Date()).toISOString(),
64
+ ...props
65
+ // Permite sobrescrever se necessário
66
+ };
67
+ dataLayer.push(payload);
34
68
  };
35
69
 
36
70
  // src/hooks/useAutoTrackClick.ts
@@ -105,79 +139,46 @@ var TrackingProvider = ({
105
139
  useAutoTrackClick(true);
106
140
  useAutoTrackSubmit(true);
107
141
  useEffect3(() => {
108
- if (!gtmId || typeof window === "undefined") {
109
- if (debug && !gtmId) {
110
- console.warn("[NineTwo Tracking] Nenhum ID fornecido.");
142
+ captureAttribution();
143
+ if (debug) {
144
+ const source = typeof sessionStorage !== "undefined" ? sessionStorage.getItem("nt_attr_utm_source") : null;
145
+ if (source) {
146
+ console.log(`[NineTwo Tracking] \u{1F517} Origem capturada: ${source}`);
111
147
  }
112
- return;
113
148
  }
114
- const isGA4 = gtmId.startsWith("G-");
115
- const isGTM = gtmId.startsWith("GTM-");
116
- if (!isGA4 && !isGTM) {
117
- console.warn("[NineTwo Tracking] ID inv\xE1lido:", gtmId);
149
+ }, [debug]);
150
+ useEffect3(() => {
151
+ if (typeof window === "undefined")
152
+ return;
153
+ if (!gtmId) {
154
+ if (debug)
155
+ console.warn("[NineTwo Tracking] \u26A0\uFE0F GTM ID n\xE3o fornecido.");
118
156
  return;
119
157
  }
120
- const existing = document.querySelector(
121
- `script[data-ninetwo-tracking="${gtmId}"]`
122
- );
123
- if (existing) {
124
- if (debug) {
125
- console.log("[NineTwo Tracking] Script j\xE1 carregado:", gtmId);
126
- }
158
+ const scriptId = "ninetwo-gtm-script";
159
+ if (document.getElementById(scriptId)) {
160
+ if (debug)
161
+ console.log("[NineTwo Tracking] \u2139\uFE0F Script GTM j\xE1 existente. Ignorando reinje\xE7\xE3o.");
127
162
  return;
128
163
  }
129
164
  window.dataLayer = window.dataLayer || [];
130
- if (isGA4) {
131
- if (debug) {
132
- console.log("[NineTwo Tracking] Inicializando GA4:", gtmId);
133
- }
134
- const gtagScript = document.createElement("script");
135
- gtagScript.async = true;
136
- gtagScript.src = `https://www.googletagmanager.com/gtag/js?id=${gtmId}`;
137
- gtagScript.setAttribute("data-ninetwo-tracking", gtmId);
138
- gtagScript.onload = () => {
139
- if (debug) {
140
- console.log("[NineTwo Tracking] gtag.js carregado com sucesso");
141
- }
142
- };
143
- gtagScript.onerror = () => {
144
- console.error("[NineTwo Tracking] Erro ao carregar gtag.js");
145
- };
146
- document.head.appendChild(gtagScript);
147
- const inlineScript = document.createElement("script");
148
- inlineScript.setAttribute("data-ninetwo-tracking", `${gtmId}-inline`);
149
- inlineScript.innerHTML = `
150
- window.dataLayer = window.dataLayer || [];
151
- function gtag(){dataLayer.push(arguments);}
152
- gtag('js', new Date());
153
- gtag('config', '${gtmId}', {
154
- send_page_view: true
155
- });
156
- `;
157
- document.head.appendChild(inlineScript);
158
- }
159
- if (isGTM) {
160
- if (debug) {
161
- console.log("[NineTwo Tracking] Inicializando GTM:", gtmId);
162
- }
163
- window.dataLayer.push({
164
- "gtm.start": (/* @__PURE__ */ new Date()).getTime(),
165
- event: "gtm.js"
166
- });
167
- const gtmScript = document.createElement("script");
168
- gtmScript.async = true;
169
- gtmScript.src = `https://www.googletagmanager.com/gtm.js?id=${gtmId}`;
170
- gtmScript.setAttribute("data-ninetwo-tracking", gtmId);
171
- gtmScript.onload = () => {
172
- if (debug) {
173
- console.log("[NineTwo Tracking] GTM carregado com sucesso");
174
- }
175
- };
176
- gtmScript.onerror = () => {
177
- console.error("[NineTwo Tracking] Erro ao carregar GTM");
178
- };
179
- document.head.appendChild(gtmScript);
180
- }
165
+ window.dataLayer.push({
166
+ "gtm.start": (/* @__PURE__ */ new Date()).getTime(),
167
+ event: "gtm.js"
168
+ });
169
+ const script = document.createElement("script");
170
+ script.id = scriptId;
171
+ script.async = true;
172
+ script.src = `https://www.googletagmanager.com/gtm.js?id=${gtmId}`;
173
+ script.onload = () => {
174
+ if (debug)
175
+ console.log(`[NineTwo Tracking] \u2705 GTM carregado com sucesso! (${gtmId})`);
176
+ };
177
+ script.onerror = () => {
178
+ if (debug)
179
+ console.error("[NineTwo Tracking] \u274C Erro ao carregar script do GTM. Verifique AdBlockers.");
180
+ };
181
+ document.head.appendChild(script);
181
182
  }, [gtmId, debug]);
182
183
  return /* @__PURE__ */ jsx(Fragment, { children });
183
184
  };
@@ -217,7 +218,7 @@ var TrackView = ({
217
218
  if (!hasTriggeredRead) {
218
219
  timerRef.current = window.setTimeout(() => {
219
220
  pushToDataLayer({
220
- event: `${eventName}_read_confirmation`,
221
+ event: `read_confirmation`,
221
222
  category,
222
223
  label,
223
224
  type: "read_confirmation"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ninetwo-user-tracking",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "description": "User tracking abstraction for React/Nextjs with GTM",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",