@buildinams/tracking 0.2.0 → 0.3.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 CHANGED
@@ -1,185 +1,119 @@
1
1
  # @buildinams/tracking
2
2
 
3
- Vendor-neutral storefront events: Sources publish them to a Broker, and each Destination receives them through its own Mapping, behind consent. Behavior rules and glossary: [docs/events.md](docs/events.md).
3
+ Vendor-neutral storefront events. Sources publish Events to a Broker; each Destination, like GA4 or Shopify, receives them through its own Mapping, once the shopper consented.
4
4
 
5
- ```tsx
6
- import { cookiebot } from "@buildinams/tracking/consent/cookiebot";
7
- import { shopifyCustomerPrivacy } from "@buildinams/tracking/consent/shopify";
8
- import {
9
- createDestinations,
10
- map,
11
- withConsent,
12
- } from "@buildinams/tracking/destinations";
13
- import { ga4 } from "@buildinams/tracking/destinations/ga4";
14
- import { shopify } from "@buildinams/tracking/destinations/shopify";
5
+ ```bash
6
+ npm install @buildinams/tracking
7
+ ```
8
+
9
+ ## Setup
10
+
11
+ Five steps; the [complete setup](docs/setup.md) has them all in one file, with every Event Name and Detector.
12
+
13
+ ### 1. Catalog and Broker
14
+
15
+ The Event Catalog lists every Event Name the storefront publishes, with the shape of its Data:
16
+
17
+ ```ts
18
+ // src/tracking/index.ts
15
19
  import { createEventBroker, shape } from "@buildinams/tracking/events";
16
- import { startTracking } from "@buildinams/tracking/flow";
17
20
  import { createCurrentPage } from "@buildinams/tracking/page";
18
- import { createCartSource } from "@buildinams/tracking/sources/cart";
19
- import { shopifyCart } from "@buildinams/tracking/sources/cart/shopify";
20
- import type {
21
- ButtonClickData,
22
- FormEventData,
23
- FormSubmitData,
24
- ItemSelectData,
25
- LinkClickData,
26
- ListViewData,
27
- VideoEventData,
28
- } from "@buildinams/tracking/sources/dom";
29
- import {
30
- clicks,
31
- createDomSource,
32
- detailViews,
33
- forms,
34
- impressions,
35
- pageViews,
36
- scroll,
37
- selections,
38
- videos,
39
- } from "@buildinams/tracking/sources/dom";
40
21
 
41
- type Item = { id: string; name?: string; price?: string };
42
- type CartLine = { id: string; quantity: number; merchandise: { id: string } };
43
- type CartFragment = { lines: { nodes: CartLine[] } };
44
- type Named = { id?: string; name?: string };
45
- type Surroundings = { list: Named; promotion: Named; location: Named };
22
+ type Item = { id: string; name?: string };
46
23
 
47
- // A new Page per pathname; pass `key` to count e.g. `?page=2` as one too.
48
24
  export const currentPage = createCurrentPage();
49
25
 
50
26
  export const broker = createEventBroker(
51
27
  {
52
- "item:select": {
53
- data: shape<Item & ItemSelectData>(),
54
- composed: shape<Surroundings>(),
55
- },
56
- "item:view": { data: shape<Item>(), composed: shape<Surroundings>() },
57
- "promotion:select": {
58
- data: shape<Named>(),
59
- composed: shape<Surroundings>(),
60
- },
61
- "promotion:view": { data: shape<Named>(), composed: shape<Surroundings>() },
62
- "list:view": {
63
- data: shape<ListViewData>(),
64
- composed: shape<Surroundings>(),
65
- },
66
- "link:click": {
67
- data: shape<LinkClickData>(),
68
- composed: shape<Surroundings>(),
69
- },
70
- "button:click": {
71
- data: shape<ButtonClickData>(),
72
- composed: shape<Surroundings>(),
73
- },
74
- "form:start": {
75
- data: shape<FormEventData>(),
76
- composed: shape<Surroundings>(),
77
- },
78
- "form:submit": {
79
- data: shape<FormSubmitData>(),
80
- composed: shape<Surroundings>(),
81
- },
82
- "video:start": { data: shape<VideoEventData>() },
83
- "video:progress": { data: shape<VideoEventData>() },
84
- "video:complete": { data: shape<VideoEventData>() },
28
+ "item:view": { data: shape<Item>() },
85
29
  "page:view": { data: shape<{ type?: string }>() },
86
- "page:scroll": { data: shape<{ depth: string }>() },
87
- "cart:add": { data: shape<{ line: CartLine; quantity: number }>() },
88
- "cart:remove": { data: shape<{ line: CartLine; quantity: number }>() },
89
30
  },
90
- // Optional; its return type becomes every Event's `context`.
91
- { context: () => ({ ...currentPage.read(), market: "nl" }) },
31
+ { context: currentPage.read },
92
32
  );
33
+ ```
93
34
 
94
- const destinations = createDestinations(broker.events, [
95
- map(withConsent(ga4(), "none"), {
96
- // The Composition decides: an Item in a Promotion but not a List is a promotion selection.
97
- "item:select": ({ data, composed: { list, promotion }, meta: { id } }) =>
98
- promotion && !list
99
- ? {
100
- name: "select_promotion",
101
- payload: {
102
- event_id: id,
103
- promotion_id: promotion.data.id,
104
- items: [{ item_id: data.id }],
105
- },
106
- }
107
- : {
108
- name: "select_item",
109
- payload: {
110
- event_id: id,
111
- items: [
112
- {
113
- item_id: data.id,
114
- item_list_id: list?.data.id,
115
- index: data.index,
116
- },
117
- ],
118
- },
119
- },
120
- }),
121
- map(withConsent(shopify(), ["analytics"]), {
122
- "item:view": ({ data }) => ({ name: "product_viewed", payload: { data } }),
35
+ ### 2. Destinations
36
+
37
+ A Mapping turns an Event into what one Destination expects, behind the consent it needs:
38
+
39
+ ```ts
40
+ import {
41
+ createDestinations,
42
+ map,
43
+ withConsent,
44
+ } from "@buildinams/tracking/destinations";
45
+ import { ga4 } from "@buildinams/tracking/destinations/ga4";
46
+
47
+ export const destinations = createDestinations(broker.events, [
48
+ map(withConsent(ga4(), ["analytics"]), {
49
+ "item:view": ({ data }) => ({
50
+ name: "view_item",
51
+ payload: { items: [{ item_id: data.id }] },
52
+ }),
123
53
  }),
124
54
  ]);
