@fire-spark/analytics-google-ads 0.0.0-stage → 0.25.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.
@@ -0,0 +1,45 @@
1
+ import { CustomAnalyticsAdapter } from "@fire-spark/analytics";
2
+ //#region src/index.d.ts
3
+ /** Same id as the server provider, so `serverSide.providers` matches. */
4
+ declare const GOOGLE_ADS_PROVIDER_ID = "google-ads";
5
+ type GoogleAdsConsentDefaults = {
6
+ ad_storage?: "granted" | "denied";
7
+ ad_user_data?: "granted" | "denied";
8
+ ad_personalization?: "granted" | "denied";
9
+ wait_for_update?: number;
10
+ };
11
+ type GoogleAdsOptions = {
12
+ /** Google Ads tag id, `AW-` followed by digits. */
13
+ conversionId: string;
14
+ /**
15
+ * Tracked event name → conversion label of that conversion action, for
16
+ * example `{ purchase: "AbCdEfGh" }`. Events without a label are not sent.
17
+ */
18
+ conversionLabels: Readonly<Record<string, string>>;
19
+ /** Params of `gtag("config", conversionId, …)`. */
20
+ config?: Record<string, unknown>;
21
+ /** `gtag("consent", "default", …)` before the first `config`. */
22
+ consentDefaults?: GoogleAdsConsentDefaults;
23
+ /** A configuration problem. Defaults to `console.warn`. */
24
+ onWarning?: (message: string) => void;
25
+ };
26
+ /**
27
+ * `transaction_id` of a conversion: the `order_id` of the event, else its
28
+ * event id. Same rule as the server provider
29
+ * (`@fire-spark/analytics-server/google`), so a purchase sent by both the
30
+ * tag and the relay counts once in Google Ads.
31
+ */
32
+ declare const googleAdsTransactionId: (orderId: unknown, eventId: string) => string;
33
+ /**
34
+ * Google Ads conversion tag for the web. Sends
35
+ * `gtag("event", "conversion", { send_to, transaction_id, value, currency })`
36
+ * for each event with a label in `conversionLabels`. Uses the `ads` consent
37
+ * gate. React Native is skipped (no gtag there).
38
+ *
39
+ * In `hybrid` mode the tag and the server relay both report the purchase
40
+ * with the same `transaction_id`, and Google Ads keeps one. In `server`
41
+ * mode the tag does not fire.
42
+ */
43
+ declare const googleAds: (options: GoogleAdsOptions) => CustomAnalyticsAdapter;
44
+ //#endregion
45
+ export { GOOGLE_ADS_PROVIDER_ID, GoogleAdsConsentDefaults, GoogleAdsOptions, googleAds, googleAdsTransactionId };
package/dist/index.js ADDED
@@ -0,0 +1,171 @@
1
+ import { compactPayload, customAdapter, hasScript, loadScript, toDecimalString } from "@fire-spark/analytics";
2
+ import { Big } from "big.js";
3
+ //#region src/gtag.ts
4
+ const GTAG_ORIGIN = "https://www.googletagmanager.com/gtag/js";
5
+ const GOOGLE_ADS_SCRIPT_ID = "firespark-google-ads-gtag";
6
+ const pages = /* @__PURE__ */ new WeakMap();
7
+ const browser = () => {
8
+ const root = globalThis;
9
+ const doc = root.document;
10
+ if (!doc || typeof doc.createElement !== "function") return null;
11
+ return root.window ?? root;
12
+ };
13
+ /** gtag.js ignores arrays in `dataLayer`; the stub must push `arguments`. */
14
+ const installStub = (win) => {
15
+ const dataLayer = win.dataLayer ?? [];
16
+ win.dataLayer = dataLayer;
17
+ if (typeof win.gtag === "function") return false;
18
+ win.gtag = function gtag() {
19
+ dataLayer.push(arguments);
20
+ };
21
+ return true;
22
+ };
23
+ const pageState = (dataLayer) => {
24
+ const existing = pages.get(dataLayer);
25
+ if (existing) return existing;
26
+ const created = {
27
+ configured: /* @__PURE__ */ new Set(),
28
+ consentDefault: false
29
+ };
30
+ pages.set(dataLayer, created);
31
+ return created;
32
+ };
33
+ /** One gtag.js serves GA4 and Google Ads ids alike. */
34
+ const hostLoadsGtag = (win) => {
35
+ if (win.google_tag_manager) return true;
36
+ return hasScript(GTAG_ORIGIN, GOOGLE_ADS_SCRIPT_ID);
37
+ };
38
+ /**
39
+ * Installs the official stub when missing, sets the consent defaults before
40
+ * any `config`, configures the conversion id once and loads gtag.js unless
41
+ * the page (or the GA4 adapter) already loads it. Returns null outside a
42
+ * browser.
43
+ */
44
+ const setupGtag = (setup) => {
45
+ const win = browser();
46
+ if (!win) return null;
47
+ const created = installStub(win);
48
+ const gtag = win.gtag;
49
+ const state = pageState(win.dataLayer);
50
+ if (setup.consentDefaults && !state.consentDefault) {
51
+ gtag("consent", "default", setup.consentDefaults);
52
+ state.consentDefault = true;
53
+ }
54
+ if (created) gtag("js", /* @__PURE__ */ new Date());
55
+ if (!setup.load) return {
56
+ gtag,
57
+ ready: Promise.resolve()
58
+ };
59
+ const id = setup.conversionId;
60
+ if (!state.configured.has(id)) {
61
+ gtag("config", id, setup.config ?? {});
62
+ state.configured.add(id);
63
+ }
64
+ if (hostLoadsGtag(win)) return {
65
+ gtag,
66
+ ready: Promise.resolve()
67
+ };
68
+ return {
69
+ gtag,
70
+ ready: loadScript(`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(id)}`, "firespark-google-ads-gtag") ?? Promise.resolve()
71
+ };
72
+ };
73
+ //#endregion
74
+ //#region src/index.ts
75
+ /** Same id as the server provider, so `serverSide.providers` matches. */
76
+ const GOOGLE_ADS_PROVIDER_ID = "google-ads";
77
+ const CONVERSION_ID = /^AW-\d+$/;
78
+ /**
79
+ * `transaction_id` of a conversion: the `order_id` of the event, else its
80
+ * event id. Same rule as the server provider
81
+ * (`@fire-spark/analytics-server/google`), so a purchase sent by both the
82
+ * tag and the relay counts once in Google Ads.
83
+ */
84
+ const googleAdsTransactionId = (orderId, eventId) => {
85
+ if (typeof orderId === "number" && Number.isFinite(orderId)) return String(orderId);
86
+ const trimmed = typeof orderId === "string" ? orderId.trim() : "";
87
+ return trimmed.length > 0 ? trimmed : eventId;
88
+ };
89
+ /** `value`, else the sum of unit price × quantity (1 when missing). */
90
+ const conversionValue = (input) => {
91
+ const explicit = toDecimalString(input.properties.value);
92
+ if (explicit !== void 0) return new Big(explicit).toNumber();
93
+ const items = input.items ?? [];
94
+ if (items.length === 0) return void 0;
95
+ let total = new Big(0);
96
+ for (const item of items) {
97
+ const price = toDecimalString(item.price ?? item.item_price);
98
+ if (price === void 0) return void 0;
99
+ const quantity = toDecimalString(item.quantity) ?? "1";
100
+ total = total.plus(new Big(price).times(quantity));
101
+ }
102
+ return total.toNumber();
103
+ };
104
+ const consentUpdate = (consent) => {
105
+ const state = consent.ads ? "granted" : "denied";
106
+ return {
107
+ ad_storage: state,
108
+ ad_user_data: state,
109
+ ad_personalization: state
110
+ };
111
+ };
112
+ /**
113
+ * Google Ads conversion tag for the web. Sends
114
+ * `gtag("event", "conversion", { send_to, transaction_id, value, currency })`
115
+ * for each event with a label in `conversionLabels`. Uses the `ads` consent
116
+ * gate. React Native is skipped (no gtag there).
117
+ *
118
+ * In `hybrid` mode the tag and the server relay both report the purchase
119
+ * with the same `transaction_id`, and Google Ads keeps one. In `server`
120
+ * mode the tag does not fire.
121
+ */
122
+ const googleAds = (options) => {
123
+ const conversionId = options.conversionId.trim();
124
+ const valid = CONVERSION_ID.test(conversionId);
125
+ const onWarning = options.onWarning ?? console.warn;
126
+ if (!valid) onWarning(`${`Google Ads conversionId "${conversionId}" is not AW-<digits>`}; no conversions are sent`);
127
+ const setup = (load) => {
128
+ return setupGtag({
129
+ conversionId,
130
+ config: options.config,
131
+ consentDefaults: options.consentDefaults,
132
+ load
133
+ });
134
+ };
135
+ const map = (input) => {
136
+ if (!valid || input.runtime !== "web") return null;
137
+ const label = options.conversionLabels[input.name]?.trim();
138
+ if (!label) return null;
139
+ const send_to = `${conversionId}/${label}`;
140
+ const id = googleAdsTransactionId(input.properties.order_id, input.eventId);
141
+ const value = conversionValue(input);
142
+ return {
143
+ name: "conversion",
144
+ params: compactPayload({
145
+ send_to,
146
+ transaction_id: id,
147
+ value,
148
+ currency: value === void 0 ? void 0 : input.currency
149
+ })
150
+ };
151
+ };
152
+ const send = async (event) => {
153
+ const page = setup(true);
154
+ if (!page) return;
155
+ page.gtag("event", event.name, event.params);
156
+ await page.ready;
157
+ };
158
+ const setConsent = (consent, runtime) => {
159
+ if (!valid || runtime !== "web") return;
160
+ setup(false)?.gtag("consent", "update", consentUpdate(consent));
161
+ };
162
+ return customAdapter({
163
+ id: GOOGLE_ADS_PROVIDER_ID,
164
+ consent: "ads",
165
+ map,
166
+ send,
167
+ setConsent
168
+ });
169
+ };
170
+ //#endregion
171
+ export { GOOGLE_ADS_PROVIDER_ID, googleAds, googleAdsTransactionId };
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@fire-spark/analytics-google-ads",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.25.0",
4
+ "description": "Fire Spark Google Ads conversion tag (web gtag, same transaction_id as the server relay)",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "big.js": "6.2.1"
21
+ },
22
+ "peerDependencies": {
23
+ "@fire-spark/analytics": "^0.25.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/big.js": "6.2.2",
27
+ "jsdom": "^22.1.0",
28
+ "tsdown": "^0.22.14",
29
+ "typescript": "^7.0.2",
30
+ "vitest": "^2.1.8",
31
+ "@fire-spark/analytics": "0.25.0",
32
+ "@fire-spark/analytics-server": "0.25.0"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "tsdown": {
38
+ "entry": [
39
+ "src/index.ts"
40
+ ],
41
+ "format": [
42
+ "esm"
43
+ ],
44
+ "platform": "neutral",
45
+ "dts": {
46
+ "tsconfig": "tsconfig.build.json"
47
+ },
48
+ "clean": true,
49
+ "deps": {
50
+ "neverBundle": [
51
+ "@fire-spark/analytics"
52
+ ]
53
+ }
54
+ },
55
+ "scripts": {
56
+ "build": "tsdown",
57
+ "dev": "tsdown --watch",
58
+ "check-types": "tsc --noEmit",
59
+ "test:utils": "vitest run",
60
+ "lint": "oxlint ./src --max-warnings=0",
61
+ "format": "oxfmt ./src",
62
+ "check-format": "oxfmt --check ./src"
63
+ }
6
64
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.