@recapi/client 0.9.0 → 0.10.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 +64 -16
- package/package.json +1 -1
- package/src/shopify.js +403 -0
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ are, gzipped, and browsers cache them:
|
|
|
35
35
|
|
|
36
36
|
```html
|
|
37
37
|
<script type="module">
|
|
38
|
-
import { createClient } from 'https://api.example.com/sdk/0.
|
|
38
|
+
import { createClient } from 'https://api.example.com/sdk/0.10.0/index.js';
|
|
39
39
|
|
|
40
40
|
const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com', consent: false });
|
|
41
41
|
// From your cookie banner, once the visitor agrees: recapi.setConsent(true).
|
|
@@ -113,7 +113,14 @@ recapi.track('item-77', 'view');
|
|
|
113
113
|
### Shopify
|
|
114
114
|
|
|
115
115
|
Shopify's checkout runs no theme code, so a Shopify shop installs recapi
|
|
116
|
-
in two places, both shown with your address in the dashboard's quick start
|
|
116
|
+
in two places, both shown with your address in the dashboard's quick start.
|
|
117
|
+
Each is a short piece, pasted once: it holds the shop's keys and what only
|
|
118
|
+
Liquid or the pixel's sandbox can give, then imports
|
|
119
|
+
`/sdk/<version>/shopify.js` from your API and makes one call. The API serves
|
|
120
|
+
that file as it does `index.js`: an older version's address redirects to the
|
|
121
|
+
current one, cached a day, so every fix reaches a shop within a day with
|
|
122
|
+
nothing to paste again. A file of its own rather than more exports of
|
|
123
|
+
`index.js`, which every other site loads.
|
|
117
124
|
|
|
118
125
|
- [`shopify/theme.liquid`](shopify/theme.liquid), pasted in a *Custom
|
|
119
126
|
Liquid* section the theme editor adds to the footer group, so it runs on
|
|
@@ -121,22 +128,47 @@ in two places, both shown with your address in the dashboard's quick start:
|
|
|
121
128
|
([Updating themes](https://help.shopify.com/en/manual/online-store/themes/managing-themes/updating-themes)).
|
|
122
129
|
A theme whose footer takes no sections gets it before `</body>` in
|
|
123
130
|
`layout/theme.liquid` instead, again after each update. Its Liquid is
|
|
124
|
-
`product.handle`
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
131
|
+
`product.handle`, `product.title`, `product.type`, `product.tags`,
|
|
132
|
+
`customer.id` and `request.page_type`, which a section
|
|
133
|
+
reads as the layout does, and it stays far below the setting's 50 KB. It identifies a
|
|
134
|
+
logged-in customer, tracks product views, sends each product page's title,
|
|
135
|
+
type and tags to `POST /v1/shopify/products:seen` (once per product per
|
|
136
|
+
browser where it may store, again when they change; recapi uses them only
|
|
137
|
+
for products the shop never described), relays the shop's `/products.json`
|
|
138
|
+
a page of 250 per product view while recapi's answer asks for one (once the
|
|
139
|
+
browser is idle and after the row; recapi keeps the progress, so nothing is
|
|
140
|
+
stored), and fills the
|
|
141
|
+
`<div id="recapi-recommendations" style="min-height: 320px"> </div>`
|
|
142
|
+
the shop pastes where the row goes with 4 product
|
|
143
|
+
cards it loads from Shopify's `/products/<handle>.js`. The ` ` matters:
|
|
144
|
+
Dawn and the themes built on it hide every empty `div`, and a hidden box
|
|
145
|
+
never comes near the screen; the snippet also puts its style in a box
|
|
146
|
+
pasted empty at once, and warns in the console when the page still hides it. Like the row of
|
|
128
147
|
Shopify's own themes, it asks for them only once the div comes within
|
|
129
148
|
400px of the screen (an `IntersectionObserver`, at once in a browser
|
|
130
149
|
without one): each list is billed and counted as an impression, and a
|
|
131
150
|
visitor who never scrolls down saw none. The view goes at page load. A
|
|
132
151
|
shop moving from an earlier snippet sees fewer served lists and its CTR
|
|
133
152
|
rise once, since lists nobody reached no longer count. The product handle
|
|
134
|
-
is the item id.
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
153
|
+
is the item id. The snippet asks for the 4 products it shows: recapi
|
|
154
|
+
counts every product of a list as shown, so a spare would get an
|
|
155
|
+
impression and could be credited a view it never caused. It skips
|
|
156
|
+
products that are sold out (`available: false`) or deleted (404), which
|
|
157
|
+
recapi may not know about; a full list that leaves a gap that way is topped
|
|
158
|
+
up once with a second list of the missing count, without the first list's
|
|
159
|
+
products (not after the popular fallback, nor after a list shorter than 4,
|
|
160
|
+
which is all recapi has). It asks through `recommendLists()`, the call that
|
|
138
161
|
takes all of a page's rows ([Several rows in one call](#several-rows-in-one-call)):
|
|
139
|
-
the page has one row, so it costs one call
|
|
162
|
+
the page has one row, so it costs one call (two with a top-up), billed as
|
|
163
|
+
one recommendation each. Each row asks for its own placement: `product` on
|
|
164
|
+
product pages, `cart` on the cart page (Shopify's `request.page_type`),
|
|
165
|
+
`section` elsewhere, so the Overview's "By placement" and a lift test tell
|
|
166
|
+
them apart; one not configured in the dashboard serves as `default`, with
|
|
167
|
+
its settings and its running lift test. A shop that pasted an earlier
|
|
168
|
+
snippet keeps it, with every row on `default` and 6 products asked for,
|
|
169
|
+
until it pastes this one: its served lists and CTR then read on 4 products
|
|
170
|
+
a list, and "By placement" splits `default` into the rows above.
|
|
171
|
+
Each card shows the picture (resized by Shopify's
|
|
140
172
|
CDN with `?width=400`), the title and `price_min` formatted with
|
|
141
173
|
`Intl.NumberFormat` in `Shopify.currency.active` and the page's `lang`
|
|
142
174
|
(no price if either is missing). An item whose
|
|
@@ -221,11 +253,23 @@ the SDK can't read is ignored. An item shown again in a later list loses its
|
|
|
221
253
|
click (as in storage), and orders that don't go through the online store's
|
|
222
254
|
cart (POS, draft orders, subscription renewals) carry no attribute.
|
|
223
255
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
256
|
+
The two calls, and their options, are a contract from 0.10.0 on: options
|
|
257
|
+
may be added, never renamed or dropped, as shops never paste again.
|
|
258
|
+
|
|
259
|
+
| Call | Options |
|
|
260
|
+
|---|---|
|
|
261
|
+
| `shopifyTheme(options)` (theme) | `apiKey`, `baseUrl`, `project`, `platform`; `product` (`handle`, `title`, `type`, `tags`: Liquid's `product`, all `null` off a product page); `shopCurrency`; `customerId` (`''` for a guest); `pageType` (`request.page_type`). Resolves once the page's work is set up. |
|
|
262
|
+
| `shopifyPixel(options, name, event)` (pixel) | `apiKey`, `baseUrl`, `project`, `platform`, `browser` (the sandbox's); `name` is the subscribed event's, `event` Shopify's. Other names are ignored. |
|
|
263
|
+
|
|
264
|
+
`test/shopify.test.js` runs both pieces with `src/shopify.js` as the quick
|
|
265
|
+
start shows them: a view, a click on a recommendation, an add to cart, then a
|
|
266
|
+
purchase in the checkout. Every piece the quick start ever printed is kept in
|
|
267
|
+
`test/fixtures/shopify/<version>/` (0.9.0: the long snippet that held its
|
|
268
|
+
own code), and `test/shopify_published.test.js` runs every case through each
|
|
269
|
+
against the current `src/shopify.js`: a change to the pieces needs a new
|
|
270
|
+
fixture, and a change to the served code must keep every older piece
|
|
271
|
+
working. The quick start fills in the current version, your address and your
|
|
272
|
+
project (`jssdk.Shopify`).
|
|
229
273
|
|
|
230
274
|
Both files name themselves (`platform: 'shopify/<version>'`, sent as
|
|
231
275
|
`?platform=` on every call), so recapi words its setup hints for Shopify.
|
|
@@ -967,6 +1011,10 @@ minifier, to keep zero dev dependencies.
|
|
|
967
1011
|
|
|
968
1012
|
## Changes
|
|
969
1013
|
|
|
1014
|
+
- 2026-11-18: version 0.10.0. `shopify.js`, served beside `index.js`
|
|
1015
|
+
with its day of cache: the code of the Shopify pieces, which now hold only
|
|
1016
|
+
the shop's keys and Liquid values, so later fixes reach a shop with no new
|
|
1017
|
+
paste.
|
|
970
1018
|
- 2026-11-15: version 0.9.0. The `platform` option names the integration
|
|
971
1019
|
making the calls (`?platform=woocommerce/0.9.0` on every request), so recapi
|
|
972
1020
|
can word its setup hints for the shop's platform. Unset, requests are unchanged.
|
package/package.json
CHANGED
package/src/shopify.js
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a Shopify shop runs: the theme's row and events, and the checkout's
|
|
3
|
+
* pixel. The pieces a shop pastes (sdk/js/shopify/) hold only what Liquid or
|
|
4
|
+
* the pixel's sandbox can give, and import this file from the API, so a fix
|
|
5
|
+
* here reaches every shop within a day (the entry's cache), with nothing to
|
|
6
|
+
* paste again. Their options are a contract: add, never rename or drop one
|
|
7
|
+
* (each published piece is a test fixture, test/fixtures/shopify/).
|
|
8
|
+
*
|
|
9
|
+
* A file of its own rather than exports of index.js, which every other site
|
|
10
|
+
* loads: they would download a Shopify row they never draw.
|
|
11
|
+
*
|
|
12
|
+
* @module @recapi/client/shopify
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createClient, localStorageAdapter, memoryStorage } from './index.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The theme's piece: the visitor's consent, the cart attribute the pixel
|
|
19
|
+
* reads, the product's view and words, and the row in `#recapi-recommendations`.
|
|
20
|
+
* Resolves once the page's work is set up (the row loads later, as the
|
|
21
|
+
* shopper scrolls near it, or at once without IntersectionObserver).
|
|
22
|
+
*
|
|
23
|
+
* @param {{ apiKey: string, baseUrl: string, project: string, platform: string,
|
|
24
|
+
* shopCurrency?: string|null, pageType?: string|null, customerId?: string|number|null,
|
|
25
|
+
* product?: { handle: string|null, title?: string|null, type?: string|null, tags?: string[]|null }|null }} options
|
|
26
|
+
*/
|
|
27
|
+
export async function shopifyTheme(options) {
|
|
28
|
+
|
|
29
|
+
// Shopify's cookie banner decides whether recapi may keep a history on the
|
|
30
|
+
// visitor's device (ePrivacy art. 5(3)), under Analytics like the pixel.
|
|
31
|
+
// Where no consent is needed it reports allowed. If it fails to load,
|
|
32
|
+
// nothing is stored: events still go out, without a visitor id. 0.2 is the
|
|
33
|
+
// version shopify.dev/docs/api/customer-privacy documents; it no longer
|
|
34
|
+
// mentions 0.1, which Shopify could stop serving.
|
|
35
|
+
const privacy = await new Promise((resolve) => {
|
|
36
|
+
const done = (api) => { clearTimeout(timer); resolve(api); };
|
|
37
|
+
const timer = setTimeout(done, 2000, null);
|
|
38
|
+
if (!window.Shopify?.loadFeatures) return done(null);
|
|
39
|
+
window.Shopify.loadFeatures([{ name: 'consent-tracking-api', version: '0.2' }],
|
|
40
|
+
(error) => done(error ? null : window.Shopify.customerPrivacy));
|
|
41
|
+
});
|
|
42
|
+
const consent = privacy?.analyticsProcessingAllowed?.() === true;
|
|
43
|
+
|
|
44
|
+
// Shopify doesn't promise that the checkout's pixel can read this page's
|
|
45
|
+
// storage, so the cart, which Shopify carries into the checkout, holds the
|
|
46
|
+
// visitor's id and the recommendations they clicked too, in an attribute
|
|
47
|
+
// whose leading _ hides it from the buyer. Only what recapi stores (so only
|
|
48
|
+
// with consent) and only when it changes: a request per click on a card,
|
|
49
|
+
// none per page. A failed request is retried by the next page.
|
|
50
|
+
const root = window.Shopify?.routes?.root ?? '/';
|
|
51
|
+
const local = localStorageAdapter() ?? memoryStorage();
|
|
52
|
+
const remember = (key, value) => (value ? local.setItem(key, value) : local.removeItem(key));
|
|
53
|
+
const toCart = (key, state) => {
|
|
54
|
+
let value = '';
|
|
55
|
+
try {
|
|
56
|
+
const { anonId, shown } = JSON.parse(state);
|
|
57
|
+
const clicked = shown.filter((entry) => entry.length > 3).slice(-10);
|
|
58
|
+
if (clicked.length) value = JSON.stringify({ anonId, shown: clicked });
|
|
59
|
+
} catch {}
|
|
60
|
+
const memo = `${key}:cart`;
|
|
61
|
+
const sent = local.getItem(memo) ?? '';
|
|
62
|
+
if (value === sent) return;
|
|
63
|
+
remember(memo, value);
|
|
64
|
+
fetch(`${root}cart/update.js`, {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
headers: { 'Content-Type': 'application/json' },
|
|
67
|
+
body: JSON.stringify({ attributes: { _recapi: value } }),
|
|
68
|
+
keepalive: true
|
|
69
|
+
}).then((response) => { if (!response.ok) throw new Error(`cart ${response.status}`); })
|
|
70
|
+
.catch(() => { if ((local.getItem(memo) ?? '') === value) remember(memo, sent); });
|
|
71
|
+
};
|
|
72
|
+
const storage = {
|
|
73
|
+
getItem: (key) => local.getItem(key),
|
|
74
|
+
setItem: (key, state) => { local.setItem(key, state); toCart(key, state); },
|
|
75
|
+
removeItem: (key) => { local.removeItem(key); toCart(key, null); }
|
|
76
|
+
};
|
|
77
|
+
// The pixel reads this state under the same project, whatever key it holds.
|
|
78
|
+
const api = { apiKey: options.apiKey, baseUrl: options.baseUrl, platform: options.platform };
|
|
79
|
+
const recapi = createClient({ ...api, project: options.project, consent, storage });
|
|
80
|
+
// What the product pages sent (below) is remembered as recapi's history
|
|
81
|
+
// is: withdrawing consent forgets it too.
|
|
82
|
+
const DESCRIBED = 'recapi:described';
|
|
83
|
+
document.addEventListener('visitorConsentCollected', (event) => {
|
|
84
|
+
recapi.setConsent(event.detail?.analyticsAllowed === true);
|
|
85
|
+
if (recapi.getAnonId() === null) local.removeItem(DESCRIBED);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
// The product handle is the item id: the purchase pixel finds it in the
|
|
89
|
+
// product's URL, and the widget loads the product's card from it.
|
|
90
|
+
const handle = typeof options.product?.handle === 'string' && options.product.handle !== '' ? options.product.handle : null;
|
|
91
|
+
const { shopCurrency } = options;
|
|
92
|
+
if (options.customerId) recapi.identify(String(options.customerId));
|
|
93
|
+
|
|
94
|
+
// What the shop's admin says the product is: recapi names the product from
|
|
95
|
+
// it when the shop sent no catalog (no products export, no webhook), so a
|
|
96
|
+
// shop that only pasted this snippet gets similar products by name. Only
|
|
97
|
+
// words: recapi never lets them overwrite what the shop sent itself. Sent
|
|
98
|
+
// once per product per browser, again when the shop changes them. They say
|
|
99
|
+
// nothing about the visitor, so they go with or without consent; what was
|
|
100
|
+
// sent is remembered only where recapi may store (else once per page view,
|
|
101
|
+
// which recapi writes only when the words changed).
|
|
102
|
+
const product = handle && { handle, title: options.product.title ?? null, type: options.product.type ?? null, tags: options.product.tags ?? null };
|
|
103
|
+
const describe = () => {
|
|
104
|
+
const body = JSON.stringify({ products: [product] });
|
|
105
|
+
// FNV-1a: a short fingerprint of the words, to tell a change.
|
|
106
|
+
let sum = 0x811c9dc5;
|
|
107
|
+
for (let i = 0; i < body.length; i++) sum = Math.imul(sum ^ body.charCodeAt(i), 0x01000193);
|
|
108
|
+
const hash = (sum >>> 0).toString(36);
|
|
109
|
+
const keep = recapi.getAnonId() !== null;
|
|
110
|
+
let sent = {};
|
|
111
|
+
try { if (keep) sent = JSON.parse(local.getItem(DESCRIBED) ?? '{}') ?? {}; } catch {}
|
|
112
|
+
if (sent[handle] === hash) return;
|
|
113
|
+
seen(body).then(async (response) => {
|
|
114
|
+
if (!response.ok) return;
|
|
115
|
+
const page = (await response.json().catch(() => null))?.list_page;
|
|
116
|
+
if (Number.isInteger(page) && page > 0) relay(page);
|
|
117
|
+
if (recapi.getAnonId() === null) return;
|
|
118
|
+
// The 100 products seen last: a visitor's storage stays small.
|
|
119
|
+
delete sent[handle];
|
|
120
|
+
sent[handle] = hash;
|
|
121
|
+
const handles = Object.keys(sent);
|
|
122
|
+
for (const old of handles.slice(0, -100)) delete sent[old];
|
|
123
|
+
local.setItem(DESCRIBED, JSON.stringify(sent));
|
|
124
|
+
}).catch(() => {});
|
|
125
|
+
};
|
|
126
|
+
// A product's words outlive the page (keepalive), as its view does. A
|
|
127
|
+
// relayed page doesn't: browsers refuse a keepalive body past 64 KiB, which
|
|
128
|
+
// 250 products with a few tags each reach, and recapi offers a page lost
|
|
129
|
+
// to navigation again once its 30 s hold ends.
|
|
130
|
+
const seen = (body, keepalive = true) => fetch(`${api.baseUrl}/v1/shopify/products:seen?key=${encodeURIComponent(api.apiKey)}&platform=${encodeURIComponent(api.platform)}`, {
|
|
131
|
+
method: 'POST',
|
|
132
|
+
// text/plain: no CORS preflight, one network trip.
|
|
133
|
+
headers: { 'Content-Type': 'text/plain' },
|
|
134
|
+
body,
|
|
135
|
+
keepalive
|
|
136
|
+
});
|
|
137
|
+
// While recapi has no catalog from the shop, it asks, in the answer above,
|
|
138
|
+
// for a page of the shop's own product list, which every Shopify storefront
|
|
139
|
+
// serves at /products.json to its visitors: a page of 250 products per page
|
|
140
|
+
// view, so a shop that only pasted this snippet has its whole catalog named
|
|
141
|
+
// after a few product views, its owner's own click-through included. recapi
|
|
142
|
+
// keeps the progress, so this needs nothing stored on the device, and hands
|
|
143
|
+
// each page to one browser at a time. Only once the browser is idle and the
|
|
144
|
+
// row (when it is being drawn) is on the page; a refused or failed read
|
|
145
|
+
// waits for the next page view, which gets the same page again.
|
|
146
|
+
let drawing = null;
|
|
147
|
+
const idle = (callback) => (window.requestIdleCallback ? window.requestIdleCallback(callback, { timeout: 10000 }) : setTimeout(callback, 2000));
|
|
148
|
+
const relay = async (page) => {
|
|
149
|
+
await new Promise(idle);
|
|
150
|
+
await drawing;
|
|
151
|
+
const response = await fetch(`${root}products.json?limit=250&page=${page}`).catch(() => null);
|
|
152
|
+
const list = response?.ok ? await response.json().catch(() => null) : null;
|
|
153
|
+
if (!Array.isArray(list?.products) || list.products.length > 250) return;
|
|
154
|
+
const words = (value, cut) => (typeof value === 'string' ? value.slice(0, cut) : '');
|
|
155
|
+
const products = [];
|
|
156
|
+
for (const p of list.products) {
|
|
157
|
+
// Any product without a handle: not the list recapi knows, so nothing goes.
|
|
158
|
+
if (typeof p?.handle !== 'string' || p.handle === '') return;
|
|
159
|
+
const tags = Array.isArray(p.tags) ? p.tags : typeof p.tags === 'string' ? p.tags.split(',') : [];
|
|
160
|
+
// recapi keeps 32 tags of 64 characters, and a title of 512 bytes.
|
|
161
|
+
products.push({ handle: p.handle, title: words(p.title, 512), type: words(p.product_type, 64), tags: tags.slice(0, 40).map((t) => words(t, 64).trim()).filter(Boolean) });
|
|
162
|
+
}
|
|
163
|
+
// The page's number tells recapi which page this is: an empty one ends the list.
|
|
164
|
+
await seen(JSON.stringify({ page, products }), false).catch(() => null);
|
|
165
|
+
};
|
|
166
|
+
if (product) describe();
|
|
167
|
+
// A card's link carries its recommendation: without consent nothing on the
|
|
168
|
+
// device remembers which list showed the product. In the fragment, which no
|
|
169
|
+
// server or crawler sees: each list's new ?rec= looks like another page.
|
|
170
|
+
// ?rec= is still read: links already out there, and the cards that can't use
|
|
171
|
+
// a fragment (below).
|
|
172
|
+
const inFragment = /^#rec_[0-9a-f]+$/;
|
|
173
|
+
const viewed = () => {
|
|
174
|
+
const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
|
|
175
|
+
const linked = fragment ?? new URLSearchParams(location.search).get('rec');
|
|
176
|
+
recapi.track(handle, 'view', { recommendationId: linked });
|
|
177
|
+
// recapi credits an explicit id to whoever brings it: drop it from the
|
|
178
|
+
// address so a copied or shared link doesn't credit strangers' visits.
|
|
179
|
+
// The other parameters (a variant) keep their exact text.
|
|
180
|
+
if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
|
|
181
|
+
else if (linked !== null) {
|
|
182
|
+
const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
|
|
183
|
+
history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
// A browser may preload the link under the pointer, and a page it prerenders
|
|
187
|
+
// runs this script though nobody may ever open it: a click nobody made must
|
|
188
|
+
// not be credited.
|
|
189
|
+
if (handle && document.prerendering) document.addEventListener('prerenderingchange', viewed);
|
|
190
|
+
else if (handle) viewed();
|
|
191
|
+
|
|
192
|
+
// Fills <div id="recapi-recommendations"> </div> wherever the theme has one.
|
|
193
|
+
const slot = document.getElementById('recapi-recommendations');
|
|
194
|
+
// A product row in the theme's colours and fonts. :where() weighs
|
|
195
|
+
// nothing, so any rule of the theme's restyles the cards.
|
|
196
|
+
const style = '<style>' +
|
|
197
|
+
':where(#recapi-recommendations){display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:1rem;align-items:start;align-content:start}' +
|
|
198
|
+
':where(#recapi-recommendations a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}' +
|
|
199
|
+
':where(#recapi-recommendations img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}' +
|
|
200
|
+
':where(#recapi-recommendations .recapi-price){font-weight:600}' +
|
|
201
|
+
'</style>';
|
|
202
|
+
// Dawn and the themes built on it hide every empty div (div:empty
|
|
203
|
+
// { display: none }): a slot pasted empty, as the quick start once
|
|
204
|
+
// printed it, has no box, never comes near the screen, and the row would
|
|
205
|
+
// never load. Its style, there at once, makes it not empty. A slot still
|
|
206
|
+
// without a box is hidden by the theme or a section around it: the row
|
|
207
|
+
// loads if that changes, and the shop's developer is told why it doesn't.
|
|
208
|
+
if (slot && !slot.getClientRects().length) {
|
|
209
|
+
slot.insertAdjacentHTML('afterbegin', style);
|
|
210
|
+
if (!slot.getClientRects().length) console.warn('recapi: the page hides #recapi-recommendations (display: none), so the row loads only once it shows');
|
|
211
|
+
}
|
|
212
|
+
// Not only [hidden]: any display rule of the theme's beats that one, and
|
|
213
|
+
// would leave a blank where the row should be.
|
|
214
|
+
const hide = () => {
|
|
215
|
+
slot.hidden = true;
|
|
216
|
+
slot.style.setProperty('display', 'none', 'important');
|
|
217
|
+
};
|
|
218
|
+
// Each row its own placement, so the dashboard and the lift test tell them
|
|
219
|
+
// apart. An unconfigured placement serves as the default one and joins its
|
|
220
|
+
// lift test, so a shop's settings carry over.
|
|
221
|
+
const { pageType } = options;
|
|
222
|
+
const placement = handle ? 'product' : pageType === 'cart' ? 'cart' : 'section';
|
|
223
|
+
// The row shows 4 cards. recapi counts every product of a list as shown,
|
|
224
|
+
// so a spare asked for would get an impression and could be credited a
|
|
225
|
+
// view it never caused: the row asks for 4. recapi learns products from
|
|
226
|
+
// events and may not know one sold out or was deleted; one more list,
|
|
227
|
+
// without the products already listed, then fills the gap.
|
|
228
|
+
const ROW = 4;
|
|
229
|
+
// Through the call that takes all of a page's rows (billed as one, the
|
|
230
|
+
// history sent once, no product on two rows): the page has this one.
|
|
231
|
+
const ask = async (count, exclude) => (await recapi.recommendLists({
|
|
232
|
+
lists: [{ count, placement, ...(handle ? { contextItemId: handle } : {}) }],
|
|
233
|
+
...(exclude.length ? { exclude } : {})
|
|
234
|
+
}))[0];
|
|
235
|
+
const draw = async () => {
|
|
236
|
+
const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
237
|
+
// Prices are in the currency's subunit (100000 is ¥1,000), in the
|
|
238
|
+
// visitor's currency. A number and a symbol need no translation.
|
|
239
|
+
const currency = window.Shopify?.currency?.active;
|
|
240
|
+
const lang = document.documentElement?.lang;
|
|
241
|
+
let money = null;
|
|
242
|
+
try { if (currency && lang) money = new Intl.NumberFormat(lang, { style: 'currency', currency }); } catch {}
|
|
243
|
+
const tag = (amount) => `<span class="recapi-price">${escape(amount)}</span>`;
|
|
244
|
+
// Only http(s) addresses: metadata is the shop's, but a javascript: link
|
|
245
|
+
// must never reach the page.
|
|
246
|
+
const web = (address) => {
|
|
247
|
+
try {
|
|
248
|
+
const url = new URL(address, location.href);
|
|
249
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
|
|
250
|
+
} catch {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
// ?rec= only where a fragment can't carry the id: the address has its own
|
|
255
|
+
// (a theme's, not ours to overwrite), it's the page already open (a
|
|
256
|
+
// fragment wouldn't load it, so no view), or the page wouldn't read it back.
|
|
257
|
+
const carry = (url, recommendationId) => {
|
|
258
|
+
const open = url.href.split('#')[0] === location.href.split('#')[0];
|
|
259
|
+
if (recommendationId && (url.hash || open || !inFragment.test(`#${recommendationId}`))) url.searchParams.set('rec', recommendationId);
|
|
260
|
+
else if (recommendationId) url.hash = recommendationId;
|
|
261
|
+
return url;
|
|
262
|
+
};
|
|
263
|
+
// An item's metadata (sent with PUT /v1/items) draws its card when it has
|
|
264
|
+
// a name and a link, with no request to Shopify. Its price is text shown
|
|
265
|
+
// as it is, or a number in the shop's currency: a visitor browsing in
|
|
266
|
+
// another one gets Shopify's converted price from the lookup instead, as
|
|
267
|
+
// does a product Shopify's webhook marked "available": false: it may be
|
|
268
|
+
// sold out, or its stock untracked, and only the lookup knows which.
|
|
269
|
+
const fromMetadata = (metadata, recommendationId) => {
|
|
270
|
+
const link = metadata?.available !== false && typeof metadata?.url === 'string' && typeof metadata.name === 'string' ? web(metadata.url) : null;
|
|
271
|
+
if (!link) return null;
|
|
272
|
+
let price = '';
|
|
273
|
+
if (typeof metadata.price === 'string') price = tag(metadata.price);
|
|
274
|
+
else if (typeof metadata.price === 'number') {
|
|
275
|
+
if (currency !== shopCurrency) return null;
|
|
276
|
+
if (money) price = tag(money.format(metadata.price));
|
|
277
|
+
}
|
|
278
|
+
carry(link, recommendationId);
|
|
279
|
+
const picture = typeof metadata.picture === 'string' ? web(metadata.picture) : null;
|
|
280
|
+
return `<a href="${escape(link.href)}">${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}<span>${escape(metadata.name)}</span>${price}</a>`;
|
|
281
|
+
};
|
|
282
|
+
// Shopify's CDN resizes on ?width=: a card needs no 2048 px original.
|
|
283
|
+
const image = (src) => (src ? `${src}${src.includes('?') ? '&' : '?'}width=400` : '');
|
|
284
|
+
// Shopify gives a product's address as a path, and it stays one.
|
|
285
|
+
const path = (address, recommendationId) => {
|
|
286
|
+
const url = carry(new URL(address, location.href), recommendationId);
|
|
287
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
288
|
+
};
|
|
289
|
+
const fromProduct = (p, recommendationId) => (p?.available
|
|
290
|
+
? `<a href="${escape(path(p.url, recommendationId))}"><img src="${escape(image(p.featured_image))}" alt="" loading="lazy"><span>${escape(p.title)}</span>${money && Number.isFinite(p.price_min) ? tag(money.format(p.price_min / 100)) : ''}</a>`
|
|
291
|
+
: null);
|
|
292
|
+
// A list's cards, in recapi's order. The others come from the product's
|
|
293
|
+
// own page data, one request each.
|
|
294
|
+
const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata }) => {
|
|
295
|
+
const card = fromMetadata(metadata, recommendationId);
|
|
296
|
+
if (card) return card;
|
|
297
|
+
const response = await fetch(`${root}products/${encodeURIComponent(itemId)}.js`).catch(() => null);
|
|
298
|
+
return fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId);
|
|
299
|
+
}))).filter(Boolean);
|
|
300
|
+
const list = await ask(ROW, []);
|
|
301
|
+
let cards = await cardsOf(list);
|
|
302
|
+
// Only a full list that couldn't fill the row: a shorter one means recapi
|
|
303
|
+
// has no more to give, and a fallback (recapi slow, down or at a limit)
|
|
304
|
+
// would only wait again.
|
|
305
|
+
if (cards.length < ROW && list.items.length >= ROW && !list.fallback) {
|
|
306
|
+
const more = await ask(ROW - cards.length, list.items.map(({ itemId }) => itemId));
|
|
307
|
+
cards = [...cards, ...await cardsOf(more)];
|
|
308
|
+
}
|
|
309
|
+
cards = cards.slice(0, ROW);
|
|
310
|
+
if (cards.length) slot.innerHTML = style + cards.join('');
|
|
311
|
+
else hide();
|
|
312
|
+
};
|
|
313
|
+
// recommendLists() rejects only on a bad request: a page still loses no more than the row.
|
|
314
|
+
const fill = () => (drawing = draw().catch((error) => {
|
|
315
|
+
hide();
|
|
316
|
+
console.warn('recapi:', error);
|
|
317
|
+
}));
|
|
318
|
+
// Only once the row comes within 400px of the screen, as Shopify's own
|
|
319
|
+
// themes load theirs: each list is billed and counted as shown, and a
|
|
320
|
+
// shopper who never scrolls down saw none. The div's min-height holds its
|
|
321
|
+
// place meanwhile. The view above went at once.
|
|
322
|
+
if (slot && typeof IntersectionObserver !== 'function') await fill();
|
|
323
|
+
else if (slot) {
|
|
324
|
+
const observer = new IntersectionObserver((entries) => {
|
|
325
|
+
if (!entries.some((entry) => entry.isIntersecting)) return undefined;
|
|
326
|
+
observer.disconnect();
|
|
327
|
+
return fill();
|
|
328
|
+
}, { rootMargin: '0px 0px 400px 0px' });
|
|
329
|
+
observer.observe(slot);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Product URLs end in /products/<handle>, the theme's item id.
|
|
334
|
+
const handleOf = (url) => {
|
|
335
|
+
const match = /\/products\/([^/?#]+)/.exec(url ?? '');
|
|
336
|
+
return match ? decodeURIComponent(match[1]) : null;
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
// Shopify doesn't promise that the checkout reads the storefront's storage:
|
|
340
|
+
// the theme's snippet also leaves the visitor and the recommendations they
|
|
341
|
+
// clicked in the cart. The SDK discards a state it can't read, so anything
|
|
342
|
+
// else there leaves the purchase without ids, as before.
|
|
343
|
+
const fromCart = (attributes) => {
|
|
344
|
+
try {
|
|
345
|
+
const { anonId, shown } = JSON.parse(attributes.find((a) => a.key === '_recapi').value);
|
|
346
|
+
return JSON.stringify({ anonId, userId: null, history: { top: [], recent: [], rejected: [], lastT: null }, shown });
|
|
347
|
+
} catch {
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
async function withRecapi({ apiKey, baseUrl, project, platform, browser }, track, attributes) {
|
|
353
|
+
// The pixel's own storage is not the shop's: read the snippet's state from
|
|
354
|
+
// the page (browser.localStorage is asynchronous, the SDK's storage
|
|
355
|
+
// synchronous) and write the events back to it.
|
|
356
|
+
const key = `recapi:v1:${project}`;
|
|
357
|
+
const read = await browser.localStorage.getItem(key);
|
|
358
|
+
let value = read ?? fromCart(attributes);
|
|
359
|
+
const storage = {
|
|
360
|
+
getItem: () => value,
|
|
361
|
+
setItem: (k, v) => { value = v; },
|
|
362
|
+
removeItem: () => { value = null; }
|
|
363
|
+
};
|
|
364
|
+
// Shopify runs this pixel only with the visitor's Analytics consent (its
|
|
365
|
+
// Customer privacy setting), and the theme's snippet stored the state under
|
|
366
|
+
// the same consent: without it there is nothing here to read.
|
|
367
|
+
const recapi = createClient({ apiKey, baseUrl, project, storage, consent: true, platform });
|
|
368
|
+
track(recapi);
|
|
369
|
+
const sent = recapi.destroy();
|
|
370
|
+
// On the storefront the theme's snippet writes the same state meanwhile
|
|
371
|
+
// (a recommendation it just showed): if it did, its copy is the newer one.
|
|
372
|
+
if (value !== read && (await browser.localStorage.getItem(key)) === read) {
|
|
373
|
+
await (value === null ? browser.localStorage.removeItem(key) : browser.localStorage.setItem(key, value));
|
|
374
|
+
}
|
|
375
|
+
await sent;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* The pixel's piece: one Shopify event (`checkout_completed` or
|
|
380
|
+
* `product_added_to_cart`) sent to recapi. Other events are ignored, so a
|
|
381
|
+
* later piece may pass more.
|
|
382
|
+
*
|
|
383
|
+
* @param {{ apiKey: string, baseUrl: string, project: string, platform: string, browser: object }} options
|
|
384
|
+
* @param {string} name the event's name
|
|
385
|
+
* @param {object} event Shopify's event
|
|
386
|
+
*/
|
|
387
|
+
export function shopifyPixel(options, name, event) {
|
|
388
|
+
if (name === 'checkout_completed') {
|
|
389
|
+
return withRecapi(options, (recapi) => {
|
|
390
|
+
for (const line of event.data.checkout.lineItems) {
|
|
391
|
+
const item = handleOf(line.variant?.product?.url);
|
|
392
|
+
if (item) recapi.track(item, 'purchase');
|
|
393
|
+
}
|
|
394
|
+
}, event.data.checkout.attributes);
|
|
395
|
+
}
|
|
396
|
+
if (name === 'product_added_to_cart') {
|
|
397
|
+
return withRecapi(options, (recapi) => {
|
|
398
|
+
const item = handleOf(event.data.cartLine?.merchandise?.product?.url);
|
|
399
|
+
if (item) recapi.track(item, 'cart');
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return Promise.resolve();
|
|
403
|
+
}
|