125
-
126
- export const domSource = createDomSource(
127
- broker,
128
- [
129
- pageViews(),
130
- selections(),
131
- impressions(),
132
- detailViews(),
133
- clicks(),
134
- forms(),
135
- videos(),
136
- scroll(),
137
- ],
138
- // Flushes Detectors when a Page ends and resets them when the next starts.
139
- { currentPage },
140
- );
141
- // Or your own adapter: { lines: (cart) => …, key: (line) => …, quantity: (line) => … }
142
- export const cartSource = createCartSource(broker, shopifyCart<CartFragment>());
143
-
144
- // In the browser, once, e.g. in instrumentation-client.ts (see Starting the Flow):
145
- startTracking(broker, cookiebot(), destinations, {
146
- sources: [domSource, cartSource],
147
- // Tells Shopify what the shopper answered in Cookiebot
148
- consentSinks: [shopifyCustomerPrivacy()],
149
- });
150
55
  ```
151
56
 
152
- Use `onetrust()` from `@buildinams/tracking/consent/onetrust` or `shopifyConsent()` from `@buildinams/tracking/consent/shopify` instead of `cookiebot()` for OneTrust or Shopify's privacy banner.
57
+ ### 3. Sources
153
58
 
154
- Then:
59
+ The DOM Source runs Detectors over annotated markup:
155
60
 
156
- - Opt in to clicks and videos per element with a Flag (`data-e="click"`, `data-e="video"`), or per area with `data-e-auto="links buttons forms videos"`, e.g. `<footer data-e-auto="links">`. `data-e-auto="none"` opts an area or a single element out.
157
- - Describe each Page with `data-e="page"`, e.g. `<main data-e="page" data-e-data="type:product">`: `pageViews()` publishes one `page:view` per Page with the Data of every such element, also when there are none. Put it on an element without a Role, e.g. `<div hidden data-e="page" data-e-data="type:product">` inside an Item, or the Role's Data is mixed in. List `pageViews()` first so `page:view` precedes the Page's other Events, and when mapping it to GA4's `page_view`, turn off gtag's own (`send_page_view: false` and Enhanced Measurement's history page views) or Pages count twice.
158
- - Mark the product on its detail page `data-e="item detail"` for `item:view`; clicks inside it, like add to cart, aren't `item:select`. `data-e` takes several words in any order.
159
- - Annotate markup: `data-e="item" data-e-data="id:product1"`, with `data-e-data="name"` on a descendant to use its text. In JSX or templates, spread `annotate()` from `/sources/dom` to write both attributes, e.g. `<div {...annotate(["item", "detail"], { id, title })} />`: it escapes `;` and `\` in values, which hand-written markup writes as `\;` and `\\`.
160
- - Limit a Detector by pathname with `only()` or `except()` from `/sources/dom`, e.g. `except(scroll(), ["/collections/*", "/search", /^\/account\//])` or `only(videos(), ["/lookbook/*"])`.
161
- - Call `currentPage.sync()` after every client-side navigation; in React, from a layout effect (see [New Pages in React](#new-pages-in-react)). Calling it when the Page didn't change does nothing.
162
- - Call `cartSource.setSnapshot(cart)` whenever the cart changes.
61
+ ```ts
62
+ import {
63
+ createDomSource,
64
+ detailViews,
65
+ pageViews,
66
+ } from "@buildinams/tracking/sources/dom";
67
+
68
+ export const domSource = createDomSource(broker, [pageViews(), detailViews()], {
69
+ currentPage,
70
+ });
71
+ ```
72
+
73
+ The Cart Source publishes `cart:add` and `cart:remove`: see the [complete setup](docs/setup.md).
163
74
 
164
- ## Starting the Flow
75
+ ### 4. Start the Flow
165
76
 
166
77
  Start the Flow once, in the browser's entry point rather than in a component: it then runs before hydration, so clicks and views before React takes over count too. In Next.js, that's `instrumentation-client.ts` at the project root (or in `src/`):
167
78
 
168
79
  ```ts
169
80
  // instrumentation-client.ts
81
+ import { cookiebot } from "@buildinams/tracking/consent/cookiebot";
170
82
  import { startTracking } from "@buildinams/tracking/flow";
171
83
 
172
- import { broker, cartSource, destinations, domSource } from "./src/tracking";
84
+ import { broker, destinations, domSource } from "./src/tracking";
173
85
 
174
- startTracking(broker, cookiebot(), destinations, {
175
- sources: [domSource, cartSource],
176
- consentSinks: [shopifyCustomerPrivacy()],
177
- });
86
+ startTracking(broker, cookiebot(), destinations, { sources: [domSource] });
178
87
  ```
179
88
 
180
89
  Elsewhere, call it in the module that boots the page. On the server it does nothing, and running it again, e.g. after HMR, replaces the previous Flow.
181
90
 
182
- ## New Pages in React
91
+ Use `onetrust()` or `shopifyConsent()` instead of `cookiebot()` for OneTrust or Shopify's privacy banner, from `/consent/onetrust` and `/consent/shopify`.
92
+
93
+ With GTM, pass `googleConsentMode()` from `/consent/google` in `consentSinks`, so Google's tags follow the same answer. It denies everything when created, so call `startTracking()` before GTM loads.
94
+
95
+ `googleConsentMode()` always grants `security_storage`, since storage strictly necessary for security needs no consent; `mapConsent: (_consent, google) => ({ ...google, security_storage: "denied" })` denies it.
96
+
97
+ Both built-in Consent Sinks take `mapConsent(consent, defaults)`, e.g. when the merchant counts language and region cookies as essential, or decides `sale_of_data` differently:
98
+
99
+ ```ts
100
+ googleConsentMode({
101
+ mapConsent: (_consent, google) => ({
102
+ ...google,
103
+ functionality_storage: "granted",
104
+ }),
105
+ });
106
+ shopifyCustomerPrivacy({
107
+ mapConsent: (consent, shopify) => ({
108
+ ...shopify,
109
+ sale_of_data: consent.marketing && consent.analytics,
110
+ }),
111
+ });
112
+ ```
113
+
114
+ A Consent Sink of your own takes `{ name, apply(consent), clear() }`: `clear()` is called when an answer is withdrawn back to unanswered, and should undo what `apply()` granted.
115
+
116
+ ### 5. New Pages in React
183
117
 
184
118
  `currentPage.sync()` stays in React: it has to run after the URL changed, which a router's "transition start" hook (like Next's `onRouterTransitionStart`) is too early for. Call it from a layout effect on every navigation:
185
119
 
@@ -202,67 +136,22 @@ export const TrackingPages = () => {
202
136
 
203
137
  It must be a layout effect. React commits the new page's DOM first, then runs layout effects, and only then do Detectors watching the DOM (like `detailViews()`) report what changed. With `useEffect`, a product page's `item:view` is published before `currentPage.sync()` and carries the previous Page's referrer. The first Page is the one `createCurrentPage()` was called on, so the initial render's `sync()` does nothing.
204
138
 
205
- ## Custom Context
206
-
207
- `context` is any function; its return type becomes every Event's `context`, typed in Mappings. Without it, `context` is `undefined`. Spread `currentPage.read()` into your own to add project data, such as the user:
208
-
209
- ```ts
210
- // src/tracking/context.ts
211
- import { createCurrentPage } from "@buildinams/tracking/page";
212
-
213
- // The one Current Page: also pass it to `createDomSource()` and call its `sync()`.
214
- export const currentPage = createCurrentPage();
215
-
216
- type User =
217
- | { loggedIn: true; id: string; tier: "member" | "vip" }
218
- | { loggedIn: false };
139
+ ## Annotating markup
219
140
 
220
- let user: User = { loggedIn: false };
221
-
222
- /** Called by the app whenever the session changes. */
223
- export const setTrackingUser = (next: User) => {
224
- user = next;
225
- };
141
+ Nothing is tracked unless the markup asks for it:
226
142
 
227
- export const readContext = () => ({
228
- ...currentPage.read(),
229
- user,
230
- market: document.documentElement.dataset.market ?? "default",
231
- });
143
+ ```html
144
+ <main data-e="item detail" data-e-data="id:product1">
145
+ <div hidden data-e="page" data-e-data="type:product"></div>
146
+ </main>
232
147
  ```
233
148
 
234
- ```ts
235
- const broker = createEventBroker(catalog, { context: readContext });
236
-
237
- const destinations = createDestinations(broker.events, [
238
- map(withConsent(ga4(), "none"), {
239
- "item:select": ({ data, context: { user } }) => ({
240
- name: "select_item",
241
- payload: {
242
- user_id: user.loggedIn ? user.id : undefined,
243
- items: [{ item_id: data.id }],
244
- },
245
- }),
246
- }),
247
- ]);
248
- ```
149
+ This publishes `page:view` with `{ type: "product" }` and `item:view` with `{ id: "product1" }`. Roles, Flags, `annotate()` and per-area opt-ins: [Annotations](docs/annotations.md).
249
150
 
250
- ```tsx
251
- // Wherever the session lives
252
- const TrackingUser = () => {
253
- const session = useSession();
254
- useEffect(() => {
255
- setTrackingUser(
256
- session
257
- ? { loggedIn: true, id: session.id, tier: session.tier }
258
- : { loggedIn: false },
259
- );
260
- }, [session]);
261
- return null;
262
- };
263
- ```
151
+ ## Docs
264
152
 
265
- - **Read on publish.** Each Event keeps the Context of the moment it happened, also while it waits for consent; a login mid-visit shows from the next Event on.
266
- - **Synchronous.** The reader runs inside `publish()`; keep async data, like a fetched profile, in a variable it returns, as `setTrackingUser` does.
267
- - **Only what Mappings send leaves the page.** Context isn't forwarded by itself: each Mapping picks the fields its Destination gets, behind that Destination's consent, so personal data is decided per Destination.
268
- - **Browser only.** The reader never runs on the server, so it can use `document` and `window`.
153
+ - [Complete setup](docs/setup.md): every Event Name, Detector, the Cart Source and consent in one file.
154
+ - [Annotations](docs/annotations.md): marking up Items, Lists, Pages, clicks and videos.
155
+ - [Context](docs/context.md): adding the user or market to every Event.
156
+ - [Events module](docs/events.md): glossary, behavior rules and built-in Event Names.
157
+ - [Decisions](docs/decisions/): why the pipeline is shaped this way.
@@ -0,0 +1,6 @@
1
+ // src/google/data-layer.ts
2
+ var dataLayer = (name = "dataLayer") => window[name] ??= [];
3
+
4
+ export { dataLayer };
5
+ //# sourceMappingURL=chunk-MRBVRDP6.js.map
6
+ //# sourceMappingURL=chunk-MRBVRDP6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/google/data-layer.ts"],"names":[],"mappings":";AACO,IAAM,YAAY,CAAC,IAAA,GAAO,gBAC9B,MAAA,CAA4D,IAAI,MAAM","file":"chunk-MRBVRDP6.js","sourcesContent":["/** GTM's data layer, created if GTM hasn't loaded yet. */\nexport const dataLayer = (name = \"dataLayer\"): unknown[] =>\n\t((window as unknown as Record<string, unknown[] | undefined>)[name] ??= []);\n"]}
@@ -0,0 +1,19 @@
1
+ import { ConsentMapping, ConsentSink } from '../index.js';
2
+
3
+ type GoogleConsentType = "ad_personalization" | "ad_storage" | "ad_user_data" | "analytics_storage" | "functionality_storage" | "personalization_storage" | "security_storage";
4
+ type GoogleConsentState = Record<GoogleConsentType, "granted" | "denied">;
5
+ type GoogleConsentModeOptions = {
6
+ /** The GTM data layer's global name. */
7
+ dataLayerName?: string;
8
+ /** Also maps the unanswered default, so a type granted regardless of the answer is granted from the start. */
9
+ mapConsent?: ConsentMapping<GoogleConsentState>;
10
+ /** How long Google's tags wait for the answer before firing under the default, in milliseconds. */
11
+ waitForUpdate?: number;
12
+ };
13
+ /**
14
+ * Forwards consent to Google Consent Mode. The first one created for a data layer denies every
15
+ * category by default, so create it before GTM loads or anything is pushed to the data layer.
16
+ */
17
+ declare const googleConsentMode: ({ dataLayerName, mapConsent, waitForUpdate, }?: GoogleConsentModeOptions) => ConsentSink;
18
+
19
+ export { type GoogleConsentModeOptions, type GoogleConsentState, type GoogleConsentType, googleConsentMode };
@@ -0,0 +1,53 @@
1
+ import { dataLayer } from '../../chunk-MRBVRDP6.js';
2
+
3
+ // src/consent/google/google-consent-mode.ts
4
+ var toGoogleConsent = ({
5
+ analytics,
6
+ marketing,
7
+ preferences
8
+ }) => {
9
+ const state = (allowed) => allowed ? "granted" : "denied";
10
+ return {
11
+ ad_personalization: state(marketing),
12
+ ad_storage: state(marketing),
13
+ ad_user_data: state(marketing),
14
+ analytics_storage: state(analytics),
15
+ functionality_storage: state(preferences),
16
+ personalization_storage: state(preferences),
17
+ security_storage: "granted"
18
+ };
19
+ };
20
+ var UNANSWERED = {
21
+ necessary: true,
22
+ preferences: false,
23
+ analytics: false,
24
+ marketing: false
25
+ };
26
+ var defaulted = /* @__PURE__ */ new WeakSet();
27
+ var googleConsentMode = ({
28
+ dataLayerName = "dataLayer",
29
+ mapConsent = (_consent, defaults) => defaults,
30
+ // Leaves room for consent loaded after GTM, e.g. Shopify's Customer Privacy API on a headless store.
31
+ waitForUpdate = 2e3
32
+ } = {}) => {
33
+ const toConsentMode = (consent) => mapConsent(consent, toGoogleConsent(consent));
34
+ function gtag(..._args) {
35
+ dataLayer(dataLayerName).push(arguments);
36
+ }
37
+ if (typeof window !== "undefined" && !defaulted.has(dataLayer(dataLayerName))) {
38
+ defaulted.add(dataLayer(dataLayerName));
39
+ gtag("consent", "default", {
40
+ ...toConsentMode(UNANSWERED),
41
+ wait_for_update: waitForUpdate
42
+ });
43
+ }
44
+ return {
45
+ name: "google",
46
+ apply: (consent) => gtag("consent", "update", toConsentMode(consent)),
47
+ clear: () => gtag("consent", "update", toConsentMode(UNANSWERED))
48
+ };
49
+ };
50
+
51
+ export { googleConsentMode };
52
+ //# sourceMappingURL=index.js.map
53
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/consent/google/google-consent-mode.ts"],"names":[],"mappings":";;;AA0BA,IAAM,kBAAkB,CAAC;AAAA,EACxB,SAAA;AAAA,EACA,SAAA;AAAA,EACA;AACD,CAAA,KAAmC;AAClC,EAAA,MAAM,KAAA,GAAQ,CAAC,OAAA,KAAsB,OAAA,GAAU,SAAA,GAAY,QAAA;AAC3D,EAAA,OAAO;AAAA,IACN,kBAAA,EAAoB,MAAM,SAAS,CAAA;AAAA,IACnC,UAAA,EAAY,MAAM,SAAS,CAAA;AAAA,IAC3B,YAAA,EAAc,MAAM,SAAS,CAAA;AAAA,IAC7B,iBAAA,EAAmB,MAAM,SAAS,CAAA;AAAA,IAClC,qBAAA,EAAuB,MAAM,WAAW,CAAA;AAAA,IACxC,uBAAA,EAAyB,MAAM,WAAW,CAAA;AAAA,IAC1C,gBAAA,EAAkB;AAAA,GACnB;AACD,CAAA;AAEA,IAAM,UAAA,GAAsB;AAAA,EAC3B,SAAA,EAAW,IAAA;AAAA,EACX,WAAA,EAAa,KAAA;AAAA,EACb,SAAA,EAAW,KAAA;AAAA,EACX,SAAA,EAAW;AACZ,CAAA;AAGA,IAAM,SAAA,uBAAgB,OAAA,EAAmB;AAMlC,IAAM,oBAAoB,CAAC;AAAA,EACjC,aAAA,GAAgB,WAAA;AAAA,EAChB,UAAA,GAAa,CAAC,QAAA,EAAU,QAAA,KAAa,QAAA;AAAA;AAAA,EAErC,aAAA,GAAgB;AACjB,CAAA,GAA8B,EAAC,KAAmB;AACjD,EAAA,MAAM,gBAAgB,CAAC,OAAA,KACtB,WAAW,OAAA,EAAS,eAAA,CAAgB,OAAO,CAAC,CAAA;AAE7C,EAAA,SAAS,QAAQ,KAAA,EAAkB;AAGlC,IAAA,SAAA,CAAU,aAAa,CAAA,CAAE,IAAA,CAAK,SAAS,CAAA;AAAA,EACxC;AAEA,EAAA,IACC,OAAO,WAAW,WAAA,IAClB,CAAC,UAAU,GAAA,CAAI,SAAA,CAAU,aAAa,CAAC,CAAA,EACtC;AACD,IAAA,SAAA,CAAU,GAAA,CAAI,SAAA,CAAU,aAAa,CAAC,CAAA;AACtC,IAAA,IAAA,CAAK,WAAW,SAAA,EAAW;AAAA,MAC1B,GAAG,cAAc,UAAU,CAAA;AAAA,MAC3B,eAAA,EAAiB;AAAA,KACjB,CAAA;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACN,IAAA,EAAM,QAAA;AAAA,IACN,KAAA,EAAO,CAAC,OAAA,KAAY,IAAA,CAAK,WAAW,QAAA,EAAU,aAAA,CAAc,OAAO,CAAC,CAAA;AAAA,IACpE,OAAO,MAAM,IAAA,CAAK,WAAW,QAAA,EAAU,aAAA,CAAc,UAAU,CAAC;AAAA,GACjE;AACD","file":"index.js","sourcesContent":["import { dataLayer } from \"../../google/data-layer\";\nimport type { Consent, ConsentMapping, ConsentSink } from \"..\";\n\nexport type GoogleConsentType =\n\t| \"ad_personalization\"\n\t| \"ad_storage\"\n\t| \"ad_user_data\"\n\t| \"analytics_storage\"\n\t| \"functionality_storage\"\n\t| \"personalization_storage\"\n\t| \"security_storage\";\n\nexport type GoogleConsentState = Record<\n\tGoogleConsentType,\n\t\"granted\" | \"denied\"\n>;\n\nexport type GoogleConsentModeOptions = {\n\t/** The GTM data layer's global name. */\n\tdataLayerName?: string;\n\t/** Also maps the unanswered default, so a type granted regardless of the answer is granted from the start. */\n\tmapConsent?: ConsentMapping<GoogleConsentState>;\n\t/** How long Google's tags wait for the answer before firing under the default, in milliseconds. */\n\twaitForUpdate?: number;\n};\n\nconst toGoogleConsent = ({\n\tanalytics,\n\tmarketing,\n\tpreferences,\n}: Consent): GoogleConsentState => {\n\tconst state = (allowed: boolean) => (allowed ? \"granted\" : \"denied\");\n\treturn {\n\t\tad_personalization: state(marketing),\n\t\tad_storage: state(marketing),\n\t\tad_user_data: state(marketing),\n\t\tanalytics_storage: state(analytics),\n\t\tfunctionality_storage: state(preferences),\n\t\tpersonalization_storage: state(preferences),\n\t\tsecurity_storage: \"granted\",\n\t};\n};\n\nconst UNANSWERED: Consent = {\n\tnecessary: true,\n\tpreferences: false,\n\tanalytics: false,\n\tmarketing: false,\n};\n\n// A default after an update would override the answer.\nconst defaulted = new WeakSet<unknown[]>();\n\n/**\n * Forwards consent to Google Consent Mode. The first one created for a data layer denies every\n * category by default, so create it before GTM loads or anything is pushed to the data layer.\n */\nexport const googleConsentMode = ({\n\tdataLayerName = \"dataLayer\",\n\tmapConsent = (_consent, defaults) => defaults,\n\t// Leaves room for consent loaded after GTM, e.g. Shopify's Customer Privacy API on a headless store.\n\twaitForUpdate = 2000,\n}: GoogleConsentModeOptions = {}): ConsentSink => {\n\tconst toConsentMode = (consent: Consent) =>\n\t\tmapConsent(consent, toGoogleConsent(consent));\n\n\tfunction gtag(..._args: unknown[]) {\n\t\t// GTM reads consent commands only as an `arguments` object, not an array.\n\t\t// eslint-disable-next-line prefer-rest-params\n\t\tdataLayer(dataLayerName).push(arguments);\n\t}\n\n\tif (\n\t\ttypeof window !== \"undefined\" &&\n\t\t!defaulted.has(dataLayer(dataLayerName))\n\t) {\n\t\tdefaulted.add(dataLayer(dataLayerName));\n\t\tgtag(\"consent\", \"default\", {\n\t\t\t...toConsentMode(UNANSWERED),\n\t\t\twait_for_update: waitForUpdate,\n\t\t});\n\t}\n\n\treturn {\n\t\tname: \"google\",\n\t\tapply: (consent) => gtag(\"consent\", \"update\", toConsentMode(consent)),\n\t\tclear: () => gtag(\"consent\", \"update\", toConsentMode(UNANSWERED)),\n\t};\n};\n"]}
@@ -8,11 +8,15 @@ type ConsentProvider = {
8
8
  get(): Consent | null;
9
9
  subscribe(listener: (consent: Consent | null) => void): () => void;
10
10
  };
11
+ /** Turns an answer into a platform's consent state; `defaults` is the sink's own mapping of it. */
12
+ type ConsentMapping<T> = (consent: Consent, defaults: T) => T;
11
13
  /** Is told every consent answer, e.g. a platform that gates its own tracking on it. */
12
14
  type ConsentSink = {
13
15
  /** A sink named like the Consent Provider is skipped, so consent isn't written back to its source. */
14
16
  name: string;
15
17
  apply(consent: Consent): void;
18
+ /** Told when an answer is withdrawn back to unanswered, e.g. by a banner reset, to undo what `apply()` granted. */
19
+ clear?(): void;
16
20
  };
17
21
 
18
- export type { Consent, ConsentCategory, ConsentProvider, ConsentRequirement, ConsentSink };
22
+ export type { Consent, ConsentCategory, ConsentMapping, ConsentProvider, ConsentRequirement, ConsentSink };
@@ -1,13 +1,19 @@
1
- import { ConsentProvider, ConsentCategory, Consent, ConsentSink } from '../index.js';
1
+ import { ConsentProvider, ConsentMapping, ConsentSink } from '../index.js';
2
2
 
3
3
  /** Reads consent from Shopify's Customer Privacy API, e.g. its privacy banner. */
4
4
  declare const shopifyConsent: () => ConsentProvider;
5
5
 
6
+ type ShopifyTrackingConsent = {
7
+ analytics: boolean;
8
+ marketing: boolean;
9
+ preferences: boolean;
10
+ sale_of_data: boolean;
11
+ };
6
12
  type ShopifyCustomerPrivacyOptions = {
7
- /** What Shopify's `sale_of_data` follows: a consent category, or a function of the answer. */
8
- saleOfData?: ConsentCategory | ((consent: Consent) => boolean);
13
+ /** By default `sale_of_data` follows `marketing`. */
14
+ mapConsent?: ConsentMapping<ShopifyTrackingConsent>;
9
15
  };
10
16
  /** Forwards consent to Shopify's Customer Privacy API. */
11
- declare const shopifyCustomerPrivacy: ({ saleOfData, }?: ShopifyCustomerPrivacyOptions) => ConsentSink;
17
+ declare const shopifyCustomerPrivacy: ({ mapConsent, }?: ShopifyCustomerPrivacyOptions) => ConsentSink;
12
18
 
13
- export { type ShopifyCustomerPrivacyOptions, shopifyConsent, shopifyCustomerPrivacy };
19
+ export { type ShopifyCustomerPrivacyOptions, type ShopifyTrackingConsent, shopifyConsent, shopifyCustomerPrivacy };
@@ -69,24 +69,39 @@ var shopifyConsent = () => ({
69
69
  });
70
70
 
71
71
  // src/consent/shopify/shopify-customer-privacy.ts
72
+ var toShopifyConsent = ({
73
+ analytics,
74
+ marketing,
75
+ preferences
76
+ }) => ({
77
+ analytics,
78
+ marketing,
79
+ preferences,
80
+ sale_of_data: marketing
81
+ });
72
82
  var shopifyCustomerPrivacy = ({
73
- saleOfData = "marketing"
74
- } = {}) => ({
75
- name: "shopify",
76
- apply(consent) {
77
- const { analytics, marketing, preferences } = consent;
78
- const sale_of_data = typeof saleOfData === "function" ? saleOfData(consent) : consent[saleOfData];
83
+ mapConsent = (_consent, defaults) => defaults
84
+ } = {}) => {
85
+ const apply = (consent) => {
86
+ const tracking = mapConsent(consent, toShopifyConsent(consent));
79
87
  withCustomerPrivacy(
80
- (api) => api.setTrackingConsent(
81
- { analytics, marketing, preferences, sale_of_data },
82
- (result) => {
83
- if (result?.error)
84
- warn("Shopify rejected the tracking consent", result.error);
85
- }
86
- )
88
+ (api) => api.setTrackingConsent(tracking, (result) => {
89
+ if (result?.error)
90
+ warn("Shopify rejected the tracking consent", result.error);
91
+ })
87
92
  );
88
- }
89
- });
93
+ };
94
+ return {
95
+ name: "shopify",
96
+ apply,
97
+ clear: () => apply({
98
+ necessary: true,
99
+ preferences: false,
100
+ analytics: false,
101
+ marketing: false
102
+ })
103
+ };
104
+ };
90
105
 
91
106
  export { shopifyConsent, shopifyCustomerPrivacy };
92
107
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/consent/shopify/customer-privacy-api.ts","../../../src/consent/shopify/shopify-consent.ts","../../../src/consent/shopify/shopify-customer-privacy.ts"],"names":[],"mappings":";;;AAqCO,IAAM,IAAA,GAAO,IAAI,IAAA,KAAoB;AAC3C,EAAA,IAAI,cAAA,EAAgB,OAAA,CAAQ,IAAA,CAAK,YAAA,EAAc,GAAG,IAAI,CAAA;AACvD,CAAA;AAGA,IAAM,gBAAA,GAAmB,0BAAA;AAGzB,IAAM,QAAA,GAAW,CAChB,GAAA,KAEA,OAAO,KAAK,kBAAA,KAAuB,UAAA,IACnC,IAAI,aAAA,KAAkB,SAAA;AAGhB,IAAM,sBAAsB,MAAM;AACxC,EAAA,MAAM,GAAA,GAAO,OAAyB,OAAA,EAAS,eAAA;AAC/C,EAAA,OAAO,QAAA,CAAS,GAAG,CAAA,GAAI,GAAA,GAAM,MAAA;AAC9B,CAAA;AAGO,IAAM,mBAAA,GAAsB,CAClC,QAAA,KACI;AACJ,EAAA,MAAM,MAAM,mBAAA,EAAoB;AAChC,EAAA,IAAI,GAAA,EAAK,OAAO,QAAA,CAAS,GAAG,CAAA;AAC5B,EAAA,MAAM,UAAW,MAAA,CAAyB,OAAA;AAC1C,EAAA,IAAI,CAAC,SAAS,YAAA,EAAc;AAC3B,IAAA,QAAA,CAAS,gBAAA;AAAA,MACR,gBAAA;AAAA,MACA,MAAM;AACL,QAAA,MAAM,SAAS,mBAAA,EAAoB;AACnC,QAAA,IAAI,MAAA,WAAiB,MAAM,CAAA;AAAA,kBACjB,4CAA4C,CAAA;AAAA,MACvD,CAAA;AAAA,MACA,EAAE,MAAM,IAAA;AAAK,KACd;AACA,IAAA;AAAA,EACD;AACA,EAAA,OAAA,CAAQ,YAA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ACD,IAAA,OAAO,MAAM;AACZ,MAAA,MAAA,GAAS,KAAA;AACT,MAAA,QAAA,CAAS,mBAAA,CAAoB,2BAA2B,QAAQ,CAAA;AAAA,IACjE,CAAA;AAAA,EACD;AACD,CAAA;;;AC9BO,IAAM,yBAAyB,CAAC;AAAA,EACtC,UAAA,GAAa;AACd,CAAA,GAAmC,EAAC,MAAoB;AAAA,EACvD,IAAA,EAAM,SAAA;AAAA,EACN,MAAM,OAAA,EAAS;AACd,IAAA,MAAM,EAAE,SAAA,EAAW,SAAA,EAAW,WAAA,EAAY,GAAI,OAAA;AAC9C,IAAA,MAAM,YAAA,GACL,OAAO,UAAA,KAAe,UAAA,GACnB,WAAW,OAAO,CAAA,GAClB,QAAQ,UAAU,CAAA;AACtB,IAAA,mBAAA;AAAA,MAAoB,CAAC,QACpB,GAAA,CAAI,kBAAA;AAAA,QACH,EAAE,SAAA,EAAW,SAAA,EAAW,WAAA,EAAa,YAAA,EAAa;AAAA,QAClD,CAAC,MAAA,KAAW;AACX,UAAA,IAAI,MAAA,EAAQ,KAAA;AACX,YAAA,IAAA,CAAK,uCAAA,EAAyC,OAAO,KAAK,CAAA;AAAA,QAC5D;AAAA;AACD,KACD;AAAA,EACD;AACD,CAAA","file":"index.js","sourcesContent":["import { IS_DEVELOPMENT } from \"../../config\";\n\ntype ConsentValue = \"yes\" | \"no\" | \"\";\n\nexport type CustomerPrivacyApi = {\n\tsetTrackingConsent(\n\t\tconsent: {\n\t\t\tanalytics: boolean;\n\t\t\tmarketing: boolean;\n\t\t\tpreferences: boolean;\n\t\t\tsale_of_data: boolean;\n\t\t},\n\t\tcallback: (result?: { error?: unknown }) => void,\n\t): void;\n\tcurrentVisitorConsent(): {\n\t\tanalytics: ConsentValue;\n\t\tmarketing: ConsentValue;\n\t\tpreferences: ConsentValue;\n\t};\n\tshouldShowBanner(): boolean;\n\tanalyticsProcessingAllowed(): boolean;\n\tmarketingAllowed(): boolean;\n\tpreferencesProcessingAllowed(): boolean;\n\t/** Set on headless storefronts, by Shopify's scripts. */\n\tconsentStatus?: \"loading\" | \"loaded\";\n};\n\ntype ShopifyGlobal = {\n\tShopify?: {\n\t\tcustomerPrivacy?: Partial<CustomerPrivacyApi>;\n\t\tloadFeatures?(\n\t\t\tfeatures: { name: string; version: string }[],\n\t\t\tcallback: (error?: unknown) => void,\n\t\t): void;\n\t};\n};\n\nexport const warn = (...args: unknown[]) => {\n\tif (IS_DEVELOPMENT) console.warn(\"[tracking]\", ...args);\n};\n\n/** Fired on `document` by Shopify's scripts on headless storefronts once the API has loaded. */\nconst API_LOADED_EVENT = \"consentTrackingApiLoaded\";\n\n// Headless storefronts expose a placeholder first: without methods, then one that allows everything while loading.\nconst isLoaded = (\n\tapi: Partial<CustomerPrivacyApi> | undefined,\n): api is CustomerPrivacyApi =>\n\ttypeof api?.setTrackingConsent === \"function\" &&\n\tapi.consentStatus !== \"loading\";\n\n/** The API once it has loaded, else `undefined`. */\nexport const readCustomerPrivacy = () => {\n\tconst api = (window as ShopifyGlobal).Shopify?.customerPrivacy;\n\treturn isLoaded(api) ? api : undefined;\n};\n\n/** Calls back with the API once it has loaded: loading it on themes, waiting for Shopify's scripts on headless storefronts. */\nexport const withCustomerPrivacy = (\n\tcallback: (api: CustomerPrivacyApi) => void,\n) => {\n\tconst api = readCustomerPrivacy();\n\tif (api) return callback(api);\n\tconst shopify = (window as ShopifyGlobal).Shopify;\n\tif (!shopify?.loadFeatures) {\n\t\tdocument.addEventListener(\n\t\t\tAPI_LOADED_EVENT,\n\t\t\t() => {\n\t\t\t\tconst loaded = readCustomerPrivacy();\n\t\t\t\tif (loaded) callback(loaded);\n\t\t\t\telse warn(\"Shopify's Customer Privacy API didn't load\");\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\treturn;\n\t}\n\tshopify.loadFeatures(\n\t\t[{ name: \"consent-tracking-api\", version: \"0.1\" }],\n\t\t(error) => {\n\t\t\tconst loaded = readCustomerPrivacy();\n\t\t\tif (error || !loaded)\n\t\t\t\twarn(\"Shopify's Customer Privacy API didn't load\", error);\n\t\t\telse callback(loaded);\n\t\t},\n\t);\n};\n","import type { Consent, ConsentProvider } from \"..\";\nimport {\n\treadCustomerPrivacy,\n\twithCustomerPrivacy,\n} from \"./customer-privacy-api\";\n\nconst read = (): Consent | null => {\n\tconst api = readCustomerPrivacy();\n\tif (!api) return null;\n\tconst { analytics, marketing, preferences } = api.currentVisitorConsent();\n\t// Where no banner is required, Shopify's regional defaults are the answer.\n\tconst answered =\n\t\t!api.shouldShowBanner() ||\n\t\t[analytics, marketing, preferences].some(Boolean);\n\tif (!answered) return null;\n\treturn {\n\t\tnecessary: true,\n\t\tpreferences: api.preferencesProcessingAllowed(),\n\t\tanalytics: api.analyticsProcessingAllowed(),\n\t\tmarketing: api.marketingAllowed(),\n\t};\n};\n\n/** Reads consent from Shopify's Customer Privacy API, e.g. its privacy banner. */\nexport const shopifyConsent = (): ConsentProvider => ({\n\tname: \"shopify\",\n\tget: read,\n\tsubscribe(listener) {\n\t\tlet active = true;\n\t\tconst onChange = () => listener(read());\n\t\tdocument.addEventListener(\"visitorConsentCollected\", onChange);\n\t\twithCustomerPrivacy(() => {\n\t\t\tif (active) onChange();\n\t\t});\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t\tdocument.removeEventListener(\"visitorConsentCollected\", onChange);\n\t\t};\n\t},\n});\n","import type { Consent, ConsentCategory, ConsentSink } from \"..\";\nimport { warn, withCustomerPrivacy } from \"./customer-privacy-api\";\n\nexport type ShopifyCustomerPrivacyOptions = {\n\t/** What Shopify's `sale_of_data` follows: a consent category, or a function of the answer. */\n\tsaleOfData?: ConsentCategory | ((consent: Consent) => boolean);\n};\n\n/** Forwards consent to Shopify's Customer Privacy API. */\nexport const shopifyCustomerPrivacy = ({\n\tsaleOfData = \"marketing\",\n}: ShopifyCustomerPrivacyOptions = {}): ConsentSink => ({\n\tname: \"shopify\",\n\tapply(consent) {\n\t\tconst { analytics, marketing, preferences } = consent;\n\t\tconst sale_of_data =\n\t\t\ttypeof saleOfData === \"function\"\n\t\t\t\t? saleOfData(consent)\n\t\t\t\t: consent[saleOfData];\n\t\twithCustomerPrivacy((api) =>\n\t\t\tapi.setTrackingConsent(\n\t\t\t\t{ analytics, marketing, preferences, sale_of_data },\n\t\t\t\t(result) => {\n\t\t\t\t\tif (result?.error)\n\t\t\t\t\t\twarn(\"Shopify rejected the tracking consent\", result.error);\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t},\n});\n"]}
1
+ {"version":3,"sources":["../../../src/consent/shopify/customer-privacy-api.ts","../../../src/consent/shopify/shopify-consent.ts","../../../src/consent/shopify/shopify-customer-privacy.ts"],"names":[],"mappings":";;;AAqCO,IAAM,IAAA,GAAO,IAAI,IAAA,KAAoB;AAC3C,EAAA,IAAI,cAAA,EAAgB,OAAA,CAAQ,IAAA,CAAK,YAAA,EAAc,GAAG,IAAI,CAAA;AACvD,CAAA;AAGA,IAAM,gBAAA,GAAmB,0BAAA;AAGzB,IAAM,QAAA,GAAW,CAChB,GAAA,KAEA,OAAO,KAAK,kBAAA,KAAuB,UAAA,IACnC,IAAI,aAAA,KAAkB,SAAA;AAGhB,IAAM,sBAAsB,MAAM;AACxC,EAAA,MAAM,GAAA,GAAO,OAAyB,OAAA,EAAS,eAAA;AAC/C,EAAA,OAAO,QAAA,CAAS,GAAG,CAAA,GAAI,GAAA,GAAM,MAAA;AAC9B,CAAA;AAGO,IAAM,mBAAA,GAAsB,CAClC,QAAA,KACI;AACJ,EAAA,MAAM,MAAM,mBAAA,EAAoB;AAChC,EAAA,IAAI,GAAA,EAAK,OAAO,QAAA,CAAS,GAAG,CAAA;AAC5B,EAAA,MAAM,UAAW,MAAA,CAAyB,OAAA;AAC1C,EAAA,IAAI,CAAC,SAAS,YAAA,EAAc;AAC3B,IAAA,QAAA,CAAS,gBAAA;AAAA,MACR,gBAAA;AAAA,MACA,MAAM;AACL,QAAA,MAAM,SAAS,mBAAA,EAAoB;AACnC,QAAA,IAAI,M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","file":"index.js","sourcesContent":["import { IS_DEVELOPMENT } from \"../../config\";\n\ntype ConsentValue = \"yes\" | \"no\" | \"\";\n\nexport type CustomerPrivacyApi = {\n\tsetTrackingConsent(\n\t\tconsent: {\n\t\t\tanalytics: boolean;\n\t\t\tmarketing: boolean;\n\t\t\tpreferences: boolean;\n\t\t\tsale_of_data: boolean;\n\t\t},\n\t\tcallback: (result?: { error?: unknown }) => void,\n\t): void;\n\tcurrentVisitorConsent(): {\n\t\tanalytics: ConsentValue;\n\t\tmarketing: ConsentValue;\n\t\tpreferences: ConsentValue;\n\t};\n\tshouldShowBanner(): boolean;\n\tanalyticsProcessingAllowed(): boolean;\n\tmarketingAllowed(): boolean;\n\tpreferencesProcessingAllowed(): boolean;\n\t/** Set on headless storefronts, by Shopify's scripts. */\n\tconsentStatus?: \"loading\" | \"loaded\";\n};\n\ntype ShopifyGlobal = {\n\tShopify?: {\n\t\tcustomerPrivacy?: Partial<CustomerPrivacyApi>;\n\t\tloadFeatures?(\n\t\t\tfeatures: { name: string; version: string }[],\n\t\t\tcallback: (error?: unknown) => void,\n\t\t): void;\n\t};\n};\n\nexport const warn = (...args: unknown[]) => {\n\tif (IS_DEVELOPMENT) console.warn(\"[tracking]\", ...args);\n};\n\n/** Fired on `document` by Shopify's scripts on headless storefronts once the API has loaded. */\nconst API_LOADED_EVENT = \"consentTrackingApiLoaded\";\n\n// Headless storefronts expose a placeholder first: without methods, then one that allows everything while loading.\nconst isLoaded = (\n\tapi: Partial<CustomerPrivacyApi> | undefined,\n): api is CustomerPrivacyApi =>\n\ttypeof api?.setTrackingConsent === \"function\" &&\n\tapi.consentStatus !== \"loading\";\n\n/** The API once it has loaded, else `undefined`. */\nexport const readCustomerPrivacy = () => {\n\tconst api = (window as ShopifyGlobal).Shopify?.customerPrivacy;\n\treturn isLoaded(api) ? api : undefined;\n};\n\n/** Calls back with the API once it has loaded: loading it on themes, waiting for Shopify's scripts on headless storefronts. */\nexport const withCustomerPrivacy = (\n\tcallback: (api: CustomerPrivacyApi) => void,\n) => {\n\tconst api = readCustomerPrivacy();\n\tif (api) return callback(api);\n\tconst shopify = (window as ShopifyGlobal).Shopify;\n\tif (!shopify?.loadFeatures) {\n\t\tdocument.addEventListener(\n\t\t\tAPI_LOADED_EVENT,\n\t\t\t() => {\n\t\t\t\tconst loaded = readCustomerPrivacy();\n\t\t\t\tif (loaded) callback(loaded);\n\t\t\t\telse warn(\"Shopify's Customer Privacy API didn't load\");\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\treturn;\n\t}\n\tshopify.loadFeatures(\n\t\t[{ name: \"consent-tracking-api\", version: \"0.1\" }],\n\t\t(error) => {\n\t\t\tconst loaded = readCustomerPrivacy();\n\t\t\tif (error || !loaded)\n\t\t\t\twarn(\"Shopify's Customer Privacy API didn't load\", error);\n\t\t\telse callback(loaded);\n\t\t},\n\t);\n};\n","import type { Consent, ConsentProvider } from \"..\";\nimport {\n\treadCustomerPrivacy,\n\twithCustomerPrivacy,\n} from \"./customer-privacy-api\";\n\nconst read = (): Consent | null => {\n\tconst api = readCustomerPrivacy();\n\tif (!api) return null;\n\tconst { analytics, marketing, preferences } = api.currentVisitorConsent();\n\t// Where no banner is required, Shopify's regional defaults are the answer.\n\tconst answered =\n\t\t!api.shouldShowBanner() ||\n\t\t[analytics, marketing, preferences].some(Boolean);\n\tif (!answered) return null;\n\treturn {\n\t\tnecessary: true,\n\t\tpreferences: api.preferencesProcessingAllowed(),\n\t\tanalytics: api.analyticsProcessingAllowed(),\n\t\tmarketing: api.marketingAllowed(),\n\t};\n};\n\n/** Reads consent from Shopify's Customer Privacy API, e.g. its privacy banner. */\nexport const shopifyConsent = (): ConsentProvider => ({\n\tname: \"shopify\",\n\tget: read,\n\tsubscribe(listener) {\n\t\tlet active = true;\n\t\tconst onChange = () => listener(read());\n\t\tdocument.addEventListener(\"visitorConsentCollected\", onChange);\n\t\twithCustomerPrivacy(() => {\n\t\t\tif (active) onChange();\n\t\t});\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t\tdocument.removeEventListener(\"visitorConsentCollected\", onChange);\n\t\t};\n\t},\n});\n","import type { Consent, ConsentMapping, ConsentSink } from \"..\";\nimport { warn, withCustomerPrivacy } from \"./customer-privacy-api\";\n\nexport type ShopifyTrackingConsent = {\n\tanalytics: boolean;\n\tmarketing: boolean;\n\tpreferences: boolean;\n\tsale_of_data: boolean;\n};\n\nexport type ShopifyCustomerPrivacyOptions = {\n\t/** By default `sale_of_data` follows `marketing`. */\n\tmapConsent?: ConsentMapping<ShopifyTrackingConsent>;\n};\n\nconst toShopifyConsent = ({\n\tanalytics,\n\tmarketing,\n\tpreferences,\n}: Consent): ShopifyTrackingConsent => ({\n\tanalytics,\n\tmarketing,\n\tpreferences,\n\tsale_of_data: marketing,\n});\n\n/** Forwards consent to Shopify's Customer Privacy API. */\nexport const shopifyCustomerPrivacy = ({\n\tmapConsent = (_consent, defaults) => defaults,\n}: ShopifyCustomerPrivacyOptions = {}): ConsentSink => {\n\tconst apply = (consent: Consent) => {\n\t\tconst tracking = mapConsent(consent, toShopifyConsent(consent));\n\t\twithCustomerPrivacy((api) =>\n\t\t\tapi.setTrackingConsent(tracking, (result) => {\n\t\t\t\tif (result?.error)\n\t\t\t\t\twarn(\"Shopify rejected the tracking consent\", result.error);\n\t\t\t}),\n\t\t);\n\t};\n\n\treturn {\n\t\tname: \"shopify\",\n\t\tapply,\n\t\tclear: () =>\n\t\t\tapply({\n\t\t\t\tnecessary: true,\n\t\t\t\tpreferences: false,\n\t\t\t\tanalytics: false,\n\t\t\t\tmarketing: false,\n\t\t\t}),\n\t};\n};\n"]}
@@ -1,12 +1,14 @@
1
+ import { dataLayer } from '../../chunk-MRBVRDP6.js';
2
+
1
3
  // src/destinations/ga4/ga4.ts
2
4
  var ga4 = ({
3
5
  dataLayerName = "dataLayer"
4
6
  } = {}) => ({
5
7
  name: "ga4",
6
8
  send({ name, payload }) {
7
- const target = window;
8
- const dataLayer = target[dataLayerName] ??= [];
9
- dataLayer.push({ event: name, ...payload });
9
+ const target = dataLayer(dataLayerName);
10
+ if ("ecommerce" in payload) target.push({ ecommerce: null });
11
+ target.push({ event: name, ...payload });
10
12
  }
11
13
  });
12
14
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/destinations/ga4/ga4.ts"],"names":[],"mappings":";AAUO,IAAM,MAAM,CAAC;AAAA,EACnB,aAAA,GAAgB;AACjB,CAAA,GAAgB,EAAC,MAA8B;AAAA,EAC9C,IAAA,EAAM,KAAA;AAAA,EACN,IAAA,CAAK,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG;AACvB,IAAA,MAAM,MAAA,GAAS,MAAA;AACf,IAAA,MAAM,SAAA,GAAa,MAAA,CAAO,aAAa,CAAA,KAAM,EAAC;AAC9C,IAAA,SAAA,CAAU,KAAK,EAAE,KAAA,EAAO,IAAA,EAAM,GAAG,SAAS,CAAA;AAAA,EAC3C;AACD,CAAA","file":"index.js","sourcesContent":["import type { Destination } from \"..\";\n\nexport type Ga4Event = { name: string; payload: Record<string, unknown> };\n\nexport type Ga4Options = {\n\t/** The GTM data layer's global name. */\n\tdataLayerName?: string;\n};\n\n/** Pushes to GTM's data layer; GA4 Consent Mode in the container gates it. */\nexport const ga4 = ({\n\tdataLayerName = \"dataLayer\",\n}: Ga4Options = {}): Destination<Ga4Event> => ({\n\tname: \"ga4\",\n\tsend({ name, payload }) {\n\t\tconst target = window as unknown as Record<string, unknown[] | undefined>;\n\t\tconst dataLayer = (target[dataLayerName] ??= []);\n\t\tdataLayer.push({ event: name, ...payload });\n\t},\n});\n"]}
1
+ {"version":3,"sources":["../../../src/destinations/ga4/ga4.ts"],"names":[],"mappings":";;;AAWO,IAAM,MAAM,CAAC;AAAA,EACnB,aAAA,GAAgB;AACjB,CAAA,GAAgB,EAAC,MAA8B;AAAA,EAC9C,IAAA,EAAM,KAAA;AAAA,EACN,IAAA,CAAK,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG;AACvB,IAAA,MAAM,MAAA,GAAS,UAAU,aAAa,CAAA;AAEtC,IAAA,IAAI,eAAe,OAAA,EAAS,MAAA,CAAO,KAAK,EAAE,SAAA,EAAW,MAAM,CAAA;AAC3D,IAAA,MAAA,CAAO,KAAK,EAAE,KAAA,EAAO,IAAA,EAAM,GAAG,SAAS,CAAA;AAAA,EACxC;AACD,CAAA","file":"index.js","sourcesContent":["import { dataLayer } from \"../../google/data-layer\";\nimport type { Destination } from \"..\";\n\nexport type Ga4Event = { name: string; payload: Record<string, unknown> };\n\nexport type Ga4Options = {\n\t/** The GTM data layer's global name. */\n\tdataLayerName?: string;\n};\n\n/** Pushes to GTM's data layer; GA4 Consent Mode in the container gates it. */\nexport const ga4 = ({\n\tdataLayerName = \"dataLayer\",\n}: Ga4Options = {}): Destination<Ga4Event> => ({\n\tname: \"ga4\",\n\tsend({ name, payload }) {\n\t\tconst target = dataLayer(dataLayerName);\n\t\t// GTM merges every push into one data model, so the previous event's `ecommerce` would carry over.\n\t\tif (\"ecommerce\" in payload) target.push({ ecommerce: null });\n\t\ttarget.push({ event: name, ...payload });\n\t},\n});\n"]}