@recapi/client 0.14.0 → 0.15.1

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 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.14.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.15.1/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
 
@@ -732,7 +742,7 @@ for (const item of items) {
732
742
 
733
743
  ### Client methods
734
744
 
735
- - **`track(itemId, level, { recommendationId? })`**: `level` is any integer
745
+ - **`track(itemId, level, { recommendationId?, value?, currency? })`**: `level` is any integer
736
746
  0–10 of the [recommended scale](https://recapi.io/docs/api#interaction-levels) (3
737
747
  opened, 5 strong interest, 10 the action that matters most), or one of its
738
748
  shop names `'view'`, `'cart'` and `'purchase'` (3, 5 and 10). `'reject'`
@@ -744,7 +754,10 @@ for (const item of items) {
744
754
  timestamp and a fresh `event_id` (the idempotency
745
755
  key, reused on retries). Level 0 means an impression: it is sent but does
746
756
  not change the history. Throws `RecapiError('invalid_request')` on a bad
747
- level. An item id follows the API's rules, 1–256 bytes of UTF-8
757
+ level. A purchase may carry `{ value, currency }` (what the buyer paid for
758
+ the line, and its ISO 4217 code such as `'EUR'`), kept for the sales figure
759
+ of a lift test; a negative value, or a currency without a value or not of
760
+ three letters, throws the same error. An item id follows the API's rules, 1–256 bytes of UTF-8
748
761
  (128 characters of Cyrillic or accented Latin, 85 of CJK) without
749
762
  control characters; any other drops the event and reports it instead of
750
763
  throwing, as a visitor's URL can carry one (see [Fallback](#fallback)). A stored history entry whose id breaks the rule,
@@ -1102,6 +1115,15 @@ minifier, to keep zero dev dependencies.
1102
1115
 
1103
1116
  ## Changes
1104
1117
 
1118
+ - 2026-11-22: version 0.15.1. Shopify, WooCommerce and Magento: a product
1119
+ page's second row prints "Often bought together" only when one of the
1120
+ cards it shows was carted or bought with the product on screen (`why:
1121
+ bought_together`); otherwise the same cards show without the title, as
1122
+ more of the row above. When recapi answers the second call (the one that
1123
+ fills cards a shop can't sell) with popular products, only the first row
1124
+ takes them: Often bought together keeps the cards it has.
1125
+ - 2026-11-22: version 0.15.0. `track()` takes a purchase's `value` and
1126
+ `currency`, sent with the event for the sales figure of a lift test.
1105
1127
  - 2026-11-21: version 0.14.0. Shopify: a row in a full-width section
1106
1128
  (Dawn's Custom Liquid) keeps to the theme's page width, four cards across
1107
1129
  (two on a phone); the theme editor's preview shows the row and sends or
package/index.d.ts CHANGED
@@ -168,7 +168,11 @@ export interface PopularResult {
168
168
  export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
169
169
 
170
170
  export interface RecapiClient {
171
- track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null }): void;
171
+ /**
172
+ * `value` is what the buyer paid for a purchase's line (a number of at least 0; 0 is a free line), `currency` its ISO 4217 code
173
+ * (three letters, any case); a currency needs a value. An invalid pair throws `RecapiError('invalid_request')`, as a bad level does.
174
+ */
175
+ track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string }): void;
172
176
  /** Falls back to popular items on a network error, a timeout, a 5xx or a 429 (an empty list if those fail too), to an empty list on a 401 or 403; rejects on a bad request or a reply that isn't the API's. */
173
177
  recommend(params?: RecommendParams): Promise<RecommendResult>;
174
178
  /** Several lists in one call, billed as one recommendation; falls back as `recommend()` does, list by list. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
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/client.js CHANGED
@@ -545,10 +545,14 @@ export function createClient(options) {
545
545
  * Does nothing under Do Not Track (see `respectDoNotTrack`).
546
546
  * An `itemId` the API would refuse (a page often takes it from a
547
547
  * visitor's URL) drops the event and goes to `onError`, without throwing.
548
- * @param {{ recommendationId?: string | null }} [options] Overrides the
549
- * automatic attribution. `null` (a fallback list's id) is no override.
548
+ * @param {{ recommendationId?: string | null, value?: number,
549
+ * currency?: string }} [options] `recommendationId` overrides the
550
+ * automatic attribution; `null` (a fallback list's id) is no override.
551
+ * `value` is what the buyer paid for a purchase's line (0 for a free
552
+ * line), `currency` its ISO 4217 code (three letters, any case); a
553
+ * currency needs a value. An invalid pair throws, as a bad level does.
550
554
  */
551
- track(itemId, level, { recommendationId: explicit } = {}) {
555
+ track(itemId, level, { recommendationId: explicit, value, currency } = {}) {
552
556
  start();
553
557
  // A fallback list has a null id, and a page passing it on must not
554
558
  // send `null` or lose the item's earlier, real attribution.
@@ -560,6 +564,7 @@ export function createClient(options) {
560
564
  "level must be an integer between -10 and 10, or 'view', 'cart', 'purchase' or 'reject'"
561
565
  );
562
566
  }
567
+ checkAmount(value, currency);
563
568
  // A page often takes this id from a visitor's URL, so a crafted link
564
569
  // must not fail it. Nothing is kept: in the history it would make the
565
570
  // API refuse every later list. The line never quotes the visitor's id.
@@ -584,6 +589,8 @@ export function createClient(options) {
584
589
  user_id: userId ?? undefined,
585
590
  anon_id: anonId ?? undefined,
586
591
  recommendation_id: attributed,
592
+ value,
593
+ currency,
587
594
  timestamp: new Date(t).toISOString(),
588
595
  event_id: uuid()
589
596
  }));
@@ -880,6 +887,22 @@ function withRejected(exclude, rejected) {
880
887
  return [...out];
881
888
  }
882
889
 
890
+ /**
891
+ * Refuses what the API would refuse in an event: a value that is not a
892
+ * finite number of at least 0, a currency that is not three ASCII letters or
893
+ * comes without a value. `undefined` is no value, no currency.
894
+ */
895
+ function checkAmount(value, currency) {
896
+ if (value !== undefined && !(typeof value === 'number' && value >= 0 && value !== Infinity)) {
897
+ throw new RecapiError('invalid_request', 'value must be a number of at least 0');
898
+ }
899
+ if (currency === undefined) return;
900
+ if (value === undefined) throw new RecapiError('invalid_request', 'currency needs a value');
901
+ if (typeof currency !== 'string' || !/^[A-Za-z]{3}$/.test(currency)) {
902
+ throw new RecapiError('invalid_request', 'currency must be three letters (ISO 4217)');
903
+ }
904
+ }
905
+
883
906
  function compact(object) {
884
907
  return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
885
908
  }
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
- return [...cards.values()].filter((card) => card && web(card.url)).map((card) => ({ ...card, recommendationId }));
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
- const extra = await Promise.all(more.map(cardsOf));
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. The others come from the product's
321
- // own page data, one request each.
322
- const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata }) => {
323
- const card = fromMetadata(metadata, recommendationId);
324
- if (card) return card;
325
- const response = await fetch(`${root}products/${encodeURIComponent(itemId)}.js`).catch(() => null);
326
- return fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId);
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
- await Promise.all(more.map(async (list, k) => { cards[short[k]] = [...cards[short[k]], ...await cardsOf(list)]; }));
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
- const title = together ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
349
- slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${second.join('')}</div></div>`);
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.
@@ -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.values()].filter(Boolean);
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
- const cards = await Promise.all(more.map(cardsOf));
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
- slot.insertAdjacentHTML('afterend', `${heading(rows[1].heading)}<div id="${TOGETHER}">${style.replaceAll('recapi-recommendations', TOGETHER)}${together.join('')}</div>`);
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();