@recapi/client 0.12.0 → 0.13.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.
Files changed (3) hide show
  1. package/README.md +31 -1
  2. package/package.json +1 -1
  3. package/src/magento.js +262 -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.12.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.13.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).
@@ -543,6 +543,32 @@ pages it fills recapi's row, drawing each card from the item's `metadata`
543
543
  or, without it, from the store; the row is printed with the store's own
544
544
  products, which stay while recapi has none.
545
545
 
546
+ #### The served storefront code
547
+
548
+ From module 0.4.25 (library 0.13.0) the module's template holds only what
549
+ Magento knows about the page and the store's key: it imports
550
+ `/sdk/<version>/magento.js` from your API and makes one call, on Luma and on
551
+ Hyvä alike. The API serves that file beside `index.js`, with the same day of
552
+ cache, and an older version's address redirects to it. So a fix of the row,
553
+ consent or the events reaches every store within a day, with nothing to
554
+ install again. A fix of the module's PHP (catalog sync, orders) still needs
555
+ `composer update` or the new zip. The module's Content Security Policy
556
+ already allows the API's host, which serves both files.
557
+
558
+ The call and its options are a contract from 0.13.0 on: options may be added,
559
+ never renamed or dropped, as stores keep the module they installed.
560
+
561
+ | Call | Options |
562
+ |---|---|
563
+ | `magentoPage(page)` | `page`, as the module's block prints it: `api` (your API's address), `key` (the public key), `platform` (`magento/<module version>`), `product` (the product page's id, `null` elsewhere), `placement` (`product`, `cart` or `block`), `cookieRestriction` (`true` when Cookie Restriction Mode is on), `website` (the website's id, the key of the cookie notice's answer), `cards` (the store's card lookup for products without metadata), `currency` (the store's base currency, `null` while the visitor browses in another), `sdk` (the address it was imported from). Resolves once the page's work is set up. |
564
+
565
+ The storefront code of every module version is kept in
566
+ `test/fixtures/magento/<version>/` (`Block/Script.php` and the template;
567
+ 0.4.24: the last one holding its own page code), and
568
+ `test/magento_published.test.js` runs every case of `test/magento.test.js`
569
+ through each against the current `src/`: a change to that code needs a new
570
+ fixture, and a change to the served code must keep every older module working.
571
+
546
572
  ### Node
547
573
 
548
574
  ```js
@@ -1076,6 +1102,10 @@ minifier, to keep zero dev dependencies.
1076
1102
 
1077
1103
  ## Changes
1078
1104
 
1105
+ - 2026-11-20: version 0.13.0. `magento.js`, served beside `index.js` with
1106
+ its day of cache: the Magento module's storefront code (the rows, consent,
1107
+ the view and the add-to-cart events). The module now prints only the page's
1108
+ values, so later fixes reach a store with nothing to install again.
1079
1109
  - 2026-11-20: version 0.12.0. `woocommerce.js`, served beside `index.js`
1080
1110
  with its day of cache: the WooCommerce plugin's page code (the rows,
1081
1111
  consent, cart and purchase events). The plugin now prints only the page's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Browser and Node client for the recapi recommendation API: local decayed history, event batching, attribution.",
5
5
  "homepage": "https://recapi.io/docs",
6
6
  "bugs": {
package/src/magento.js ADDED
@@ -0,0 +1,262 @@
1
+ /**
2
+ * What a Magento store's pages run: the visitor's consent (Cookie Restriction
3
+ * Mode), the add-to-cart events, the product view and the rows in
4
+ * `#recapi-recommendations` and `#recapi-bought-together`. The module's
5
+ * template (sdk/php/magento/view/frontend/templates/script.phtml) prints only
6
+ * what Magento knows about the page and imports this file from the API, on
7
+ * Luma and on Hyvä alike, so a fix here reaches every store within a day (the
8
+ * entry's cache), with nothing to install again. Its options are a contract:
9
+ * add, never rename or drop one (each published module's storefront code is a
10
+ * test fixture, test/fixtures/magento/).
11
+ *
12
+ * A file of its own rather than exports of index.js, which every other site
13
+ * loads: they would download a Magento row they never draw.
14
+ *
15
+ * @module @recapi/client/magento
16
+ */
17
+
18
+ import { createClient } from './index.js';
19
+
20
+ /**
21
+ * Runs a page of the store. Resolves once the page's work is set up (the row
22
+ * loads later, as the shopper scrolls near it, or at once without
23
+ * IntersectionObserver).
24
+ *
25
+ * @param {{ api: string, key: string, platform: string, product: string|null,
26
+ * placement: string, cookieRestriction: boolean, website: string,
27
+ * cards: string, currency: string|null }} page
28
+ */
29
+ export async function magentoPage(page) {
30
+ // The server sends the orders and can't read the browser's storage: each
31
+ // time the library saves the visitor's state, the "recapi" cookie gets what
32
+ // a purchase needs, the visitor's id and the recommendation each clicked
33
+ // product came from (the saved list entries that have a click time). The
34
+ // library saves only with consent. A day, as long as the library credits a
35
+ // click.
36
+ const secure = location.protocol === 'https:' ? '; secure' : '';
37
+ const cookie = (value, maxAge) => {
38
+ document.cookie = `recapi=${value}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
39
+ };
40
+ const mirror = (saved) => {
41
+ let state;
42
+ try {
43
+ state = JSON.parse(saved);
44
+ } catch {
45
+ return;
46
+ }
47
+ if (typeof state?.anonId !== 'string') return;
48
+ const clicked = (Array.isArray(state.shown) ? state.shown : []).filter((entry) => Array.isArray(entry) && entry.length >= 4);
49
+ // A browser drops a cookie over 4 KB: the products shown last stay.
50
+ let value;
51
+ do {
52
+ value = encodeURIComponent(JSON.stringify({ anon: state.anonId, recs: Object.fromEntries(clicked.map(([item, rec]) => [item, rec])) }));
53
+ } while (value.length > 3000 && clicked.shift());
54
+ cookie(value, 86400);
55
+ };
56
+ const storage = {
57
+ getItem: (key) => localStorage.getItem(key),
58
+ setItem: (key, value) => {
59
+ localStorage.setItem(key, value);
60
+ mirror(value);
61
+ },
62
+ removeItem: (key) => localStorage.removeItem(key)
63
+ };
64
+
65
+ // Magento's Cookie Restriction Mode is the store's consent switch: on, the
66
+ // visitor's device keeps nothing until they accept the cookie notice, which
67
+ // writes {"<website id>": 1} into user_allowed_save_cookie. Without consent
68
+ // events still go out, without a visitor id.
69
+ const allowed = () => {
70
+ if (!page.cookieRestriction) return true;
71
+ const raw = /(?:^|;\s*)user_allowed_save_cookie=([^;]*)/.exec(document.cookie)?.[1];
72
+ try {
73
+ return JSON.parse(decodeURIComponent(raw))[page.website] === 1;
74
+ } catch {
75
+ return false;
76
+ }
77
+ };
78
+ const consent = allowed();
79
+ const recapi = createClient({ apiKey: page.key, baseUrl: page.api, consent, storage, platform: page.platform });
80
+ // A visitor who took their consent back (deleted the notice's cookie) leaves
81
+ // no ids for their next order.
82
+ if (!consent && /(?:^|;\s*)recapi=/.test(document.cookie)) cookie('', 0);
83
+
84
+ // Luma and its children announce through jQuery, which RequireJS loads:
85
+ // the cookie notice's accept and the Ajax add to cart, with its products.
86
+ const jquery = (use) => {
87
+ if (typeof window.require === 'function') window.require(['jquery'], use);
88
+ else if (window.jQuery) use(window.jQuery);
89
+ };
90
+ jquery(($) => {
91
+ $(document).on('user:allowed:save:cookie', () => recapi.setConsent(allowed()));
92
+ $(document).on('ajax:addToCart', (event, data) => {
93
+ for (const id of data?.productIds ?? []) if (id) recapi.track(String(id), 'cart');
94
+ });
95
+ });
96
+ // Hyvä's cookie notice announces the accept on the window instead: the
97
+ // consent applies on the same page there too, not only from the next one.
98
+ window.addEventListener('user-allowed-save-cookie', () => recapi.setConsent(allowed()));
99
+ // Themes without jQuery (Hyvä) post the add-to-cart form, and the next page
100
+ // loads: counted at the submit, once no script stopped it for an Ajax call.
101
+ // Window listeners run last, so defaultPrevented is final here.
102
+ window.addEventListener('submit', (event) => {
103
+ const form = event.target;
104
+ if (event.defaultPrevented || !/\/checkout\/cart\/add\b/.test(form?.action ?? '')) return;
105
+ const id = form.querySelector?.('[name="product"]')?.value;
106
+ if (id) recapi.track(String(id), 'cart');
107
+ });
108
+
109
+ // The product id is the item id. A card's link carries its recommendation:
110
+ // without consent nothing on the device remembers which list showed it. In the
111
+ // fragment, which no server or page cache sees: an unknown ?rec= gave every
112
+ // click from the row its own entry in the full-page cache. ?rec= is still read:
113
+ // links already out there, and the cards that can't use a fragment (below).
114
+ const inFragment = /^#rec_[0-9a-f]+$/;
115
+ const viewed = () => {
116
+ const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
117
+ const linked = fragment ?? new URLSearchParams(location.search).get('rec');
118
+ recapi.track(page.product, 'view', { recommendationId: linked });
119
+ // recapi credits an explicit id to whoever brings it: drop it from the
120
+ // address so a copied or shared link doesn't credit strangers' visits.
121
+ if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
122
+ else if (linked !== null) {
123
+ const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
124
+ history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
125
+ }
126
+ };
127
+ // A browser may preload the link under the pointer, and a page it prerenders
128
+ // runs this script though nobody may ever open it: a click nobody made must
129
+ // not be credited.
130
+ if (page.product && document.prerendering) document.addEventListener('prerenderingchange', viewed);
131
+ else if (page.product) viewed();
132
+
133
+ // recapi's row (the product page's recommendations block) arrives printed
134
+ // with the store's own products in it: recapi's cards replace them when it
135
+ // has some to show, else they stay. A product page has a second row under it,
136
+ // "Often bought together" (unless the store turned it off), printed hidden
137
+ // and empty: it shows only once recapi has products for it.
138
+ const slot = document.getElementById('recapi-recommendations');
139
+ const together = page.product ? document.getElementById('recapi-bought-together') : null;
140
+ const rows = [
141
+ { slot, placement: page.placement },
142
+ ...(slot && together ? [{ slot: together, placement: 'bought_together', together: true }] : [])
143
+ ];
144
+ const blockOf = (element) => element.closest?.('.recapi-recommendations') ?? element;
145
+ const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
146
+ // Only http(s) addresses: metadata is the shop's, but a javascript: link
147
+ // must never reach the page.
148
+ const web = (address) => {
149
+ try {
150
+ const url = new URL(address, location.href);
151
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
152
+ } catch {
153
+ return null;
154
+ }
155
+ };
156
+ const lang = document.documentElement?.lang || undefined;
157
+ const money = (amount) => {
158
+ if (typeof amount === 'string') return amount;
159
+ if (typeof amount !== 'number' || !Number.isFinite(amount) || !page.currency) return null;
160
+ try {
161
+ return new Intl.NumberFormat(lang, { style: 'currency', currency: page.currency }).format(amount);
162
+ } catch {
163
+ return null;
164
+ }
165
+ };
166
+ // An item's metadata draws its card when it has a name and a link (and a
167
+ // price the visitor's currency can show); the others come from the store.
168
+ const fromMetadata = (metadata) => {
169
+ if (typeof metadata?.name !== 'string' || typeof metadata.url !== 'string' || !web(metadata.url)) return null;
170
+ const price = metadata.price === undefined || metadata.price === null ? '' : money(metadata.price);
171
+ if (price === null) return null;
172
+ return { name: metadata.name, url: metadata.url, picture: typeof metadata.picture === 'string' ? metadata.picture : '', price };
173
+ };
174
+ // A row shows 4 cards. recapi counts every product of a list as shown, so
175
+ // a spare asked for would get an impression and could be credited a view it
176
+ // never caused: each row asks for 4. recapi may not know a product sold out
177
+ // or was disabled since the last sync; one more call, for the rows left
178
+ // short only and without the products already listed, then fills the gaps.
179
+ const ROW = 4;
180
+ // Through the call that takes all of a page's rows: billed as one, the
181
+ // history sent once, and no product on two rows (the first row's go first).
182
+ // Each row its own placement.
183
+ const ask = (wanted, exclude) => recapi.recommendLists({
184
+ lists: wanted.map(({ count, placement }) => ({ count, placement, ...(page.product ? { contextItemId: page.product } : {}) })),
185
+ ...(exclude.length ? { exclude } : {})
186
+ });
187
+ // A list's cards, in recapi's order, each with the list's id: those whose
188
+ // metadata draws them, the others from the store in one request.
189
+ const cardsOf = async ({ recommendationId, items }) => {
190
+ const cards = new Map(items.map(({ itemId, metadata }) => [itemId, fromMetadata(metadata)]));
191
+ const missing = [...cards].filter(([id, card]) => !card && /^\d+$/.test(id)).map(([id]) => id);
192
+ if (missing.length) {
193
+ const url = new URL(page.cards, location.href);
194
+ url.searchParams.set('ids', missing.join(','));
195
+ const response = await fetch(url.href, { headers: { Accept: 'application/json' } }).catch(() => null);
196
+ const found = (response?.ok ? await response.json().catch(() => null) : null)?.cards;
197
+ for (const card of Array.isArray(found) ? found : []) if (cards.has(String(card?.id))) cards.set(String(card.id), card);
198
+ }
199
+ return [...cards.values()].filter((card) => card && web(card.url)).map((card) => ({ ...card, recommendationId }));
200
+ };
201
+ const html = (cards) => cards.slice(0, ROW).map(({ recommendationId, ...card }) => {
202
+ const link = web(card.url);
203
+ // ?rec= only where a fragment can't carry the id: the address has its own
204
+ // (a theme's, not ours to overwrite), it's the page already open (a
205
+ // fragment wouldn't load it, so no view), or the page wouldn't read it back.
206
+ const open = link.href.split('#')[0] === location.href.split('#')[0];
207
+ if (recommendationId && (link.hash || open || !inFragment.test(`#${recommendationId}`))) link.searchParams.set('rec', recommendationId);
208
+ else if (recommendationId) link.hash = recommendationId;
209
+ const picture = web(card.picture);
210
+ return `<a href="${escape(link.href)}">${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}` +
211
+ `<span>${escape(card.name)}</span>${card.price ? `<span class="recapi-price">${escape(card.price)}</span>` : ''}</a>`;
212
+ });
213
+ // Each row's cards, drawn as far as recapi got: a row never waits on, nor
214
+ // loses its cards to, the other row or a later call.
215
+ const draw = async () => {
216
+ const lists = await ask(rows.map(({ placement }) => ({ count: ROW, placement })), []);
217
+ // Popular items (recapi slow, down or at a limit) are no bought-together row.
218
+ const cards = await Promise.all(lists.map((list, i) => (rows[i].together && list.fallback ? [] : cardsOf(list))));
219
+ // Only a full list that couldn't fill its row: a shorter one means recapi
220
+ // has no more to give, and a fallback would only wait again.
221
+ const short = rows.map((row, i) => i).filter((i) => cards[i].length < ROW && lists[i].items.length >= ROW && !lists[i].fallback);
222
+ if (short.length) {
223
+ try {
224
+ const more = await ask(short.map((i) => ({ count: ROW - cards[i].length, placement: rows[i].placement })),
225
+ lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)));
226
+ const extra = await Promise.all(more.map(cardsOf));
227
+ short.forEach((i, k) => cards[i].push(...extra[k]));
228
+ } catch (error) {
229
+ // Rejected (a key revoked mid-page): the cards of the first call stay.
230
+ console.warn('recapi:', error);
231
+ }
232
+ }
233
+ rows.forEach((row, i) => {
234
+ const drawn = html(cards[i]);
235
+ if (drawn.length) {
236
+ row.slot.innerHTML = drawn.join('');
237
+ blockOf(row.slot).hidden = false;
238
+ }
239
+ });
240
+ };
241
+ // A row with no card at all (no store product either) hides, title included.
242
+ // A rejected request (a revoked key: recapi's own error) keeps the store's.
243
+ const fill = async () => {
244
+ await draw().catch(() => 0);
245
+ for (const row of rows) if (!row.slot.children.length) blockOf(row.slot).hidden = true;
246
+ };
247
+ // Only once the row comes within 400px of the screen, as Magento's lazy
248
+ // images load: each list is billed and counted as shown, and a shopper who
249
+ // never scrolls down saw none. The view above went at once. The block is
250
+ // watched, not the cards' div: with no store product that div is empty, and
251
+ // a theme hiding every empty div (div:empty { display: none }, Dawn's rule)
252
+ // would leave nothing to come near the screen; the block has its title.
253
+ if (slot && typeof IntersectionObserver !== 'function') await fill();
254
+ else if (slot) {
255
+ const observer = new IntersectionObserver((entries) => {
256
+ if (!entries.some((entry) => entry.isIntersecting)) return undefined;
257
+ observer.disconnect();
258
+ return fill();
259
+ }, { rootMargin: '0px 0px 400px 0px' });
260
+ observer.observe(blockOf(slot));
261
+ }
262
+ }