@usequeek/theme-kit 0.1.28 → 0.1.29
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/apps/storefront-events.ts +277 -0
- package/client.ts +1 -0
- package/package.json +1 -1
- package/stores/cart-store.ts +9 -6
- package/types/vendor.ts +7 -1
- package/utils/format.ts +9 -0
- package/apps/analytics-events.ts +0 -32
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { roundAmount } from '../utils/format';
|
|
4
|
+
import { gtagPush } from './gtag';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The one place a storefront announces a shopping event.
|
|
8
|
+
*
|
|
9
|
+
* trackStorefrontEvent('product_added_to_cart', { currency, value, items });
|
|
10
|
+
*
|
|
11
|
+
* Code that emits an event never calls a provider SDK. Providers subscribe:
|
|
12
|
+
* the Google Analytics subscriber is registered below, once, as soon as this
|
|
13
|
+
* module loads; the host registers any other provider with `onStorefrontEvent`.
|
|
14
|
+
*
|
|
15
|
+
* The bus is synchronous. A subscriber that throws is isolated: the page and
|
|
16
|
+
* the other subscribers carry on. With no `window` (server render) an event is
|
|
17
|
+
* a no-op, so emitting is always safe.
|
|
18
|
+
*
|
|
19
|
+
* No customer field travels on the bus: product ids, names, prices, quantities,
|
|
20
|
+
* value, currency, the order number and `paid` only. That is enforced at runtime,
|
|
21
|
+
* not just in the types: every event is rebuilt from its known keys before any
|
|
22
|
+
* subscriber sees it, so an extra key on the payload or on an item (line text,
|
|
23
|
+
* an email, a phone) never reaches a subscriber or `dataLayer`.
|
|
24
|
+
*
|
|
25
|
+
* Register subscribers on the client (an effect, or client module load), never
|
|
26
|
+
* in a server render body: on the server `onStorefrontEvent` is a no-op.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
export interface StorefrontEventItem {
|
|
30
|
+
item_id: string;
|
|
31
|
+
item_name: string;
|
|
32
|
+
/** The unit price actually charged, after discounts. Providers sum price * quantity as revenue. */
|
|
33
|
+
price: number;
|
|
34
|
+
quantity: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface StorefrontEventMap {
|
|
38
|
+
product_viewed: { currency: string; value: number; items: StorefrontEventItem[] };
|
|
39
|
+
/** Scrubbed by the bus before any subscriber sees it (see `scrubSearchTerm`). */
|
|
40
|
+
search_submitted: { search_term: string };
|
|
41
|
+
product_added_to_cart: { currency: string; value: number; items: StorefrontEventItem[] };
|
|
42
|
+
checkout_started: { currency: string; value: number; num_items: number; items: StorefrontEventItem[] };
|
|
43
|
+
checkout_completed: {
|
|
44
|
+
/** The human order number, never the order UUID. */
|
|
45
|
+
order_no: string;
|
|
46
|
+
currency: string;
|
|
47
|
+
/** The order's grand total (what the customer paid), tax and shipping included. */
|
|
48
|
+
value: number;
|
|
49
|
+
/** False for an order still awaiting online payment. */
|
|
50
|
+
paid: boolean;
|
|
51
|
+
items: StorefrontEventItem[];
|
|
52
|
+
/** Items after discounts, excluding tax and shipping. GA4 `purchase.value` uses it
|
|
53
|
+
* when finite, otherwise the sum of price * quantity of `items`. */
|
|
54
|
+
subtotal?: number;
|
|
55
|
+
/** Tax and shipping amounts of the order, when known. GA4 takes them as separate parameters. */
|
|
56
|
+
tax?: number;
|
|
57
|
+
shipping?: number;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type StorefrontEventName = keyof StorefrontEventMap;
|
|
62
|
+
|
|
63
|
+
export type StorefrontEvent = {
|
|
64
|
+
[K in StorefrontEventName]: { name: K; data: StorefrontEventMap[K] };
|
|
65
|
+
}[StorefrontEventName];
|
|
66
|
+
|
|
67
|
+
/** A handler may be async; a rejection is caught and logged like a throw. */
|
|
68
|
+
export type StorefrontEventHandler = (event: StorefrontEvent) => void | Promise<unknown>;
|
|
69
|
+
|
|
70
|
+
const SEARCH_TERM_MAX_LENGTH = 100;
|
|
71
|
+
const SEARCH_TERM_MAX_DIGITS = 6;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Cleans a shopper's search text before it can reach any provider. Returns
|
|
75
|
+
* `null` when the event must be dropped entirely: empty, an `@` (or `%40`)
|
|
76
|
+
* anywhere (an email address), or 7 or more digits IN TOTAL anywhere in the
|
|
77
|
+
* text (a phone, card or order number; "in total" rather than "consecutive" is
|
|
78
|
+
* the stricter rule, so `0803 123 4567` and `08-03-12-34-567` are both dropped).
|
|
79
|
+
* The text is NFKC-normalised first, so full-width `@`, small `﹫`, superscript
|
|
80
|
+
* and circled digits count as what they look like. The checks run on the full
|
|
81
|
+
* trimmed text, then the result is capped at 100 characters.
|
|
82
|
+
*/
|
|
83
|
+
export function scrubSearchTerm(raw: unknown): string | null {
|
|
84
|
+
if (typeof raw !== 'string') {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const trimmed = raw.normalize('NFKC').trim();
|
|
89
|
+
|
|
90
|
+
if (trimmed === '' || trimmed.includes('@') || /%40/i.test(trimmed)) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if ((trimmed.match(/\p{N}/gu) ?? []).length > SEARCH_TERM_MAX_DIGITS) {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const capped = Array.from(trimmed).slice(0, SEARCH_TERM_MAX_LENGTH).join('').trim();
|
|
99
|
+
|
|
100
|
+
return capped === '' ? null : capped;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const handlers = new Set<StorefrontEventHandler>();
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Subscribes to every storefront event. Returns the unsubscribe function.
|
|
107
|
+
* Without a `window` (server render) nothing is stored and the unsubscribe is a no-op.
|
|
108
|
+
*/
|
|
109
|
+
export function onStorefrontEvent(handler: StorefrontEventHandler): () => void {
|
|
110
|
+
if (typeof window === 'undefined') {
|
|
111
|
+
return () => {};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
handlers.add(handler);
|
|
115
|
+
|
|
116
|
+
return () => {
|
|
117
|
+
handlers.delete(handler);
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function normalizeItems(items: unknown): StorefrontEventItem[] {
|
|
122
|
+
if (!Array.isArray(items)) {
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return items.map((item: Partial<StorefrontEventItem> | null) => ({
|
|
127
|
+
item_id: String(item?.item_id ?? ''),
|
|
128
|
+
item_name: String(item?.item_name ?? ''),
|
|
129
|
+
price: Number(item?.price),
|
|
130
|
+
quantity: Number(item?.quantity),
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Rebuilds an event from its known keys only, so nothing extra reaches a subscriber. */
|
|
135
|
+
function normalizeEvent<K extends StorefrontEventName>(name: K, data: StorefrontEventMap[K]): StorefrontEvent | null {
|
|
136
|
+
const raw = (data ?? {}) as Record<string, unknown>;
|
|
137
|
+
|
|
138
|
+
switch (name) {
|
|
139
|
+
case 'search_submitted': {
|
|
140
|
+
const term = scrubSearchTerm(raw.search_term);
|
|
141
|
+
|
|
142
|
+
return term === null ? null : { name: 'search_submitted', data: { search_term: term } };
|
|
143
|
+
}
|
|
144
|
+
case 'product_viewed':
|
|
145
|
+
case 'product_added_to_cart':
|
|
146
|
+
return {
|
|
147
|
+
name,
|
|
148
|
+
data: {
|
|
149
|
+
currency: String(raw.currency ?? ''),
|
|
150
|
+
value: roundAmount(Number(raw.value)),
|
|
151
|
+
items: normalizeItems(raw.items),
|
|
152
|
+
},
|
|
153
|
+
} as StorefrontEvent;
|
|
154
|
+
case 'checkout_started':
|
|
155
|
+
return {
|
|
156
|
+
name: 'checkout_started',
|
|
157
|
+
data: {
|
|
158
|
+
currency: String(raw.currency ?? ''),
|
|
159
|
+
value: roundAmount(Number(raw.value)),
|
|
160
|
+
num_items: Number(raw.num_items),
|
|
161
|
+
items: normalizeItems(raw.items),
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
case 'checkout_completed': {
|
|
165
|
+
const extras = (key: 'subtotal' | 'tax' | 'shipping'): Partial<Record<typeof key, number>> =>
|
|
166
|
+
typeof raw[key] === 'number' ? { [key]: roundAmount(raw[key] as number) } : {};
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
name: 'checkout_completed',
|
|
170
|
+
data: {
|
|
171
|
+
order_no: String(raw.order_no ?? ''),
|
|
172
|
+
currency: String(raw.currency ?? ''),
|
|
173
|
+
value: roundAmount(Number(raw.value)),
|
|
174
|
+
paid: raw.paid === true,
|
|
175
|
+
items: normalizeItems(raw.items),
|
|
176
|
+
...extras('subtotal'),
|
|
177
|
+
...extras('tax'),
|
|
178
|
+
...extras('shipping'),
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
default:
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function logSubscriberError(name: string, error: unknown): void {
|
|
188
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
189
|
+
console.error('[storefront-events] a subscriber threw on', name, error);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function trackStorefrontEvent<K extends StorefrontEventName>(name: K, data: StorefrontEventMap[K]): void {
|
|
194
|
+
if (typeof window === 'undefined') {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const event = normalizeEvent(name, data);
|
|
199
|
+
|
|
200
|
+
if (event === null) {
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
for (const handler of [...handlers]) {
|
|
205
|
+
try {
|
|
206
|
+
const result = handler(event);
|
|
207
|
+
|
|
208
|
+
if (result && typeof (result as Promise<unknown>).catch === 'function') {
|
|
209
|
+
(result as Promise<unknown>).catch((error: unknown) => logSubscriberError(name, error));
|
|
210
|
+
}
|
|
211
|
+
} catch (error) {
|
|
212
|
+
logSubscriberError(name, error);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const finite = (value: number): boolean => Number.isFinite(value);
|
|
218
|
+
|
|
219
|
+
/** `{ value }` when it is a real number, nothing otherwise: GA gets no `NaN`. */
|
|
220
|
+
const valueParam = (value: number): { value: number } | Record<string, never> => (finite(value) ? { value } : {});
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Google Analytics 4. Not gated on consent here: Consent Mode (see
|
|
224
|
+
* analytics.tsx) decides whether gtag.js transmits anything for a denied
|
|
225
|
+
* visitor, so events are pushed unconditionally and Google's library filters.
|
|
226
|
+
*
|
|
227
|
+
* `purchase.value` follows Google's reference: the sum of price * quantity of
|
|
228
|
+
* the items (after discounts), excluding shipping and tax, which go in their own
|
|
229
|
+
* parameters. The event's `subtotal` is used when given; the payload `value`
|
|
230
|
+
* (grand total) is never sent to GA as the purchase value.
|
|
231
|
+
*/
|
|
232
|
+
function googleAnalyticsSubscriber(event: StorefrontEvent): void {
|
|
233
|
+
switch (event.name) {
|
|
234
|
+
case 'product_viewed':
|
|
235
|
+
gtagPush('event', 'view_item', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
|
|
236
|
+
return;
|
|
237
|
+
case 'search_submitted':
|
|
238
|
+
gtagPush('event', 'search', { search_term: event.data.search_term });
|
|
239
|
+
return;
|
|
240
|
+
case 'product_added_to_cart':
|
|
241
|
+
gtagPush('event', 'add_to_cart', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
|
|
242
|
+
return;
|
|
243
|
+
case 'checkout_started':
|
|
244
|
+
gtagPush('event', 'begin_checkout', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
|
|
245
|
+
return;
|
|
246
|
+
case 'checkout_completed': {
|
|
247
|
+
const { order_no, currency, items, subtotal, tax, shipping } = event.data;
|
|
248
|
+
const value =
|
|
249
|
+
typeof subtotal === 'number' && finite(subtotal)
|
|
250
|
+
? subtotal
|
|
251
|
+
: roundAmount(items.reduce((sum, item) => sum + item.price * item.quantity, 0));
|
|
252
|
+
|
|
253
|
+
gtagPush('event', 'purchase', {
|
|
254
|
+
transaction_id: order_no,
|
|
255
|
+
...valueParam(value),
|
|
256
|
+
currency,
|
|
257
|
+
...(typeof tax === 'number' && finite(tax) ? { tax } : {}),
|
|
258
|
+
...(typeof shipping === 'number' && finite(shipping) ? { shipping } : {}),
|
|
259
|
+
items,
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
let googleAnalyticsRegistered = false;
|
|
266
|
+
|
|
267
|
+
/** Idempotent; runs once at module load so GA is live whenever the bus is used. */
|
|
268
|
+
export function registerGoogleAnalyticsSubscriber(): void {
|
|
269
|
+
if (googleAnalyticsRegistered) {
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
googleAnalyticsRegistered = true;
|
|
274
|
+
handlers.add(googleAnalyticsSubscriber);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
registerGoogleAnalyticsSubscriber();
|
package/client.ts
CHANGED
|
@@ -27,6 +27,7 @@ export * from './components/checkout/default-checkout-shell';
|
|
|
27
27
|
export * from './components/checkout/checkout-contact';
|
|
28
28
|
export * from './components/checkout/policy-links';
|
|
29
29
|
export * from './apps/follow-card';
|
|
30
|
+
export * from './apps/storefront-events';
|
|
30
31
|
export * from './apps/subscribe-form';
|
|
31
32
|
export * from './api/collections';
|
|
32
33
|
export * from './api/orders';
|
package/package.json
CHANGED
package/stores/cart-store.ts
CHANGED
|
@@ -5,8 +5,8 @@ import { createJSONStorage, persist } from 'zustand/middleware';
|
|
|
5
5
|
import type { CartAddon, CartItem } from '../types/cart';
|
|
6
6
|
import type { Product, ProductVariant } from '../types/product';
|
|
7
7
|
import { toast } from './toast-store';
|
|
8
|
-
import { normalizeCurrencyCode, PLATFORM_DEFAULT_CURRENCY } from '../utils/format';
|
|
9
|
-
import {
|
|
8
|
+
import { normalizeCurrencyCode, PLATFORM_DEFAULT_CURRENCY, roundAmount } from '../utils/format';
|
|
9
|
+
import { trackStorefrontEvent } from '../apps/storefront-events';
|
|
10
10
|
import { getActivePlatform, platformScopedStorage } from '../sdk/platform';
|
|
11
11
|
import { productRequiresVariant } from '../utils/match-variant';
|
|
12
12
|
import { readLineText } from './line-text-store';
|
|
@@ -154,10 +154,7 @@ export const useCartStore = create<CartState>()(
|
|
|
154
154
|
showCart: true,
|
|
155
155
|
});
|
|
156
156
|
}
|
|
157
|
-
|
|
158
|
-
{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: Math.max(1, quantity) },
|
|
159
|
-
get().currency,
|
|
160
|
-
);
|
|
157
|
+
const addedQuantity = Math.max(1, quantity);
|
|
161
158
|
|
|
162
159
|
set((state) => {
|
|
163
160
|
const existing = state.items.findIndex(
|
|
@@ -196,6 +193,12 @@ export const useCartStore = create<CartState>()(
|
|
|
196
193
|
],
|
|
197
194
|
};
|
|
198
195
|
});
|
|
196
|
+
|
|
197
|
+
trackStorefrontEvent('product_added_to_cart', {
|
|
198
|
+
currency: get().currency,
|
|
199
|
+
value: roundAmount(unitPrice * addedQuantity),
|
|
200
|
+
items: [{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: addedQuantity }],
|
|
201
|
+
});
|
|
199
202
|
},
|
|
200
203
|
removeItem: (id, shopId) => {
|
|
201
204
|
set((state) => ({
|
package/types/vendor.ts
CHANGED
|
@@ -225,7 +225,13 @@ export interface StorefrontConfig {
|
|
|
225
225
|
}>;
|
|
226
226
|
apps?: {
|
|
227
227
|
whatsapp_chat?: { enabled?: boolean; number?: string; message?: string; position?: string; bottom_offset?: number };
|
|
228
|
-
analytics?: {
|
|
228
|
+
analytics?: {
|
|
229
|
+
enabled?: boolean;
|
|
230
|
+
ga_id?: string;
|
|
231
|
+
meta_pixel_id?: string;
|
|
232
|
+
tiktok_pixel_id?: string;
|
|
233
|
+
pinterest_tag_id?: string;
|
|
234
|
+
};
|
|
229
235
|
follow_card?: { enabled?: boolean; display?: 'floating' | 'footer' | 'block'; position?: string };
|
|
230
236
|
subscribe?: {
|
|
231
237
|
enabled?: boolean;
|
package/utils/format.ts
CHANGED
|
@@ -172,6 +172,15 @@ export function formatMoney(
|
|
|
172
172
|
}
|
|
173
173
|
|
|
174
174
|
/** A whole-number percentage string, e.g. `toPercent(12.4)` is `"12%"`. */
|
|
175
|
+
/**
|
|
176
|
+
* The one rounding for an amount the kit computes (event values, line totals):
|
|
177
|
+
* three decimals, enough for KWD/BHD/OMR, and it strips float noise such as
|
|
178
|
+
* 59.970000000000006. A non-finite input stays non-finite so callers can omit it.
|
|
179
|
+
*/
|
|
180
|
+
export function roundAmount(amount: number): number {
|
|
181
|
+
return Number(amount.toFixed(3));
|
|
182
|
+
}
|
|
183
|
+
|
|
175
184
|
export function toPercent(value: number): string {
|
|
176
185
|
return `${Math.max(0, Math.round(value))}%`;
|
|
177
186
|
}
|
package/apps/analytics-events.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
'use client';
|
|
2
|
-
|
|
3
|
-
import { gtagPush } from './gtag';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Not gated on consent here — Consent Mode (see analytics.tsx) is what
|
|
7
|
-
* decides whether gtag.js actually transmits anything for a denied visitor.
|
|
8
|
-
* Callers push events unconditionally; Google's library filters them.
|
|
9
|
-
*/
|
|
10
|
-
interface GaItem {
|
|
11
|
-
item_id: string;
|
|
12
|
-
item_name: string;
|
|
13
|
-
price: number;
|
|
14
|
-
quantity?: number;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function pushViewItem(item: GaItem, currency: string): void {
|
|
18
|
-
gtagPush('event', 'view_item', { currency, value: item.price, items: [item] });
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function pushAddToCart(item: GaItem, currency: string): void {
|
|
22
|
-
gtagPush('event', 'add_to_cart', { currency, value: item.price * (item.quantity ?? 1), items: [item] });
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export function pushPurchase(args: { transactionId: string; value: number; currency: string; items: GaItem[] }): void {
|
|
26
|
-
gtagPush('event', 'purchase', {
|
|
27
|
-
transaction_id: args.transactionId,
|
|
28
|
-
value: args.value,
|
|
29
|
-
currency: args.currency,
|
|
30
|
-
items: args.items,
|
|
31
|
-
});
|
|
32
|
-
}
|