@fire-spark/analytics-ga4 0.17.3 → 0.19.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.
- package/README.md +14 -0
- package/dist/index.d.ts +42 -1
- package/dist/index.js +248 -49
- package/package.json +4 -3
package/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# @fire-spark/analytics-ga4
|
|
2
|
+
|
|
3
|
+
GA4 destination for `@fire-spark/analytics`: gtag.js on web, Firebase
|
|
4
|
+
`logEvent` in React Native.
|
|
5
|
+
|
|
6
|
+
```typescript
|
|
7
|
+
import { ga4 } from "@fire-spark/analytics-ga4";
|
|
8
|
+
|
|
9
|
+
ga4({ measurementId: "G-XXXXXXX" }); // web
|
|
10
|
+
ga4({ logEvent, setUserId, setUserProperties, setConsent }); // React Native
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Pass it to `adapters` in `configure()`. Options and behavior:
|
|
14
|
+
https://firespark.cloud/docs/guides/analytics/destinations#ga4
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,51 @@
|
|
|
1
1
|
import { AnalyticsAdapter } from "@fire-spark/analytics";
|
|
2
|
+
//#region src/firebase.d.ts
|
|
3
|
+
/** Returns why Firebase rejects the event name, or null when valid. */
|
|
4
|
+
declare const firebaseNameIssue: (name: string) => string | null;
|
|
5
|
+
//#endregion
|
|
2
6
|
//#region src/index.d.ts
|
|
3
7
|
type Ga4LogEvent = (name: string, params?: Record<string, unknown>) => Promise<void> | void;
|
|
8
|
+
type Ga4ConsentState = "granted" | "denied";
|
|
9
|
+
/** `gtag("consent", "default", …)`, sent before gtag.js loads. */
|
|
10
|
+
type Ga4ConsentDefaults = {
|
|
11
|
+
analytics_storage?: Ga4ConsentState;
|
|
12
|
+
ad_storage?: Ga4ConsentState;
|
|
13
|
+
ad_user_data?: Ga4ConsentState;
|
|
14
|
+
ad_personalization?: Ga4ConsentState;
|
|
15
|
+
functionality_storage?: Ga4ConsentState;
|
|
16
|
+
personalization_storage?: Ga4ConsentState;
|
|
17
|
+
security_storage?: Ga4ConsentState;
|
|
18
|
+
wait_for_update?: number;
|
|
19
|
+
region?: string[];
|
|
20
|
+
};
|
|
21
|
+
/** Firebase `setConsent` input (React Native). */
|
|
22
|
+
type Ga4FirebaseConsent = {
|
|
23
|
+
analytics_storage: boolean;
|
|
24
|
+
ad_storage: boolean;
|
|
25
|
+
ad_user_data: boolean;
|
|
26
|
+
ad_personalization: boolean;
|
|
27
|
+
};
|
|
4
28
|
type Ga4Options = {
|
|
29
|
+
/** Web: GA4 property. Events are sent with `send_to` this id. */
|
|
5
30
|
measurementId?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Web: params of `gtag("config", measurementId, config)`, for example
|
|
33
|
+
* `debug_mode`, `send_page_view` or `cookie_domain`.
|
|
34
|
+
*/
|
|
35
|
+
config?: Record<string, unknown>;
|
|
36
|
+
/** Web: consent mode defaults, set before the first `config`. */
|
|
37
|
+
consentDefaults?: Ga4ConsentDefaults;
|
|
38
|
+
/** React Native: Firebase `logEvent`. */
|
|
6
39
|
logEvent?: Ga4LogEvent;
|
|
40
|
+
/** React Native: Firebase `setUserId`. */
|
|
41
|
+
setUserId?: (id: string | null) => Promise<void> | void;
|
|
42
|
+
/** React Native: Firebase `setUserProperties`. */
|
|
43
|
+
setUserProperties?: (properties: Record<string, string | null>) => Promise<void> | void;
|
|
44
|
+
/** React Native: Firebase `setConsent`. */
|
|
45
|
+
setConsent?: (consent: Ga4FirebaseConsent) => Promise<void> | void;
|
|
46
|
+
/** Firebase limit warnings. Defaults to `console.warn`. */
|
|
47
|
+
onWarning?: (message: string) => void;
|
|
7
48
|
};
|
|
8
49
|
declare const ga4: (options?: Ga4Options) => AnalyticsAdapter;
|
|
9
50
|
//#endregion
|
|
10
|
-
export { Ga4LogEvent, Ga4Options, ga4 };
|
|
51
|
+
export { Ga4ConsentDefaults, Ga4ConsentState, Ga4FirebaseConsent, Ga4LogEvent, Ga4Options, firebaseNameIssue, ga4 };
|
package/dist/index.js
CHANGED
|
@@ -1,65 +1,264 @@
|
|
|
1
|
+
import { compactPayload, hasScript, loadScript } from "@fire-spark/analytics";
|
|
2
|
+
//#region src/firebase.ts
|
|
3
|
+
/** Event names Firebase Analytics reserves for automatic events. */
|
|
4
|
+
const RESERVED_EVENT_NAMES = /* @__PURE__ */ new Set([
|
|
5
|
+
"ad_activeview",
|
|
6
|
+
"ad_click",
|
|
7
|
+
"ad_exposure",
|
|
8
|
+
"ad_impression",
|
|
9
|
+
"ad_query",
|
|
10
|
+
"ad_reward",
|
|
11
|
+
"adunit_exposure",
|
|
12
|
+
"app_background",
|
|
13
|
+
"app_clear_data",
|
|
14
|
+
"app_exception",
|
|
15
|
+
"app_remove",
|
|
16
|
+
"app_store_refund",
|
|
17
|
+
"app_store_subscription_cancel",
|
|
18
|
+
"app_store_subscription_convert",
|
|
19
|
+
"app_store_subscription_renew",
|
|
20
|
+
"app_update",
|
|
21
|
+
"app_upgrade",
|
|
22
|
+
"dynamic_link_app_open",
|
|
23
|
+
"dynamic_link_app_update",
|
|
24
|
+
"dynamic_link_first_open",
|
|
25
|
+
"error",
|
|
26
|
+
"first_open",
|
|
27
|
+
"first_visit",
|
|
28
|
+
"in_app_purchase",
|
|
29
|
+
"notification_dismiss",
|
|
30
|
+
"notification_foreground",
|
|
31
|
+
"notification_open",
|
|
32
|
+
"notification_receive",
|
|
33
|
+
"os_update",
|
|
34
|
+
"session_start",
|
|
35
|
+
"session_start_with_rollout",
|
|
36
|
+
"user_engagement"
|
|
37
|
+
]);
|
|
38
|
+
const RESERVED_PREFIXES = [
|
|
39
|
+
"firebase_",
|
|
40
|
+
"google_",
|
|
41
|
+
"ga_"
|
|
42
|
+
];
|
|
43
|
+
const NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{0,39}$/;
|
|
44
|
+
const MAX_PARAMS = 25;
|
|
45
|
+
const MAX_PARAM_NAME = 40;
|
|
46
|
+
const MAX_STRING_VALUE = 100;
|
|
47
|
+
/** Returns why Firebase rejects the event name, or null when valid. */
|
|
48
|
+
const firebaseNameIssue = (name) => {
|
|
49
|
+
if (RESERVED_EVENT_NAMES.has(name)) return `"${name}" is reserved`;
|
|
50
|
+
const prefix = RESERVED_PREFIXES.find((item) => name.startsWith(item));
|
|
51
|
+
if (prefix) return `"${name}" uses the reserved prefix "${prefix}"`;
|
|
52
|
+
if (!NAME_PATTERN.test(name)) return `"${name}" must start with a letter and use up to 40 letters, digits or underscores`;
|
|
53
|
+
return null;
|
|
54
|
+
};
|
|
55
|
+
/** Limits Firebase applies by dropping or truncating params. */
|
|
56
|
+
const firebaseParamIssues = (params) => {
|
|
57
|
+
const issues = [];
|
|
58
|
+
const keys = Object.keys(params).filter((key) => key !== "items");
|
|
59
|
+
if (keys.length > MAX_PARAMS) {
|
|
60
|
+
const p1 = `has ${keys.length} params; Firebase keeps ${MAX_PARAMS}`;
|
|
61
|
+
issues.push(p1);
|
|
62
|
+
}
|
|
63
|
+
for (const key of keys) {
|
|
64
|
+
if (key.length > MAX_PARAM_NAME) issues.push(`param "${key}" is longer than ${MAX_PARAM_NAME}`);
|
|
65
|
+
const value = params[key];
|
|
66
|
+
if (typeof value === "string" && value.length > MAX_STRING_VALUE) {
|
|
67
|
+
const p1 = `is longer than ${MAX_STRING_VALUE} characters`;
|
|
68
|
+
issues.push(`param "${key}" value ${p1}; Firebase truncates it`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return issues;
|
|
72
|
+
};
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/gtag.ts
|
|
75
|
+
const GTAG_ORIGIN = "https://www.googletagmanager.com/gtag/js";
|
|
76
|
+
const SCRIPT_ID = "firespark-ga4-gtag";
|
|
77
|
+
const pages = /* @__PURE__ */ new WeakMap();
|
|
78
|
+
const browser = () => {
|
|
79
|
+
const root = globalThis;
|
|
80
|
+
const doc = root.document;
|
|
81
|
+
if (!doc || typeof doc.createElement !== "function") return null;
|
|
82
|
+
return root.window ?? root;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* gtag.js only processes `arguments` objects pushed by the official snippet;
|
|
86
|
+
* arrays are ignored, so the stub must push `arguments`.
|
|
87
|
+
*/
|
|
88
|
+
const installStub = (win) => {
|
|
89
|
+
const dataLayer = win.dataLayer ?? [];
|
|
90
|
+
win.dataLayer = dataLayer;
|
|
91
|
+
if (typeof win.gtag === "function") return false;
|
|
92
|
+
win.gtag = function gtag() {
|
|
93
|
+
dataLayer.push(arguments);
|
|
94
|
+
};
|
|
95
|
+
return true;
|
|
96
|
+
};
|
|
97
|
+
const pageState = (dataLayer) => {
|
|
98
|
+
const existing = pages.get(dataLayer);
|
|
99
|
+
if (existing) return existing;
|
|
100
|
+
const created = {
|
|
101
|
+
configured: /* @__PURE__ */ new Set(),
|
|
102
|
+
consentDefault: false,
|
|
103
|
+
src: null
|
|
104
|
+
};
|
|
105
|
+
pages.set(dataLayer, created);
|
|
106
|
+
return created;
|
|
107
|
+
};
|
|
108
|
+
const hostLoadsGtag = (win) => {
|
|
109
|
+
if (win.google_tag_manager) return true;
|
|
110
|
+
return hasScript(GTAG_ORIGIN, SCRIPT_ID);
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Installs the official stub when missing, sets the consent defaults before
|
|
114
|
+
* any `config`, configures each measurement id once and loads gtag.js unless
|
|
115
|
+
* it is already on the page. Commands stay in `dataLayer` when the script
|
|
116
|
+
* fails, and the next call retries the load.
|
|
117
|
+
*/
|
|
118
|
+
const setupGtag = (setup) => {
|
|
119
|
+
const win = browser();
|
|
120
|
+
if (!win) return null;
|
|
121
|
+
const created = installStub(win);
|
|
122
|
+
const gtag = win.gtag;
|
|
123
|
+
const state = pageState(win.dataLayer);
|
|
124
|
+
if (setup.consentDefaults && !state.consentDefault) {
|
|
125
|
+
gtag("consent", "default", setup.consentDefaults);
|
|
126
|
+
state.consentDefault = true;
|
|
127
|
+
}
|
|
128
|
+
if (created) gtag("js", /* @__PURE__ */ new Date());
|
|
129
|
+
if (!setup.load) return {
|
|
130
|
+
gtag,
|
|
131
|
+
ready: Promise.resolve()
|
|
132
|
+
};
|
|
133
|
+
const id = setup.measurementId;
|
|
134
|
+
if (id && !state.configured.has(id)) {
|
|
135
|
+
gtag("config", id, setup.config ?? {});
|
|
136
|
+
state.configured.add(id);
|
|
137
|
+
}
|
|
138
|
+
if (!id || hostLoadsGtag(win)) return {
|
|
139
|
+
gtag,
|
|
140
|
+
ready: Promise.resolve()
|
|
141
|
+
};
|
|
142
|
+
state.src ??= `${GTAG_ORIGIN}?id=${encodeURIComponent(id)}`;
|
|
143
|
+
return {
|
|
144
|
+
gtag,
|
|
145
|
+
ready: loadScript(state.src, SCRIPT_ID) ?? Promise.resolve()
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
//#endregion
|
|
1
149
|
//#region src/index.ts
|
|
2
|
-
const
|
|
3
|
-
|
|
150
|
+
const WARN_PREFIX = "[@fire-spark/analytics-ga4]";
|
|
151
|
+
const consentState = (granted) => {
|
|
152
|
+
return granted ? "granted" : "denied";
|
|
4
153
|
};
|
|
5
|
-
const
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
154
|
+
const toFirebaseConsent = (consent) => {
|
|
155
|
+
const b1 = { analytics_storage: consent.analytics };
|
|
156
|
+
const b2 = {
|
|
157
|
+
ad_storage: consent.ads,
|
|
158
|
+
ad_user_data: consent.ads
|
|
159
|
+
};
|
|
160
|
+
return {
|
|
161
|
+
...b1,
|
|
162
|
+
...b2,
|
|
163
|
+
ad_personalization: consent.ads
|
|
164
|
+
};
|
|
10
165
|
};
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const el = document.createElement("script");
|
|
16
|
-
el.id = id;
|
|
17
|
-
el.async = true;
|
|
18
|
-
el.src = src;
|
|
19
|
-
el.onload = () => resolve();
|
|
20
|
-
el.onerror = () => reject(/* @__PURE__ */ new Error(`Failed to load ${src}`));
|
|
21
|
-
document.head.appendChild(el);
|
|
166
|
+
const toGtagConsent = (consent) => {
|
|
167
|
+
const firebase = toFirebaseConsent(consent);
|
|
168
|
+
const entries = Object.entries(firebase).map(([key, granted]) => {
|
|
169
|
+
return [key, consentState(granted)];
|
|
22
170
|
});
|
|
171
|
+
return Object.fromEntries(entries);
|
|
23
172
|
};
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
const root = host();
|
|
32
|
-
root.dataLayer = root.dataLayer ?? [];
|
|
33
|
-
const gtag = (...args) => {
|
|
34
|
-
root.dataLayer?.push(args);
|
|
35
|
-
};
|
|
36
|
-
root.gtag = gtag;
|
|
37
|
-
const src = `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`;
|
|
38
|
-
await injectScript(src, "firespark-ga4-gtag");
|
|
39
|
-
gtag("js", /* @__PURE__ */ new Date());
|
|
40
|
-
gtag("config", measurementId);
|
|
41
|
-
return gtag;
|
|
42
|
-
})();
|
|
43
|
-
try {
|
|
44
|
-
return await loading;
|
|
45
|
-
} finally {
|
|
46
|
-
loading = null;
|
|
47
|
-
}
|
|
173
|
+
const stringProperties = (properties = {}) => {
|
|
174
|
+
const next = {};
|
|
175
|
+
for (const [key, value] of Object.entries(properties)) next[key] = value === null ? null : String(value);
|
|
176
|
+
return next;
|
|
177
|
+
};
|
|
178
|
+
const userKey = (user) => {
|
|
179
|
+
return JSON.stringify([user?.id ?? null, user?.properties ?? {}]);
|
|
48
180
|
};
|
|
49
181
|
const ga4 = (options = {}) => {
|
|
182
|
+
let appliedUser = userKey(void 0);
|
|
183
|
+
const warn = (message) => {
|
|
184
|
+
if (options.onWarning) {
|
|
185
|
+
options.onWarning(message);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
console.warn(`${WARN_PREFIX} ${message}`);
|
|
189
|
+
};
|
|
190
|
+
const gtagSetup = (load) => {
|
|
191
|
+
const { measurementId, config, consentDefaults } = options;
|
|
192
|
+
return setupGtag({
|
|
193
|
+
measurementId,
|
|
194
|
+
config,
|
|
195
|
+
consentDefaults,
|
|
196
|
+
load
|
|
197
|
+
});
|
|
198
|
+
};
|
|
199
|
+
const applyWebUser = (user) => {
|
|
200
|
+
const page = gtagSetup(false);
|
|
201
|
+
if (!page) return;
|
|
202
|
+
page.gtag("set", { user_id: user.id ?? null });
|
|
203
|
+
if (user.properties) page.gtag("set", "user_properties", user.properties);
|
|
204
|
+
};
|
|
205
|
+
const applyNativeUser = async (user) => {
|
|
206
|
+
await options.setUserId?.(user.id ?? null);
|
|
207
|
+
if (user.properties && options.setUserProperties) await options.setUserProperties(stringProperties(user.properties));
|
|
208
|
+
};
|
|
209
|
+
const applyUser = async (user, native) => {
|
|
210
|
+
appliedUser = userKey(user);
|
|
211
|
+
if (native) {
|
|
212
|
+
await applyNativeUser(user);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
applyWebUser(user);
|
|
216
|
+
};
|
|
217
|
+
const syncUser = async (user, native) => {
|
|
218
|
+
if (userKey(user) === appliedUser) return;
|
|
219
|
+
await applyUser(user ?? { id: null }, native);
|
|
220
|
+
};
|
|
221
|
+
const sendNative = async (name, params) => {
|
|
222
|
+
if (!options.logEvent) return;
|
|
223
|
+
const issue = firebaseNameIssue(name);
|
|
224
|
+
if (issue) throw new Error(`Firebase rejects event name ${issue}`);
|
|
225
|
+
const clean = compactPayload(params);
|
|
226
|
+
for (const message of firebaseParamIssues(clean)) warn(`Event "${name}" ${message}`);
|
|
227
|
+
await options.logEvent(name, clean);
|
|
228
|
+
};
|
|
229
|
+
const sendWeb = async (name, params) => {
|
|
230
|
+
const page = gtagSetup(true);
|
|
231
|
+
if (!page) return;
|
|
232
|
+
const id = options.measurementId;
|
|
233
|
+
const payload = id ? {
|
|
234
|
+
...params,
|
|
235
|
+
send_to: id
|
|
236
|
+
} : params;
|
|
237
|
+
page.gtag("event", name, payload);
|
|
238
|
+
await page.ready;
|
|
239
|
+
};
|
|
50
240
|
return {
|
|
51
241
|
provider: "ga4",
|
|
52
242
|
send: async (event) => {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
243
|
+
const native = event.runtime === "react-native";
|
|
244
|
+
await syncUser(event.user, native);
|
|
245
|
+
if (native) {
|
|
246
|
+
await sendNative(event.name, event.params);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
await sendWeb(event.name, event.params);
|
|
250
|
+
},
|
|
251
|
+
setUser: async (user, runtime) => {
|
|
252
|
+
await applyUser(user, runtime === "react-native");
|
|
253
|
+
},
|
|
254
|
+
setConsent: async (consent, runtime) => {
|
|
255
|
+
if (runtime === "react-native") {
|
|
256
|
+
await options.setConsent?.(toFirebaseConsent(consent));
|
|
56
257
|
return;
|
|
57
258
|
}
|
|
58
|
-
|
|
59
|
-
if (!gtag) return;
|
|
60
|
-
gtag("event", event.name, event.params);
|
|
259
|
+
gtagSetup(false)?.gtag("consent", "update", toGtagConsent(consent));
|
|
61
260
|
}
|
|
62
261
|
};
|
|
63
262
|
};
|
|
64
263
|
//#endregion
|
|
65
|
-
export { ga4 };
|
|
264
|
+
export { firebaseNameIssue, ga4 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fire-spark/analytics-ga4",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.0",
|
|
4
4
|
"description": "Fire Spark GA4 analytics adapter (web gtag + RN inject)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -17,13 +17,14 @@
|
|
|
17
17
|
}
|
|
18
18
|
},
|
|
19
19
|
"peerDependencies": {
|
|
20
|
-
"@fire-spark/analytics": "^0.
|
|
20
|
+
"@fire-spark/analytics": "^0.19.0"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
|
+
"jsdom": "^22.1.0",
|
|
23
24
|
"tsdown": "^0.22.14",
|
|
24
25
|
"typescript": "^7.0.2",
|
|
25
26
|
"vitest": "^2.1.8",
|
|
26
|
-
"@fire-spark/analytics": "0.
|
|
27
|
+
"@fire-spark/analytics": "0.19.0"
|
|
27
28
|
},
|
|
28
29
|
"publishConfig": {
|
|
29
30
|
"access": "public"
|