@recapi/client 0.11.1 → 0.12.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 +35 -1
- package/index.d.ts +3 -1
- package/package.json +1 -1
- package/src/transport.js +11 -4
- package/src/woocommerce.js +334 -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.12.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).
|
|
@@ -508,6 +508,30 @@ nothing, and can't show what WordPress.org would do with a same-named listing.
|
|
|
508
508
|
Nothing answers that filter yet, so a shop gets no update notice. A snippet
|
|
509
509
|
install has neither header's effect: both are comments there.
|
|
510
510
|
|
|
511
|
+
#### The served page code
|
|
512
|
+
|
|
513
|
+
From 0.12.0 the plugin's page script holds only what PHP knows about the page
|
|
514
|
+
and the shop's key: it imports `/sdk/<version>/woocommerce.js` from your API
|
|
515
|
+
and makes one call. The API serves that file beside `index.js`, with the same
|
|
516
|
+
day of cache, and an older version's address redirects to it. So a fix of the
|
|
517
|
+
row, consent or the events reaches every shop within a day, with nothing to
|
|
518
|
+
install again. A fix of the plugin's PHP (product sync, paid orders, settings)
|
|
519
|
+
still needs the new file.
|
|
520
|
+
|
|
521
|
+
The call and its options are a contract from 0.12.0 on: options may be added,
|
|
522
|
+
never renamed or dropped, as shops keep the plugin they installed.
|
|
523
|
+
|
|
524
|
+
| Call | Options |
|
|
525
|
+
|---|---|
|
|
526
|
+
| `woocommercePage(options)` | `apiKey`, `baseUrl`, `platform`; `page`, as PHP prints it: `products` (the Store API's products address), `product` (the product page's id, `null` elsewhere), `placement` (`product`, `cart` or `shortcode`), `heading` (the row's title, `null` for none), `together` (the second row's title, `null` when turned off), `orders` (`true` with a secret key: keep the `recapi` cookie), `consent` (`wp-consent-api`, `banner` or `no-banner`), `currency` (the shop's, `null` while the visitor browses in another), `order` (`items` and `customer` on the order-received page, else `null`). Resolves once the page's work is set up. |
|
|
527
|
+
|
|
528
|
+
Every plugin the quick start ever printed is kept in
|
|
529
|
+
`test/fixtures/woocommerce/<version>/` (0.11.2: the last one holding its own
|
|
530
|
+
page code), and `test/woocommerce_published.test.js` runs every case of
|
|
531
|
+
`test/woocommerce.test.js` through each against the current `src/`: a change
|
|
532
|
+
to the page script needs a new fixture, and a change to the served code must
|
|
533
|
+
keep every older plugin working.
|
|
534
|
+
|
|
511
535
|
### Magento
|
|
512
536
|
|
|
513
537
|
The Magento 2 module ([guide](https://recapi.io/docs/magento)) prints
|
|
@@ -758,6 +782,10 @@ transient failures apart. `recommend()` and `popular()` resolve with a
|
|
|
758
782
|
list instead of rejecting on `network`, `timeout`, 5xx, 429, 401 and 403
|
|
759
783
|
errors, and report the error to `onError` (see [Fallback](#fallback)).
|
|
760
784
|
|
|
785
|
+
An API error also carries `docsUrl`, the address of its section on the
|
|
786
|
+
errors page, and its `message` ends with it, so the console line is a link
|
|
787
|
+
(absent from an older server and on client codes).
|
|
788
|
+
|
|
761
789
|
Each error code, its cause and its fix: [Errors](https://recapi.io/docs/errors).
|
|
762
790
|
No lists yet, empty lists, only popular items, key errors: [Troubleshooting](https://recapi.io/docs/troubleshooting).
|
|
763
791
|
Shops: the [Shopify](https://recapi.io/docs/shopify), [WooCommerce](https://recapi.io/docs/woocommerce) and [Magento](https://recapi.io/docs/magento) guides.
|
|
@@ -1048,6 +1076,12 @@ minifier, to keep zero dev dependencies.
|
|
|
1048
1076
|
|
|
1049
1077
|
## Changes
|
|
1050
1078
|
|
|
1079
|
+
- 2026-11-20: version 0.12.0. `woocommerce.js`, served beside `index.js`
|
|
1080
|
+
with its day of cache: the WooCommerce plugin's page code (the rows,
|
|
1081
|
+
consent, cart and purchase events). The plugin now prints only the page's
|
|
1082
|
+
values, so later fixes reach a shop with nothing to install again.
|
|
1083
|
+
- 2026-11-19: version 0.11.2. An API error's `docsUrl` is the address of
|
|
1084
|
+
its section on the errors page, and its message ends with it.
|
|
1051
1085
|
- 2026-11-19: version 0.11.1. No code change: this page's links lead to
|
|
1052
1086
|
the public docs, and an errors section names the errors and
|
|
1053
1087
|
troubleshooting pages.
|
package/index.d.ts
CHANGED
|
@@ -192,7 +192,7 @@ export class RecapiError extends Error {
|
|
|
192
192
|
constructor(
|
|
193
193
|
code: string,
|
|
194
194
|
message: string,
|
|
195
|
-
extra?: { status?: number; retryAfterMs?: number; details?: unknown; cause?: unknown }
|
|
195
|
+
extra?: { status?: number; retryAfterMs?: number; details?: unknown; cause?: unknown; docsUrl?: string }
|
|
196
196
|
);
|
|
197
197
|
readonly name: 'RecapiError';
|
|
198
198
|
/** API code (`invalid_request`, `rate_limited`, …) or client code (`network`, `timeout`, `invalid_response`, `event_rejected`, `queue_overflow`). */
|
|
@@ -201,6 +201,8 @@ export class RecapiError extends Error {
|
|
|
201
201
|
status: number;
|
|
202
202
|
retryAfterMs?: number;
|
|
203
203
|
details?: unknown;
|
|
204
|
+
/** The errors page's section for this code, sent by the API (absent from older servers and on client codes). `message` ends with it. */
|
|
205
|
+
docsUrl?: string;
|
|
204
206
|
readonly retryable: boolean;
|
|
205
207
|
}
|
|
206
208
|
|
package/package.json
CHANGED
package/src/transport.js
CHANGED
|
@@ -38,15 +38,19 @@ export class RecapiError extends Error {
|
|
|
38
38
|
* or a client code (`network`, `timeout`, `invalid_response`,
|
|
39
39
|
* `event_rejected`, `queue_overflow`).
|
|
40
40
|
* @param {string} message
|
|
41
|
-
* @param {{ status?: number, retryAfterMs?: number, details?: unknown, cause?: unknown }} [extra]
|
|
41
|
+
* @param {{ status?: number, retryAfterMs?: number, details?: unknown, cause?: unknown, docsUrl?: string }} [extra]
|
|
42
42
|
*/
|
|
43
|
-
constructor(code, message, { status = 0, retryAfterMs, details, cause } = {}) {
|
|
44
|
-
|
|
43
|
+
constructor(code, message, { status = 0, retryAfterMs, details, cause, docsUrl } = {}) {
|
|
44
|
+
// The address ends the message: a browser console makes it a link in
|
|
45
|
+
// the line the error prints, and an onError that logs message gets it too.
|
|
46
|
+
super(docsUrl ? `${message}, see ${docsUrl}` : message, cause === undefined ? undefined : { cause });
|
|
45
47
|
this.name = 'RecapiError';
|
|
46
48
|
this.code = code;
|
|
47
49
|
this.status = status;
|
|
48
50
|
this.retryAfterMs = retryAfterMs;
|
|
49
51
|
this.details = details;
|
|
52
|
+
/** The errors page's section for this code, from the API's body; undefined when it sent none. */
|
|
53
|
+
this.docsUrl = docsUrl || undefined;
|
|
50
54
|
}
|
|
51
55
|
|
|
52
56
|
/**
|
|
@@ -162,7 +166,10 @@ function httpError(response, json) {
|
|
|
162
166
|
const status = response.status;
|
|
163
167
|
const code = json?.error?.code || CODE_BY_STATUS[status] || (status >= 500 ? 'internal' : 'http_error');
|
|
164
168
|
const message = json?.error?.message || `HTTP ${status}`;
|
|
165
|
-
|
|
169
|
+
// Only a string: an older server sends none, and a proxy's odd body must
|
|
170
|
+
// not put an object in the message.
|
|
171
|
+
const docsUrl = typeof json?.error?.docs_url === 'string' ? json.error.docs_url : undefined;
|
|
172
|
+
return new RecapiError(code, message, { status, retryAfterMs: retryAfter(response), docsUrl });
|
|
166
173
|
}
|
|
167
174
|
|
|
168
175
|
function retryAfter(response) {
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a WooCommerce shop's pages run: the visitor's consent, the cart and
|
|
3
|
+
* purchase events, and the rows in `#recapi-recommendations`. The plugin
|
|
4
|
+
* (sdk/js/woocommerce/recapi.php) prints only what PHP knows about the page
|
|
5
|
+
* and imports this file from the API, so a fix here reaches every shop
|
|
6
|
+
* within a day (the entry's cache), with nothing to install again. Its
|
|
7
|
+
* options are a contract: add, never rename or drop one (each published
|
|
8
|
+
* plugin is a test fixture, test/fixtures/woocommerce/).
|
|
9
|
+
*
|
|
10
|
+
* A file of its own rather than exports of index.js, which every other site
|
|
11
|
+
* loads: they would download a WooCommerce row they never draw.
|
|
12
|
+
*
|
|
13
|
+
* @module @recapi/client/woocommerce
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { createClient } from './index.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Runs a page of the shop. Resolves once the page's work is set up (the row
|
|
20
|
+
* loads later, as the shopper scrolls near it, or at once without
|
|
21
|
+
* IntersectionObserver).
|
|
22
|
+
*
|
|
23
|
+
* @param {{ apiKey: string, baseUrl: string, platform: string, page: {
|
|
24
|
+
* products: string, product: string|null, placement: string,
|
|
25
|
+
* heading?: string|null, together?: string|null, orders?: boolean,
|
|
26
|
+
* consent: 'wp-consent-api'|'banner'|'no-banner'|string,
|
|
27
|
+
* currency?: string|null,
|
|
28
|
+
* order?: { items: string[], customer: string|null }|null } }} options
|
|
29
|
+
*/
|
|
30
|
+
export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
31
|
+
// recapi keeps a history on the visitor's device only with their consent,
|
|
32
|
+
// and the merchant says on WooCommerce → recapi where it comes from. The WP
|
|
33
|
+
// Consent API (wordpress.org/plugins/wp-consent-api) carries the answer of
|
|
34
|
+
// the shop's cookie banner (Complianz, CookieYes…): Statistics consent. With
|
|
35
|
+
// the API but no banner it reports allowed; without the API nothing is
|
|
36
|
+
// stored, and events go out without a visitor id. Another banner calls
|
|
37
|
+
// recapi.setConsent(), maybe before this module ran: the head's stand-in
|
|
38
|
+
// kept its answer. A shop that needs no banner has consent from the start.
|
|
39
|
+
const answered = window.recapi?.consent;
|
|
40
|
+
const consent = page.consent === 'no-banner'
|
|
41
|
+
|| (page.consent === 'banner' && answered === true)
|
|
42
|
+
|| (page.consent === 'wp-consent-api' && typeof window.wp_has_consent === 'function' && window.wp_has_consent('statistics') === true);
|
|
43
|
+
// With a secret key the server sends the order once paid (the buyer may
|
|
44
|
+
// never see the order-received page) and can't read the browser's storage:
|
|
45
|
+
// each time the library saves the visitor's state, which it does only with
|
|
46
|
+
// consent, the "recapi" cookie gets what a purchase needs, the visitor's id
|
|
47
|
+
// and the recommendation each clicked product came from (the saved list
|
|
48
|
+
// entries with a click time). A day, as long as the library credits a click.
|
|
49
|
+
const secure = location.protocol === 'https:' ? '; secure' : '';
|
|
50
|
+
const cookie = (value, maxAge) => {
|
|
51
|
+
document.cookie = `recapi=${value}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
|
|
52
|
+
};
|
|
53
|
+
const mirror = (saved) => {
|
|
54
|
+
let state;
|
|
55
|
+
try {
|
|
56
|
+
state = JSON.parse(saved);
|
|
57
|
+
} catch {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (typeof state?.anonId !== 'string') return;
|
|
61
|
+
const clicked = (Array.isArray(state.shown) ? state.shown : []).filter((entry) => Array.isArray(entry) && entry.length >= 4);
|
|
62
|
+
// A browser drops a cookie over 4 KB: the products shown last stay.
|
|
63
|
+
let value;
|
|
64
|
+
do {
|
|
65
|
+
value = encodeURIComponent(JSON.stringify({ anon: state.anonId, recs: Object.fromEntries(clicked.map(([item, rec]) => [item, rec])) }));
|
|
66
|
+
} while (value.length > 3000 && clicked.shift());
|
|
67
|
+
cookie(value, 86400);
|
|
68
|
+
};
|
|
69
|
+
const storage = page.orders ? {
|
|
70
|
+
getItem: (key) => localStorage.getItem(key),
|
|
71
|
+
// The cookie first: a full storage quota throws, and the order still
|
|
72
|
+
// needs it.
|
|
73
|
+
setItem: (key, value) => {
|
|
74
|
+
mirror(value);
|
|
75
|
+
localStorage.setItem(key, value);
|
|
76
|
+
},
|
|
77
|
+
removeItem: (key) => {
|
|
78
|
+
localStorage.removeItem(key);
|
|
79
|
+
cookie('', 0);
|
|
80
|
+
}
|
|
81
|
+
} : undefined;
|
|
82
|
+
const recapi = createClient({ apiKey, baseUrl, consent, storage, platform });
|
|
83
|
+
// A visitor without consent (or who took it back) leaves no ids for their
|
|
84
|
+
// next order.
|
|
85
|
+
if (page.orders && !consent && /(?:^|;\s*)recapi=/.test(document.cookie ?? '')) cookie('', 0);
|
|
86
|
+
window.recapi = { setConsent: (value) => recapi.setConsent(value === true) };
|
|
87
|
+
if (page.consent === 'wp-consent-api') {
|
|
88
|
+
document.addEventListener('wp_listen_for_consent_change', (event) => {
|
|
89
|
+
const answer = event.detail?.statistics;
|
|
90
|
+
if (answer === 'allow' || answer === 'deny') recapi.setConsent(answer === 'allow');
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// An add to cart reports its product in three ways: the classic product
|
|
95
|
+
// page posts its form (the page then reloads: count it now), an Ajax button
|
|
96
|
+
// (shop pages, some themes) fires jQuery's added_to_cart, and a block's
|
|
97
|
+
// button fires wc-blocks_added_to_cart, with no product. A button carries
|
|
98
|
+
// its product in data-product_id. One click may fire both events: it
|
|
99
|
+
// counts once.
|
|
100
|
+
let clicked = null;
|
|
101
|
+
const added = () => {
|
|
102
|
+
if (clicked) recapi.track(clicked, 'cart');
|
|
103
|
+
clicked = null;
|
|
104
|
+
};
|
|
105
|
+
document.addEventListener('click', (event) => {
|
|
106
|
+
const id = event.target?.closest?.('[data-product_id]')?.getAttribute('data-product_id');
|
|
107
|
+
if (id) clicked = id;
|
|
108
|
+
}, true);
|
|
109
|
+
document.addEventListener('submit', (event) => {
|
|
110
|
+
const form = event.target;
|
|
111
|
+
const id = event.submitter?.name === 'add-to-cart' ? event.submitter.value : form?.querySelector?.('[name="add-to-cart"]')?.value;
|
|
112
|
+
if (!id) return;
|
|
113
|
+
clicked = id;
|
|
114
|
+
added();
|
|
115
|
+
}, true);
|
|
116
|
+
window.jQuery?.(document.body).on('added_to_cart', added);
|
|
117
|
+
document.body?.addEventListener('wc-blocks_added_to_cart', added);
|
|
118
|
+
|
|
119
|
+
// The product id is the item id: the widget loads products by it. A
|
|
120
|
+
// card's link carries its recommendation: without consent nothing on the
|
|
121
|
+
// device remembers which list showed the product. In the fragment, which no
|
|
122
|
+
// server or page cache sees: an unknown ?rec= made every click from the row
|
|
123
|
+
// miss the shop's page cache. ?rec= is still read: links already out there,
|
|
124
|
+
// and the cards that can't use a fragment (below).
|
|
125
|
+
const inFragment = /^#rec_[0-9a-f]+$/;
|
|
126
|
+
const viewed = () => {
|
|
127
|
+
const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
|
|
128
|
+
const linked = fragment ?? new URLSearchParams(location.search).get('rec');
|
|
129
|
+
recapi.track(page.product, 'view', { recommendationId: linked });
|
|
130
|
+
// recapi credits an explicit id to whoever brings it: drop it from the
|
|
131
|
+
// address so a copied or shared link doesn't credit strangers' visits.
|
|
132
|
+
if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
|
|
133
|
+
else if (linked !== null) {
|
|
134
|
+
const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
|
|
135
|
+
history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
// A browser may preload the link under the pointer, and a page it prerenders
|
|
139
|
+
// runs this script though nobody may ever open it: a click nobody made must
|
|
140
|
+
// not be credited.
|
|
141
|
+
if (page.product && document.prerendering) document.addEventListener('prerenderingchange', viewed);
|
|
142
|
+
else if (page.product) viewed();
|
|
143
|
+
|
|
144
|
+
// The checkout is the shop's own page, so the purchases find the visitor
|
|
145
|
+
// and the recommendations they clicked where the product pages left them.
|
|
146
|
+
if (page.order) {
|
|
147
|
+
if (page.order.customer) recapi.identify(page.order.customer);
|
|
148
|
+
for (const item of page.order.items) recapi.track(item, 'purchase');
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Fills <div id="recapi-recommendations"></div>. A merchant who pasted one
|
|
152
|
+
// before the plugin printed its own would see an empty second row: the
|
|
153
|
+
// first is filled, the others removed. Not hidden: the cards' grid rule
|
|
154
|
+
// below matches every slot and beats the browser's [hidden] rule.
|
|
155
|
+
const [slot, ...others] = document.querySelectorAll('#recapi-recommendations');
|
|
156
|
+
for (const other of others) other.remove();
|
|
157
|
+
// Not only [hidden]: any display rule of the theme's beats that one, and
|
|
158
|
+
// would leave the slot's 320px blank.
|
|
159
|
+
const hide = () => {
|
|
160
|
+
slot.hidden = true;
|
|
161
|
+
slot.style.setProperty('display', 'none', 'important');
|
|
162
|
+
};
|
|
163
|
+
// A product row in the theme's colours and fonts. :where() weighs
|
|
164
|
+
// nothing, so any rule of the theme's restyles the cards.
|
|
165
|
+
const style = '<style>' +
|
|
166
|
+
':where(#recapi-recommendations){display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:1rem;align-items:start;align-content:start}' +
|
|
167
|
+
':where(#recapi-recommendations a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}' +
|
|
168
|
+
':where(#recapi-recommendations img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}' +
|
|
169
|
+
':where(#recapi-recommendations .recapi-price){font-weight:600}' +
|
|
170
|
+
'</style>';
|
|
171
|
+
// A theme that hides every empty div (div:empty { display: none }, Dawn's
|
|
172
|
+
// rule) hides a slot pasted empty: it would never come near the screen
|
|
173
|
+
// and the row would never load. Its style, there at once, makes it not
|
|
174
|
+
// empty. A slot still without a box is hidden by the theme or a block
|
|
175
|
+
// around it: the row loads if that changes, and the console says why.
|
|
176
|
+
if (slot && !slot.getClientRects().length) {
|
|
177
|
+
slot.insertAdjacentHTML('afterbegin', style);
|
|
178
|
+
if (!slot.getClientRects().length) console.warn('recapi: the page hides #recapi-recommendations (display: none), so the row loads only once it shows');
|
|
179
|
+
}
|
|
180
|
+
// Each row shows 4 cards. recapi counts every product of a list as shown,
|
|
181
|
+
// so a spare asked for would get an impression and could be credited a
|
|
182
|
+
// view it never caused: a row asks for 4. Without a secret key recapi
|
|
183
|
+
// may not know a product sold out or was deleted; one more call, for the
|
|
184
|
+
// rows short of cards and without the products already listed, then
|
|
185
|
+
// fills the gaps.
|
|
186
|
+
const ROW = 4;
|
|
187
|
+
// A product page has a second row, bought together, which the script
|
|
188
|
+
// adds under the first once it has cards: the printed page stays the same
|
|
189
|
+
// for every shop and every page cache, and an empty row leaves nothing.
|
|
190
|
+
const TOGETHER = 'recapi-bought-together';
|
|
191
|
+
const rows = [{ placement: page.placement, heading: page.heading }];
|
|
192
|
+
if (page.product && page.together !== null) rows.push({ placement: 'bought_together', heading: page.together });
|
|
193
|
+
// Through the call that takes all of a page's rows (billed as one, the
|
|
194
|
+
// history sent once, no product on two rows): the first row first, so a
|
|
195
|
+
// product both would list stays on it. Each row under its own placement.
|
|
196
|
+
const ask = (wanted, exclude) => recapi.recommendLists({
|
|
197
|
+
lists: wanted.map(([row, count]) => ({ count, placement: row.placement, ...(page.product ? { contextItemId: page.product } : {}) })),
|
|
198
|
+
...(exclude.length ? { exclude } : {})
|
|
199
|
+
});
|
|
200
|
+
const draw = async () => {
|
|
201
|
+
const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
202
|
+
// Only http(s) addresses: metadata is the shop's, but a javascript: link
|
|
203
|
+
// must never reach the page.
|
|
204
|
+
const web = (address) => {
|
|
205
|
+
try {
|
|
206
|
+
const url = new URL(address, location.href);
|
|
207
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
|
|
208
|
+
} catch {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
// ?rec= only where a fragment can't carry the id: the address has its own
|
|
213
|
+
// (a theme's, not ours to overwrite), it's the page already open (a
|
|
214
|
+
// fragment wouldn't load it, so no view), or the page wouldn't read it back.
|
|
215
|
+
const link = (address, recommendationId) => {
|
|
216
|
+
const url = web(address);
|
|
217
|
+
if (!url || !recommendationId) return url?.href ?? null;
|
|
218
|
+
const open = url.href.split('#')[0] === location.href.split('#')[0];
|
|
219
|
+
if (url.hash || open || !inFragment.test(`#${recommendationId}`)) url.searchParams.set('rec', recommendationId);
|
|
220
|
+
else url.hash = recommendationId;
|
|
221
|
+
return url.href;
|
|
222
|
+
};
|
|
223
|
+
const lang = document.documentElement?.lang;
|
|
224
|
+
const money = (amount, currency) => {
|
|
225
|
+
try {
|
|
226
|
+
if (!lang || !currency || !Number.isFinite(amount)) return '';
|
|
227
|
+
return `<span class="recapi-price">${escape(new Intl.NumberFormat(lang, { style: 'currency', currency }).format(amount))}</span>`;
|
|
228
|
+
} catch {
|
|
229
|
+
return '';
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
// A metadata card without a usable picture gets no image at all.
|
|
233
|
+
const card = (href, picture, name, price) =>
|
|
234
|
+
`<a href="${escape(href)}">${picture !== undefined ? `<img src="${escape(picture)}" alt="" loading="lazy">` : ''}<span>${escape(name)}</span>${price}</a>`;
|
|
235
|
+
// An item's metadata (sent with PUT /v1/items) draws its card when it has
|
|
236
|
+
// a name and a link, with no request to the shop. Its price is text shown
|
|
237
|
+
// as it is, or a number in the shop's currency: a visitor browsing in
|
|
238
|
+
// another one (a currency switcher) gets the Store API's price instead.
|
|
239
|
+
const fromMetadata = (metadata, recommendationId) => {
|
|
240
|
+
const href = typeof metadata?.url === 'string' && typeof metadata.name === 'string' ? link(metadata.url, recommendationId) : null;
|
|
241
|
+
if (!href) return null;
|
|
242
|
+
let price = '';
|
|
243
|
+
if (typeof metadata.price === 'string') price = `<span class="recapi-price">${escape(metadata.price)}</span>`;
|
|
244
|
+
else if (typeof metadata.price === 'number') {
|
|
245
|
+
if (!page.currency) return null;
|
|
246
|
+
price = money(metadata.price, page.currency);
|
|
247
|
+
}
|
|
248
|
+
const picture = typeof metadata.picture === 'string' ? web(metadata.picture) : null;
|
|
249
|
+
return card(href, picture?.href, metadata.name, price);
|
|
250
|
+
};
|
|
251
|
+
// Product names come as HTML (WordPress turns quotes into entities).
|
|
252
|
+
const text = (html) => String(html ?? '').replace(/<[^>]*>/g, '').replace(/&(#\d+|#x[0-9a-f]+|amp|lt|gt|quot);/gi, (entity, name) => {
|
|
253
|
+
const named = { amp: '&', lt: '<', gt: '>', quot: '"' }[name.toLowerCase()];
|
|
254
|
+
if (named) return named;
|
|
255
|
+
const code = name[1] === 'x' || name[1] === 'X' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
|
|
256
|
+
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity;
|
|
257
|
+
});
|
|
258
|
+
// Prices are in the currency's minor unit. A number and a symbol need
|
|
259
|
+
// no translation.
|
|
260
|
+
const price = ({ prices: p }) => money(Number(p?.price) / 10 ** p?.currency_minor_unit, p?.currency_code);
|
|
261
|
+
// A list's cards, in recapi's order: those whose metadata draws them, the
|
|
262
|
+
// others from WooCommerce's Store API (public, one request for all).
|
|
263
|
+
const cardsOf = async ({ recommendationId, items }) => {
|
|
264
|
+
const cards = new Map(items.map(({ itemId, metadata }) => [itemId, fromMetadata(metadata, recommendationId)]));
|
|
265
|
+
const ids = [...cards].filter(([id, html]) => !html && /^\d+$/.test(id)).map(([id]) => id);
|
|
266
|
+
let products = [];
|
|
267
|
+
if (ids.length) {
|
|
268
|
+
const url = new URL(page.products, location.href);
|
|
269
|
+
url.searchParams.set('include', ids.join(','));
|
|
270
|
+
url.searchParams.set('per_page', String(ids.length));
|
|
271
|
+
const response = await fetch(url.href).catch(() => null);
|
|
272
|
+
products = (response?.ok ? await response.json().catch(() => null) : null) ?? [];
|
|
273
|
+
}
|
|
274
|
+
for (const p of products) {
|
|
275
|
+
const href = link(p.permalink, recommendationId);
|
|
276
|
+
if (cards.has(String(p.id)) && p.is_purchasable && p.is_in_stock && href) {
|
|
277
|
+
cards.set(String(p.id), card(href, p.images?.[0]?.thumbnail || p.images?.[0]?.src || '', text(p.name), price(p)));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return [...cards.values()].filter(Boolean);
|
|
281
|
+
};
|
|
282
|
+
const lists = await ask(rows.map((row) => [row, ROW]), []);
|
|
283
|
+
const shown = await Promise.all(lists.map(cardsOf));
|
|
284
|
+
// Only a full list that couldn't fill its row: a shorter one means
|
|
285
|
+
// recapi has no more to give, and a fallback (recapi slow, down or at a
|
|
286
|
+
// limit) would only wait again.
|
|
287
|
+
const short = lists.flatMap((list, i) => (shown[i].length < ROW && list.items.length >= ROW && !list.fallback ? [i] : []));
|
|
288
|
+
if (short.length) {
|
|
289
|
+
// A refused top-up (a key revoked mid-page) costs the gaps, never the
|
|
290
|
+
// cards the first call already found.
|
|
291
|
+
try {
|
|
292
|
+
const more = await ask(short.map((i) => [rows[i], ROW - shown[i].length]), lists.flatMap((list) => list.items.map(({ itemId }) => itemId)));
|
|
293
|
+
const cards = await Promise.all(more.map(cardsOf));
|
|
294
|
+
short.forEach((row, k) => shown[row].push(...cards[k]));
|
|
295
|
+
} catch (error) {
|
|
296
|
+
console.warn('recapi:', error);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const [first, together] = shown.map((cards) => cards.slice(0, ROW));
|
|
300
|
+
// The theme's own h2 rule styles a heading. Added only once the cards
|
|
301
|
+
// are in, so a row that stays hidden leaves no title behind.
|
|
302
|
+
const heading = (text) => (text ? `<h2 class="recapi-heading">${escape(text)}</h2>` : '');
|
|
303
|
+
// One row empty never hides the other. A fallback (recapi slow, down or
|
|
304
|
+
// at a limit) is popular products, not what shoppers bought together:
|
|
305
|
+
// under that title it would mislead, so that row waits for the next page.
|
|
306
|
+
if (together?.length && !lists[1].fallback) {
|
|
307
|
+
slot.insertAdjacentHTML('afterend', `${heading(rows[1].heading)}<div id="${TOGETHER}">${style.replaceAll('recapi-recommendations', TOGETHER)}${together.join('')}</div>`);
|
|
308
|
+
}
|
|
309
|
+
if (first.length) {
|
|
310
|
+
slot.innerHTML = style + first.join('');
|
|
311
|
+
if (page.heading) slot.insertAdjacentHTML('beforebegin', heading(page.heading));
|
|
312
|
+
} else {
|
|
313
|
+
hide();
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
// recommendLists() rejects only on a bad request: a page still loses no more than its rows.
|
|
317
|
+
const fill = () => draw().catch((error) => {
|
|
318
|
+
hide();
|
|
319
|
+
console.warn('recapi:', error);
|
|
320
|
+
});
|
|
321
|
+
// Only once the row comes within 400px of the screen, as Shopify's themes
|
|
322
|
+
// load theirs: each list is billed and counted as shown, and a shopper who
|
|
323
|
+
// never scrolls down saw none. The slot's min-height holds its place
|
|
324
|
+
// meanwhile. The view above went at once.
|
|
325
|
+
if (slot && typeof IntersectionObserver !== 'function') await fill();
|
|
326
|
+
else if (slot) {
|
|
327
|
+
const observer = new IntersectionObserver((entries) => {
|
|
328
|
+
if (!entries.some((entry) => entry.isIntersecting)) return undefined;
|
|
329
|
+
observer.disconnect();
|
|
330
|
+
return fill();
|
|
331
|
+
}, { rootMargin: '0px 0px 400px 0px' });
|
|
332
|
+
observer.observe(slot);
|
|
333
|
+
}
|
|
334
|
+
}
|