@recapi/client 0.15.0 → 0.16.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 +25 -3
- package/index.d.ts +12 -3
- package/package.json +1 -1
- package/src/client.js +1 -1
- package/src/history.js +69 -23
- package/src/magento.js +15 -3
- package/src/shopify.js +26 -11
- package/src/woocommerce.js +17 -5
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.16.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).
|
|
@@ -185,7 +185,11 @@ nothing to paste again. A file of its own rather than more exports of
|
|
|
185
185
|
only the short rows, without any product either row listed. A refused top-up
|
|
186
186
|
(a key revoked mid-page) keeps the cards already drawn. The second row
|
|
187
187
|
never shows the popular fallback (recapi slow, down or at a limit): popular
|
|
188
|
-
items are not what was bought together.
|
|
188
|
+
items are not what was bought together. From 0.15.1 its title is drawn only
|
|
189
|
+
when one of the cards drawn (after unavailable products are dropped and the
|
|
190
|
+
top-up added) has `why: bought_together`; otherwise the cards show without
|
|
191
|
+
it, the wrapper's class gains `recapi-more` and a `margin-top` of the grid's
|
|
192
|
+
gap, so they read as more of the first row.
|
|
189
193
|
Each card shows the picture (resized by Shopify's
|
|
190
194
|
CDN with `?width=400`), the title and `price_min` formatted with
|
|
191
195
|
`Intl.NumberFormat` in `Shopify.currency.active` and the page's `lang`
|
|
@@ -384,6 +388,9 @@ the first row's div once it has cards: the printed page doesn't change,
|
|
|
384
388
|
and a row with nothing to show leaves nothing. One row empty never hides
|
|
385
389
|
the other. *WooCommerce → recapi* turns it off ("Your product pages",
|
|
386
390
|
option `recapi_bought_together`); the cart and shortcode rows never have it.
|
|
391
|
+
From 0.15.1 the heading is added only when one of the cards drawn has
|
|
392
|
+
`why: bought_together`; otherwise the cards show without it, a `margin-top`
|
|
393
|
+
of the grid's gap under the first row.
|
|
387
394
|
|
|
388
395
|
The widget fills it like the Shopify snippet's, once it nears the screen,
|
|
389
396
|
asking for the 4 products it shows (recapi counts every product of a list
|
|
@@ -541,7 +548,10 @@ mirrors the visitor's id and clicked recommendations into a first-party
|
|
|
541
548
|
cookie so the server's purchases are credited like the SDK's own. On product
|
|
542
549
|
pages it fills recapi's row, drawing each card from the item's `metadata`
|
|
543
550
|
or, without it, from the store; the row is printed with the store's own
|
|
544
|
-
products, which stay while recapi has none.
|
|
551
|
+
products, which stay while recapi has none. Its second row, "Often bought
|
|
552
|
+
together", is printed hidden and empty; from 0.15.1 the script removes that
|
|
553
|
+
block's `.block-title` when none of the cards drawn has
|
|
554
|
+
`why: bought_together`, so its cards read as more of the first row.
|
|
545
555
|
|
|
546
556
|
#### The served storefront code
|
|
547
557
|
|
|
@@ -1105,6 +1115,18 @@ minifier, to keep zero dev dependencies.
|
|
|
1105
1115
|
|
|
1106
1116
|
## Changes
|
|
1107
1117
|
|
|
1118
|
+
- 2026-11-22: version 0.16.0. Each history entry keeps the strongest level
|
|
1119
|
+
tracked on it since it started (a view, a cart, a purchase), sent as a
|
|
1120
|
+
fourth element of the entry when known, so a row can tell a product opened
|
|
1121
|
+
from one bought. A stored history gains a `maxLevel` list beside `top`; a
|
|
1122
|
+
history stored by an earlier version still loads.
|
|
1123
|
+
- 2026-11-22: version 0.15.1. Shopify, WooCommerce and Magento: a product
|
|
1124
|
+
page's second row prints "Often bought together" only when one of the
|
|
1125
|
+
cards it shows was carted or bought with the product on screen (`why:
|
|
1126
|
+
bought_together`); otherwise the same cards show without the title, as
|
|
1127
|
+
more of the row above. When recapi answers the second call (the one that
|
|
1128
|
+
fills cards a shop can't sell) with popular products, only the first row
|
|
1129
|
+
takes them: Often bought together keeps the cards it has.
|
|
1108
1130
|
- 2026-11-22: version 0.15.0. `track()` takes a purchase's `value` and
|
|
1109
1131
|
`currency`, sent with the event for the sales figure of a lift test.
|
|
1110
1132
|
- 2026-11-21: version 0.14.0. Shopify: a row in a full-width section
|
package/index.d.ts
CHANGED
|
@@ -22,6 +22,11 @@ export interface TopEntry {
|
|
|
22
22
|
s: number;
|
|
23
23
|
/** Unix ms of the last in-order interaction. */
|
|
24
24
|
t: number;
|
|
25
|
+
/**
|
|
26
|
+
* Strongest level applied since the entry started (1–10); 0 or absent when
|
|
27
|
+
* unknown (an entry stored or sent without it).
|
|
28
|
+
*/
|
|
29
|
+
m?: number;
|
|
25
30
|
}
|
|
26
31
|
|
|
27
32
|
export interface RecentEntry {
|
|
@@ -39,8 +44,11 @@ export interface HistoryState {
|
|
|
39
44
|
lastT: number | null;
|
|
40
45
|
}
|
|
41
46
|
|
|
42
|
-
/**
|
|
43
|
-
|
|
47
|
+
/**
|
|
48
|
+
* `[item_id, weight rounded to 4 decimals, age in seconds]`, plus the entry's
|
|
49
|
+
* strongest level (1–10) as a fourth element when it is known.
|
|
50
|
+
*/
|
|
51
|
+
export type WireEntry = [item: string, weight: number, ageSeconds: number, maxLevel?: number];
|
|
44
52
|
|
|
45
53
|
export interface WireHistory {
|
|
46
54
|
history: WireEntry[];
|
|
@@ -51,7 +59,8 @@ export interface WireHistory {
|
|
|
51
59
|
|
|
52
60
|
/** Server-side history snapshot (`history` field of a recommendation response). */
|
|
53
61
|
export interface ServerSnapshot {
|
|
54
|
-
|
|
62
|
+
/** An entry's optional third element is its strongest level (1–10). */
|
|
63
|
+
top: Array<[item: string, weight: number, maxLevel?: number]>;
|
|
55
64
|
recent: string[];
|
|
56
65
|
/** Absent from servers that predate rejections. */
|
|
57
66
|
rejected?: string[];
|
package/package.json
CHANGED
package/src/client.js
CHANGED
|
@@ -745,7 +745,7 @@ export function createClient(options) {
|
|
|
745
745
|
* The history exactly as the next recommendation request would send it;
|
|
746
746
|
* `rejected` goes into its `exclude`.
|
|
747
747
|
*
|
|
748
|
-
* @returns {{ history:
|
|
748
|
+
* @returns {{ history: import('./history.js').WireEntry[], recent: string[], rejected: string[] }}
|
|
749
749
|
*/
|
|
750
750
|
getHistory() {
|
|
751
751
|
start();
|
package/src/history.js
CHANGED
|
@@ -19,6 +19,8 @@
|
|
|
19
19
|
* @typedef {object} TopEntry
|
|
20
20
|
* @property {number} s Score valid at time `t`.
|
|
21
21
|
* @property {number} t Unix ms of the last in-order interaction.
|
|
22
|
+
* @property {number} [m] The strongest level applied since the entry started,
|
|
23
|
+
* 1–10; 0 (or absent) when unknown: an entry stored or sent without it.
|
|
22
24
|
*/
|
|
23
25
|
|
|
24
26
|
/**
|
|
@@ -40,12 +42,16 @@
|
|
|
40
42
|
*/
|
|
41
43
|
|
|
42
44
|
/**
|
|
43
|
-
*
|
|
45
|
+
* `[item, weight, ageSeconds]`, plus the entry's strongest level as a fourth
|
|
46
|
+
* element when it is known.
|
|
47
|
+
*
|
|
48
|
+
* @typedef {[item: string, weight: number, ageSeconds: number, maxLevel?: number]} WireEntry
|
|
44
49
|
*/
|
|
45
50
|
|
|
46
51
|
/**
|
|
47
52
|
* @typedef {object} ServerSnapshot
|
|
48
|
-
* @property {Array<[string, number]>} top
|
|
53
|
+
* @property {Array<[string, number] | [string, number, number]>} top An
|
|
54
|
+
* entry's optional third element is its strongest level.
|
|
49
55
|
* @property {string[]} recent
|
|
50
56
|
* @property {string[]} [rejected] Absent from servers older than rejections.
|
|
51
57
|
* @property {number} as_of Unix ms at which the `top` weights are valid.
|
|
@@ -103,6 +109,29 @@ export function isEmpty(state) {
|
|
|
103
109
|
return state.top.size === 0 && state.recent.length === 0;
|
|
104
110
|
}
|
|
105
111
|
|
|
112
|
+
/**
|
|
113
|
+
* The strongest level of two sides of one entry: unknown (0) wins, since the
|
|
114
|
+
* unknown side may hold a purchase.
|
|
115
|
+
*
|
|
116
|
+
* @param {number | undefined} a
|
|
117
|
+
* @param {number | undefined} b
|
|
118
|
+
* @returns {number}
|
|
119
|
+
*/
|
|
120
|
+
function strongest(a, b) {
|
|
121
|
+
return a && b ? Math.max(a, b) : 0;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* A strongest level read from storage or a snapshot: an integer 1–10, else 0
|
|
126
|
+
* (unknown).
|
|
127
|
+
*
|
|
128
|
+
* @param {unknown} value
|
|
129
|
+
* @returns {number}
|
|
130
|
+
*/
|
|
131
|
+
function levelOf(value) {
|
|
132
|
+
return Number.isInteger(value) && value >= 1 && value <= 10 ? /** @type {number} */ (value) : 0;
|
|
133
|
+
}
|
|
134
|
+
|
|
106
135
|
function decay(config, dtMs) {
|
|
107
136
|
return Math.exp((-Math.LN2 / config.halfLifeSeconds) * (dtMs / 1000));
|
|
108
137
|
}
|
|
@@ -127,7 +156,7 @@ export function weightAt(entry, T, config) {
|
|
|
127
156
|
* @param {HistoryState} state
|
|
128
157
|
* @param {number} T Unix ms.
|
|
129
158
|
* @param {HistoryConfig} config
|
|
130
|
-
* @returns {Array<{ item: string, weight: number, t: number }>}
|
|
159
|
+
* @returns {Array<{ item: string, weight: number, t: number, m: number }>}
|
|
131
160
|
*/
|
|
132
161
|
export function sortedEntries(state, T, config) {
|
|
133
162
|
return rank(state.top, T, config);
|
|
@@ -141,7 +170,7 @@ export function sortedEntries(state, T, config) {
|
|
|
141
170
|
function rank(top, T, config) {
|
|
142
171
|
const entries = [];
|
|
143
172
|
for (const [item, entry] of top) {
|
|
144
|
-
entries.push({ item, weight: weightAt(entry, T, config), t: entry.t });
|
|
173
|
+
entries.push({ item, weight: weightAt(entry, T, config), t: entry.t, m: entry.m || 0 });
|
|
145
174
|
}
|
|
146
175
|
return entries.sort((a, b) => b.weight - a.weight || compareIds(a.item, b.item));
|
|
147
176
|
}
|
|
@@ -234,11 +263,11 @@ export function applyEvent(state, { item, level, t }, config) {
|
|
|
234
263
|
const top = new Map(state.top);
|
|
235
264
|
const current = top.get(item);
|
|
236
265
|
if (!current) {
|
|
237
|
-
top.set(item, { s: level, t });
|
|
266
|
+
top.set(item, { s: level, t, m: level });
|
|
238
267
|
} else if (t >= current.t) {
|
|
239
|
-
top.set(item, { s: current.s * decay(config, t - current.t) + level, t });
|
|
268
|
+
top.set(item, { s: current.s * decay(config, t - current.t) + level, t, m: strongest(current.m, level) });
|
|
240
269
|
} else {
|
|
241
|
-
top.set(item, { s: current.s + level * decay(config, current.t - t), t: current.t });
|
|
270
|
+
top.set(item, { s: current.s + level * decay(config, current.t - t), t: current.t, m: strongest(current.m, level) });
|
|
242
271
|
}
|
|
243
272
|
|
|
244
273
|
const inOrder = state.lastT === null || t >= state.lastT;
|
|
@@ -260,8 +289,9 @@ export function applyEvent(state, { item, level, t }, config) {
|
|
|
260
289
|
/**
|
|
261
290
|
* Wire format of a recommendation request: weights decayed to `T`, at most
|
|
262
291
|
* what the API accepts, and rounded to 4 decimals, integer age in seconds (clamped at 0 so a skewed
|
|
263
|
-
* clock never yields negative ages)
|
|
264
|
-
*
|
|
292
|
+
* clock never yields negative ages), and a fourth element, the entry's
|
|
293
|
+
* strongest level, only when it is known. `rejected` (oldest mark first) is
|
|
294
|
+
* sent in the request's `exclude`.
|
|
265
295
|
*
|
|
266
296
|
* @param {HistoryState} state
|
|
267
297
|
* @param {number} T Unix ms of the request.
|
|
@@ -271,19 +301,24 @@ export function applyEvent(state, { item, level, t }, config) {
|
|
|
271
301
|
export function toWire(state, T, config) {
|
|
272
302
|
const history = sortedEntries(state, T, config)
|
|
273
303
|
.slice(0, config.topK)
|
|
274
|
-
.map(({ item, weight, t }) =>
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
304
|
+
.map(({ item, weight, t, m }) => {
|
|
305
|
+
const entry = /** @type {WireEntry} */ ([
|
|
306
|
+
item,
|
|
307
|
+
Math.round(Math.min(weight, MAX_REQUEST_WEIGHT) * 1e4) / 1e4,
|
|
308
|
+
Math.max(0, Math.floor((T - t) / 1000))
|
|
309
|
+
]);
|
|
310
|
+
if (m > 0) entry.push(m);
|
|
311
|
+
return entry;
|
|
312
|
+
});
|
|
279
313
|
const recent = state.recent.slice(-config.recentSize).map((entry) => entry.item);
|
|
280
314
|
return { history, recent, rejected: rejectedOrder(state.rejected) };
|
|
281
315
|
}
|
|
282
316
|
|
|
283
317
|
/**
|
|
284
318
|
* Builds a state from the server's fallback snapshot. Each top entry becomes
|
|
285
|
-
* `{ s: weight, t: as_of }` as the spec requires,
|
|
286
|
-
*
|
|
319
|
+
* `{ s: weight, t: as_of }` as the spec requires, with its strongest level `m`
|
|
320
|
+
* (0, unknown, when its third element is absent or not an integer 1–10), each
|
|
321
|
+
* rejected item a mark at `as_of`. `lastT` is left unknown
|
|
287
322
|
* rather than set to `as_of`: `as_of` is the server clock, and a device clock
|
|
288
323
|
* running behind it would otherwise treat every new local event as out of
|
|
289
324
|
* order and freeze the recent list.
|
|
@@ -301,7 +336,7 @@ export function fromSnapshot(snapshot, config) {
|
|
|
301
336
|
const top = new Map();
|
|
302
337
|
for (const entry of Array.isArray(snapshot.top) ? snapshot.top : []) {
|
|
303
338
|
if (Array.isArray(entry) && isId(entry[0]) && isWeight(entry[1])) {
|
|
304
|
-
top.set(entry[0], { s: entry[1], t: asOf });
|
|
339
|
+
top.set(entry[0], { s: entry[1], t: asOf, m: levelOf(entry[2]) });
|
|
305
340
|
}
|
|
306
341
|
}
|
|
307
342
|
const seen = new Set();
|
|
@@ -332,7 +367,9 @@ export function fromSnapshot(snapshot, config) {
|
|
|
332
367
|
* Top: per item, the sum of both decayed scores. The sum is expressed at the
|
|
333
368
|
* later of the two `t`s, which keeps the true last-interaction time (and so
|
|
334
369
|
* the wire `age_seconds`) instead of resetting it to the merge time; the
|
|
335
|
-
* weight at any later time equals the sum of the two weights.
|
|
370
|
+
* weight at any later time equals the sum of the two weights. An entry on one
|
|
371
|
+
* side keeps its strongest level; on both, the stronger one, unless either
|
|
372
|
+
* side's is unknown (then unknown).
|
|
336
373
|
*
|
|
337
374
|
* Recent: union of both lists ordered by interaction time (oldest first); an
|
|
338
375
|
* item in both lists takes its most recent time. Equal times keep `a`'s order
|
|
@@ -357,7 +394,7 @@ export function merge(a, b, T, config) {
|
|
|
357
394
|
continue;
|
|
358
395
|
}
|
|
359
396
|
const t = Math.max(entry.t, other.t);
|
|
360
|
-
top.set(item, { s: weightAt(entry, t, config) + weightAt(other, t, config), t });
|
|
397
|
+
top.set(item, { s: weightAt(entry, t, config) + weightAt(other, t, config), t, m: strongest(entry.m, other.m) });
|
|
361
398
|
}
|
|
362
399
|
|
|
363
400
|
const rejected = new Map(a.rejected);
|
|
@@ -411,17 +448,22 @@ export function mergeSnapshot(local, snapshot, T, config) {
|
|
|
411
448
|
/**
|
|
412
449
|
* Compact JSON-safe form for storage. Kept separate from the wire format
|
|
413
450
|
* because storage needs raw `{s, t}` (not rounded weights) to stay exact.
|
|
451
|
+
* `maxLevel` holds each top entry's strongest level, in `top`'s order (0
|
|
452
|
+
* unknown): a key of its own, not a fourth element of a top entry, so an SDK
|
|
453
|
+
* from before it (which refuses a top entry of another length) still reads
|
|
454
|
+
* the state.
|
|
414
455
|
*
|
|
415
456
|
* @param {HistoryState} state
|
|
416
457
|
* @returns {{ top: Array<[string, number, number]>, recent: Array<[string, number]>,
|
|
417
|
-
* rejected: Array<[string, number]>, lastT: number|null }}
|
|
458
|
+
* rejected: Array<[string, number]>, lastT: number|null, maxLevel: number[] }}
|
|
418
459
|
*/
|
|
419
460
|
export function encodeState(state) {
|
|
420
461
|
return {
|
|
421
462
|
top: [...state.top].map(([item, { s, t }]) => [item, s, t]),
|
|
422
463
|
recent: state.recent.map(({ item, t }) => [item, t]),
|
|
423
464
|
rejected: [...state.rejected],
|
|
424
|
-
lastT: state.lastT
|
|
465
|
+
lastT: state.lastT,
|
|
466
|
+
maxLevel: [...state.top.values()].map(({ m }) => m || 0)
|
|
425
467
|
};
|
|
426
468
|
}
|
|
427
469
|
|
|
@@ -429,6 +471,9 @@ export function encodeState(state) {
|
|
|
429
471
|
* Inverse of {@link encodeState}. Returns `null` on any malformed field so
|
|
430
472
|
* the caller discards corrupt storage instead of sending garbage. A state
|
|
431
473
|
* stored before rejections existed has no `rejected` and decodes as none.
|
|
474
|
+
* `maxLevel` is read leniently and never fails the state: absent, not a list
|
|
475
|
+
* or not as long as `top`, every level is unknown (0); an element that is not
|
|
476
|
+
* an integer 1–10 is unknown.
|
|
432
477
|
*
|
|
433
478
|
* An entry whose id the API refuses is dropped and the rest kept: earlier
|
|
434
479
|
* SDKs counted characters, not bytes, and stored such ids, which made every
|
|
@@ -442,12 +487,13 @@ export function decodeState(raw) {
|
|
|
442
487
|
if (!raw || !Array.isArray(raw.top) || !Array.isArray(raw.recent)) return null;
|
|
443
488
|
if (raw.lastT !== null && !Number.isFinite(raw.lastT)) return null;
|
|
444
489
|
|
|
490
|
+
const levels = Array.isArray(raw.maxLevel) && raw.maxLevel.length === raw.top.length ? raw.maxLevel : null;
|
|
445
491
|
const top = new Map();
|
|
446
|
-
for (const entry of raw.top) {
|
|
492
|
+
for (const [i, entry] of raw.top.entries()) {
|
|
447
493
|
if (!Array.isArray(entry) || typeof entry[0] !== 'string' || !isWeight(entry[1]) || !Number.isFinite(entry[2])) {
|
|
448
494
|
return null;
|
|
449
495
|
}
|
|
450
|
-
if (isId(entry[0])) top.set(entry[0], { s: entry[1], t: entry[2] });
|
|
496
|
+
if (isId(entry[0])) top.set(entry[0], { s: entry[1], t: entry[2], m: levels ? levelOf(levels[i]) : 0 });
|
|
451
497
|
}
|
|
452
498
|
const recent = [];
|
|
453
499
|
for (const entry of raw.recent) {
|
package/src/magento.js
CHANGED
|
@@ -196,9 +196,10 @@ export async function magentoPage(page) {
|
|
|
196
196
|
const found = (response?.ok ? await response.json().catch(() => null) : null)?.cards;
|
|
197
197
|
for (const card of Array.isArray(found) ? found : []) if (cards.has(String(card?.id))) cards.set(String(card.id), card);
|
|
198
198
|
}
|
|
199
|
-
|
|
199
|
+
const reasons = new Map(items.map(({ itemId, why }) => [itemId, why]));
|
|
200
|
+
return [...cards].filter(([, card]) => card && web(card.url)).map(([id, card]) => ({ ...card, recommendationId, why: reasons.get(id) }));
|
|
200
201
|
};
|
|
201
|
-
const html = (cards) => cards.slice(0, ROW).map(({ recommendationId, ...card }) => {
|
|
202
|
+
const html = (cards) => cards.slice(0, ROW).map(({ recommendationId, why, ...card }) => {
|
|
202
203
|
const link = web(card.url);
|
|
203
204
|
// ?rec= only where a fragment can't carry the id: the address has its own
|
|
204
205
|
// (a theme's, not ours to overwrite), it's the page already open (a
|
|
@@ -223,7 +224,11 @@ export async function magentoPage(page) {
|
|
|
223
224
|
try {
|
|
224
225
|
const more = await ask(short.map((i) => ({ count: ROW - cards[i].length, placement: rows[i].placement })),
|
|
225
226
|
lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)));
|
|
226
|
-
|
|
227
|
+
// A popular top-up (recapi slow or at a limit on this call) fills the
|
|
228
|
+
// first row's gap with what that row shows anyway when recapi is
|
|
229
|
+
// down, but under the bought-together title it would mislead: that
|
|
230
|
+
// row keeps the cards it has.
|
|
231
|
+
const extra = await Promise.all(more.map((list, k) => (rows[short[k]].together && list.fallback ? [] : cardsOf(list))));
|
|
227
232
|
short.forEach((i, k) => cards[i].push(...extra[k]));
|
|
228
233
|
} catch (error) {
|
|
229
234
|
// Rejected (a key revoked mid-page): the cards of the first call stay.
|
|
@@ -234,6 +239,13 @@ export async function magentoPage(page) {
|
|
|
234
239
|
const drawn = html(cards[i]);
|
|
235
240
|
if (drawn.length) {
|
|
236
241
|
row.slot.innerHTML = drawn.join('');
|
|
242
|
+
// The title only over a real pair among the cards drawn: a product
|
|
243
|
+
// nobody bought with another yet gets similar ones, true cards under
|
|
244
|
+
// a false title, so they show untitled, as more of the row above.
|
|
245
|
+
// Removed, not hidden: a theme's .block-title rule beats [hidden].
|
|
246
|
+
if (row.together && !cards[i].slice(0, ROW).some(({ why }) => why === 'bought_together')) {
|
|
247
|
+
blockOf(row.slot).querySelector?.('.block-title')?.remove();
|
|
248
|
+
}
|
|
237
249
|
blockOf(row.slot).hidden = false;
|
|
238
250
|
}
|
|
239
251
|
});
|
package/src/shopify.js
CHANGED
|
@@ -317,13 +317,15 @@ export async function shopifyTheme(options) {
|
|
|
317
317
|
const fromProduct = (p, recommendationId) => (p?.available
|
|
318
318
|
? `<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>`
|
|
319
319
|
: null);
|
|
320
|
-
// A list's cards, in recapi's order
|
|
321
|
-
// own page data, one request each.
|
|
322
|
-
const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata }) => {
|
|
323
|
-
|
|
324
|
-
if (
|
|
325
|
-
|
|
326
|
-
|
|
320
|
+
// A list's cards, in recapi's order, each with its reason code. The
|
|
321
|
+
// others come from the product's own page data, one request each.
|
|
322
|
+
const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata, why }) => {
|
|
323
|
+
let html = fromMetadata(metadata, recommendationId);
|
|
324
|
+
if (!html) {
|
|
325
|
+
const response = await fetch(`${root}products/${encodeURIComponent(itemId)}.js`).catch(() => null);
|
|
326
|
+
html = fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId);
|
|
327
|
+
}
|
|
328
|
+
return html && { html, why };
|
|
327
329
|
}))).filter(Boolean);
|
|
328
330
|
const lists = await ask(rows.map((_, row) => [row, ROW]), []);
|
|
329
331
|
const cards = await Promise.all(lists.map(cardsOf));
|
|
@@ -336,17 +338,30 @@ export async function shopifyTheme(options) {
|
|
|
336
338
|
// Refused (a key revoked mid-page): the rows keep the cards they have.
|
|
337
339
|
const more = await ask(short.map((row) => [row, ROW - cards[row].length]), lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)))
|
|
338
340
|
.catch((error) => { console.warn('recapi:', error); return []; });
|
|
339
|
-
|
|
341
|
+
// A popular top-up (recapi slow or at a limit on this call) fills the
|
|
342
|
+
// first row's gap with what that row shows anyway when recapi is down,
|
|
343
|
+
// but under the bought-together title it would mislead: that row keeps
|
|
344
|
+
// the cards it has.
|
|
345
|
+
await Promise.all(more.map(async (list, k) => {
|
|
346
|
+
if (short[k] === 1 && list.fallback) return;
|
|
347
|
+
cards[short[k]] = [...cards[short[k]], ...await cardsOf(list)];
|
|
348
|
+
}));
|
|
340
349
|
}
|
|
341
350
|
const [first, second = []] = cards.map((row) => row.slice(0, ROW));
|
|
342
|
-
if (first.length) slot.innerHTML = style + first.join('');
|
|
351
|
+
if (first.length) slot.innerHTML = style + first.map(({ html }) => html).join('');
|
|
343
352
|
else hide();
|
|
344
353
|
// Each row shows or hides on its own. A popular fallback is not what was
|
|
345
354
|
// bought together, so that row then stays away. The theme's own h2 rule
|
|
346
355
|
// styles its title.
|
|
347
356
|
if (second.length && !lists[1].fallback) {
|
|
348
|
-
|
|
349
|
-
|
|
357
|
+
// The title only over a real pair among the cards drawn: a product
|
|
358
|
+
// nobody bought with another yet gets similar ones, true cards under a
|
|
359
|
+
// false title, so they show untitled, the first row's gap apart, and
|
|
360
|
+
// read as more of it.
|
|
361
|
+
const paired = second.some(({ why }) => why === 'bought_together');
|
|
362
|
+
const title = together && paired ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
|
|
363
|
+
const more = paired ? '' : '<style>:where(.recapi-bought-together.recapi-more){margin-top:1rem}</style>';
|
|
364
|
+
slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}${paired ? '' : ' recapi-more'}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${more}${second.map(({ html }) => html).join('')}</div></div>`);
|
|
350
365
|
}
|
|
351
366
|
};
|
|
352
367
|
// recommendLists() rejects only on a bad request: a page still loses no more than its rows.
|
package/src/woocommerce.js
CHANGED
|
@@ -259,8 +259,10 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
259
259
|
// no translation.
|
|
260
260
|
const price = ({ prices: p }) => money(Number(p?.price) / 10 ** p?.currency_minor_unit, p?.currency_code);
|
|
261
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).
|
|
262
|
+
// others from WooCommerce's Store API (public, one request for all). Each
|
|
263
|
+
// keeps its item's reason code.
|
|
263
264
|
const cardsOf = async ({ recommendationId, items }) => {
|
|
265
|
+
const reasons = new Map(items.map(({ itemId, why }) => [itemId, why]));
|
|
264
266
|
const cards = new Map(items.map(({ itemId, metadata }) => [itemId, fromMetadata(metadata, recommendationId)]));
|
|
265
267
|
const ids = [...cards].filter(([id, html]) => !html && /^\d+$/.test(id)).map(([id]) => id);
|
|
266
268
|
let products = [];
|
|
@@ -277,7 +279,7 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
277
279
|
cards.set(String(p.id), card(href, p.images?.[0]?.thumbnail || p.images?.[0]?.src || '', text(p.name), price(p)));
|
|
278
280
|
}
|
|
279
281
|
}
|
|
280
|
-
return [...cards.
|
|
282
|
+
return [...cards].filter(([, html]) => html).map(([id, html]) => ({ html, why: reasons.get(id) }));
|
|
281
283
|
};
|
|
282
284
|
const lists = await ask(rows.map((row) => [row, ROW]), []);
|
|
283
285
|
const shown = await Promise.all(lists.map(cardsOf));
|
|
@@ -290,7 +292,11 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
290
292
|
// cards the first call already found.
|
|
291
293
|
try {
|
|
292
294
|
const more = await ask(short.map((i) => [rows[i], ROW - shown[i].length]), lists.flatMap((list) => list.items.map(({ itemId }) => itemId)));
|
|
293
|
-
|
|
295
|
+
// A popular top-up (recapi slow or at a limit on this call) fills the
|
|
296
|
+
// first row's gap with what that row shows anyway when recapi is
|
|
297
|
+
// down, but under the bought-together title it would mislead: that
|
|
298
|
+
// row keeps the cards it has.
|
|
299
|
+
const cards = await Promise.all(more.map((list, k) => (short[k] === 1 && list.fallback ? [] : cardsOf(list))));
|
|
294
300
|
short.forEach((row, k) => shown[row].push(...cards[k]));
|
|
295
301
|
} catch (error) {
|
|
296
302
|
console.warn('recapi:', error);
|
|
@@ -304,10 +310,16 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
304
310
|
// at a limit) is popular products, not what shoppers bought together:
|
|
305
311
|
// under that title it would mislead, so that row waits for the next page.
|
|
306
312
|
if (together?.length && !lists[1].fallback) {
|
|
307
|
-
|
|
313
|
+
// The title only over a real pair among the cards drawn: a product
|
|
314
|
+
// nobody bought with another yet gets similar ones, true cards under a
|
|
315
|
+
// false title, so they show untitled, the first row's gap apart, and
|
|
316
|
+
// read as more of it.
|
|
317
|
+
const paired = together.some(({ why }) => why === 'bought_together');
|
|
318
|
+
const more = paired ? '' : `<style>:where(#${TOGETHER}){margin-top:1rem}</style>`;
|
|
319
|
+
slot.insertAdjacentHTML('afterend', `${paired ? heading(rows[1].heading) : ''}<div id="${TOGETHER}">${style.replaceAll('recapi-recommendations', TOGETHER)}${more}${together.map(({ html }) => html).join('')}</div>`);
|
|
308
320
|
}
|
|
309
321
|
if (first.length) {
|
|
310
|
-
slot.innerHTML = style + first.join('');
|
|
322
|
+
slot.innerHTML = style + first.map(({ html }) => html).join('');
|
|
311
323
|
if (page.heading) slot.insertAdjacentHTML('beforebegin', heading(page.heading));
|
|
312
324
|
} else {
|
|
313
325
|
hide();
|