@recapi/client 0.17.1 → 0.18.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 CHANGED
@@ -35,12 +35,14 @@ 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.17.1/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.18.0/index.js';
39
+
40
+ const ITEM_ID = ''; // this page's product id
39
41
 
40
42
  const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com', consent: false });
41
43
  // From your cookie banner, once the visitor agrees: recapi.setConsent(true).
42
44
  // A site that needs no banner passes consent: true instead (see Consent).
43
- recapi.track('item-42', 'view'); // and the calls of the quick start below
45
+ recapi.track(ITEM_ID, 'view'); // and the calls of the quick start below
44
46
  </script>
45
47
  ```
46
48
 
@@ -85,22 +87,21 @@ const recapi = createClient({
85
87
  });
86
88
 
87
89
  // The user opened an item: a product, an article, a video… (level 3).
88
- recapi.track('item-42', 'view');
89
-
90
- // Show recommendations. If recapi is slow, failing or at your plan's limit,
91
- // recommend() resolves with popular items instead, and with an empty list if
92
- // those fail too or your key is refused (hide the slot): no try/catch needed. Give the widget's
93
- // container a CSS min-height so the page doesn't jump when the items arrive.
94
- // Below the fold, ask only once it nears the screen: each list is billed
95
- // and counted as shown, and many visitors never scroll that far.
96
- const slot = document.getElementById('recommendations');
97
- const observer = new IntersectionObserver(async (entries) => {
98
- if (!entries.some((entry) => entry.isIntersecting)) return;
99
- observer.disconnect();
100
- const { items } = await recapi.recommend({ count: 8, tagsAny: ['sports'] });
101
- render(slot, items); // [{ itemId, score, slot, why, metadata }]
102
- }, { rootMargin: '0px 0px 400px 0px' });
103
- observer.observe(slot);
90
+ // itemId is that page's own id: an empty one sends nothing.
91
+ recapi.track(itemId, 'view');
92
+
93
+ // A row of 4 product cards in <div id="recommendations"></div>, drawn from
94
+ // each item's name, url, picture and price metadata once it nears the screen.
95
+ // It shows popular items if recapi is slow, failing or at your plan's limit,
96
+ // and hides when there is nothing to show. See row() below.
97
+ recapi.row('#recommendations', { contextItemId: itemId, heading: 'You may also like' });
98
+
99
+ // Or, instead of row(), your own look: recommend() gives the list. If recapi
100
+ // is slow, failing or at your plan's limit, it resolves with popular items,
101
+ // and with an empty list if those fail too or your key is refused (hide the
102
+ // slot): no try/catch needed. Call it only once the slot nears the screen
103
+ // (row() waits for you): each list is billed and counted as shown.
104
+ // const { items } = await recapi.recommend({ count: 8, tagsAny: ['sports'] });
104
105
 
105
106
  // Later, the user clicks a recommended item and lands on its page (a
106
107
  // view). No need to pass the recommendation id: the SDK remembers which
@@ -591,7 +592,7 @@ const recapi = createClient({
591
592
  });
592
593
 
593
594
  recapi.identify('cust-881');
594
- recapi.track('item-42', 10); // the action that matters most: a purchase, a subscription…
595
+ recapi.track('item_4471', 10); // the action that matters most: a purchase, a subscription…
595
596
  await recapi.destroy(); // flushes queued events before exit
596
597
  ```
597
598
 
@@ -633,7 +634,7 @@ export default {
633
634
  async fetch(request, env, ctx) {
634
635
  const visitor = createClient({ ...options, consent: false });
635
636
  visitor.identify('cust-881');
636
- visitor.track('item-42', 'purchase');
637
+ visitor.track('item_4471', 'purchase');
637
638
  ctx.waitUntil(visitor.flush()); // sends the events after the response
638
639
  const { items } = await shared.popular({ count: 4 });
639
640
  return Response.json(items);
@@ -665,7 +666,7 @@ const recapi = createClient({ apiKey: process.env.RECAPI_KEY, baseUrl: 'https://
665
666
 
666
667
  On Node 18, or 20 before 20.19, `require` throws `ERR_REQUIRE_ESM`. Load
667
668
  the library once with `import()`, which CommonJS has on every Node, then
668
- `await recapi` where you use it: `(await recapi).track('item-42', 'view')`.
669
+ `await recapi` where you use it: `(await recapi).track('item_4471', 'view')`.
669
670
 
670
671
  ```js
671
672
  // CommonJS, Node 18 and later
@@ -775,6 +776,8 @@ for (const item of items) {
775
776
  a secret key: call the API from your backend for that.
776
777
  - **`recommendLists({ lists, exclude, allowRepeats })`**: several rows in
777
778
  one call, see [below](#several-rows-in-one-call).
779
+ - **`row(slot, { placement, contextItemId, heading })`**: a ready row, see
780
+ [The ready row](#the-ready-row).
778
781
  - **`popular({ tagsAny, tagsAll, count })`** resolves to `{ items: [{ itemId, score, why, metadata }] }`.
779
782
  A public key goes in `?key=`, so the response can be cached by a CDN.
780
783
  [How the key is sent](#how-the-key-is-sent) gives the reason for the rest.
@@ -806,10 +809,35 @@ parameters and resolves to its own result, in order, with its own
806
809
 
807
810
  ```js
808
811
  const [similar, more] = await recapi.recommendLists({
809
- lists: [{ placement: 'product', count: 4, contextItemId: 'item-42' }, { placement: 'more', count: 8 }]
812
+ lists: [{ placement: 'product', count: 4, contextItemId: 'item_4471' }, { placement: 'more', count: 8 }]
810
813
  });
811
814
  ```
812
815
 
816
+ ### The ready row
817
+
818
+ `row(slot, { placement, contextItemId, heading })` fills `slot` (an element
819
+ or a selector) with up to 4 cards, the shop rows' rules in one call:
820
+
821
+ - It holds the slot's height and asks only once the slot is within 400px
822
+ of the screen. Rows called together share one billed call, with no
823
+ product on two rows.
824
+ - A card needs the item's `name` and an http(s) `url` metadata; `picture`
825
+ and `price` show when present. A number price takes the item's `currency`,
826
+ else the page's `<meta property="product:price:currency">`. An item with
827
+ `available: false` is skipped.
828
+ - Each link carries its list's id, which the page it opens reads (see
829
+ [Consent](#consent-and-eprivacy)).
830
+ - The row hides when no card can be drawn; the console names the missing
831
+ keys. Under the `bought_together` placement, `heading` shows only over a
832
+ product bought with this one, and the row stays away when recapi answers
833
+ with popular items.
834
+ - Its styles weigh nothing (`:where`), so any rule of yours restyles it
835
+ (`.recapi-row ul`, `a`, `img`, `.recapi-heading`, `.recapi-name`,
836
+ `.recapi-price`), and pass a `style-src 'self'` CSP.
837
+
838
+ There are no other options: for another look, draw `recommend()`'s list.
839
+ The file (`row.js`) loads on the first call only.
840
+
813
841
  ### Errors and troubleshooting
814
842
 
815
843
  Every failure is a `RecapiError` with `code`, `status` and `message`. The
@@ -1033,27 +1061,14 @@ A site that needs no banner (outside the EU, or with its own legal basis)
1033
1061
  passes `consent: true`. Without consent, the SDK never reads or writes storage
1034
1062
  and creates no anonymous id. The history and the attribution map live in memory for the
1035
1063
  current page only. A single-page app keeps attribution. On a multi-page
1036
- site, a click that loads the item's page is not attributed unless you
1037
- pass the id yourself, for example in the link. A fragment (`#${recommendationId}`,
1038
- read from `location.hash`) avoids a page cache miss, as the shop rows above do;
1039
- a query also reaches pages that read the id on the server:
1040
-
1041
- ```js
1042
- // On the listing page: link each item with its recommendation id
1043
- // (null when the list is the popular fallback: then leave it out of the link).
1044
- const { recommendationId, items } = await recapi.recommend({ count: 8 });
1045
- // href = recommendationId ? `/p/${item.itemId}?rec=${recommendationId}` : `/p/${item.itemId}`
1046
-
1047
- // On the item's page:
1048
- const url = new URL(location.href);
1049
- const rec = url.searchParams.get('rec');
1050
- recapi.track('item-77', 'view', { recommendationId: rec }); // null: automatic attribution
1051
- // Then drop it, so a copied or shared address doesn't credit strangers to that list.
1052
- if (rec !== null) {
1053
- url.searchParams.delete('rec');
1054
- history.replaceState(history.state, '', url);
1055
- }
1056
- ```
1064
+ site, a card's link carries its list's id: `row()` writes it, and the page
1065
+ it opens credits it with its first `track()` above level 0 that passes no
1066
+ `recommendationId`, then takes it out of the address so a shared link
1067
+ credits nobody. A list you draw yourself carries it the same way: end each
1068
+ link with `#${recommendationId}` (no fragment when it is null, a fallback).
1069
+ `?rec=<id>` is read too, for pages that need the id on the server. Either
1070
+ way only an id recapi makes (`rec_` and hex digits) is read: any other
1071
+ `#…` or `?rec=` value is the site's own and stays.
1057
1072
 
1058
1073
  Events are still sent, without `anon_id`. Don't call `track()` if you
1059
1074
  need no network at all. Withdrawing consent deletes the stored data.
@@ -1115,6 +1130,16 @@ minifier, to keep zero dev dependencies.
1115
1130
 
1116
1131
  ## Changes
1117
1132
 
1133
+ - 2026-11-24: version 0.18.0. `recapi.row(slot, { placement, contextItemId,
1134
+ heading })` draws a ready row of product cards from the items' metadata
1135
+ ([The ready row](#the-ready-row)). `track()` above level 0 without a
1136
+ `recommendationId` key reads the id a card's link brought (`#rec_…` or
1137
+ `?rec=rec_…`, nothing else) and takes it out of the address, so a click is credited without
1138
+ consent.
1139
+
1140
+ - 2026-11-24: version 0.17.2. `track()` with an empty item id (the
1141
+ quick start's tag before its `ITEM_ID` is set) still sends nothing, and
1142
+ its console line now says to set `ITEM_ID`.
1118
1143
  - 2026-11-24: version 0.17.1. WooCommerce: the settings screen names
1119
1144
  where the dashboard now keeps the API keys (the Quickstart's last
1120
1145
  section) and the past-orders upload (Your data, under Set up).
package/index.d.ts CHANGED
@@ -176,6 +176,14 @@ export interface PopularResult {
176
176
  */
177
177
  export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
178
178
 
179
+ /** `row()`'s only options: a site that wants another look draws `recommend()`'s list itself. */
180
+ export interface RowOptions {
181
+ placement?: string;
182
+ contextItemId?: string;
183
+ /** Printed over the row; under the `bought_together` placement only over a product bought with this one. */
184
+ heading?: string;
185
+ }
186
+
179
187
  export interface RecapiClient {
180
188
  /**
181
189
  * `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
@@ -197,6 +205,11 @@ export interface RecapiClient {
197
205
  /** This device's anonymous id; null without consent or under Do Not Track. */
198
206
  getAnonId(): string | null;
199
207
  destroy(): Promise<void>;
208
+ /**
209
+ * Draws up to 4 cards from each item's `name`, `url`, `picture`, `price` and `currency` metadata into `slot` once it nears
210
+ * the screen, each link carrying its list's id. Rows asked for together share one call. Hides when no card can be drawn.
211
+ */
212
+ row(slot: Element | string, options?: RowOptions): void;
200
213
  }
201
214
 
202
215
  export function createClient(options: ClientOptions): RecapiClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.17.1",
3
+ "version": "0.18.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/client.js CHANGED
@@ -530,7 +530,8 @@ export function createClient(options) {
530
530
  globalThis.document?.addEventListener?.('visibilitychange', onVisibility);
531
531
  globalThis.window?.addEventListener?.('pagehide', flushOnHide);
532
532
 
533
- return {
533
+ let drawRow = null;
534
+ const client = {
534
535
  /**
535
536
  * Records an interaction: updates the local history immediately (so the
536
537
  * next `recommend()` reflects it) and queues the event. Level 0 is an
@@ -551,12 +552,16 @@ export function createClient(options) {
551
552
  * `value` is what the buyer paid for a purchase's line (0 for a free
552
553
  * line), `currency` its ISO 4217 code (three letters, any case); a
553
554
  * currency needs a value. An invalid pair throws, as a bad level does.
555
+ * Without a `recommendationId` key, an event above level 0 carries the
556
+ * id a card's link brought to the page (`#rec_…` or `?rec=`), which it
557
+ * takes out of the address.
554
558
  */
555
- track(itemId, level, { recommendationId: explicit, value, currency } = {}) {
559
+ track(itemId, level, options = {}) {
556
560
  start();
561
+ const { value, currency } = options;
557
562
  // A fallback list has a null id, and a page passing it on must not
558
563
  // send `null` or lose the item's earlier, real attribution.
559
- const recommendationId = explicit ?? undefined;
564
+ let recommendationId = options.recommendationId ?? undefined;
560
565
  if (typeof level === 'string' && Object.hasOwn(LEVEL_NAMES, level)) level = LEVEL_NAMES[level];
561
566
  if (!Number.isInteger(level) || level < -10 || level > 10) {
562
567
  throw new RecapiError(
@@ -569,9 +574,16 @@ export function createClient(options) {
569
574
  // must not fail it. Nothing is kept: in the history it would make the
570
575
  // API refuse every later list. The line never quotes the visitor's id.
571
576
  if (!isId(itemId)) {
572
- report(new RecapiError('invalid_request', idRule('itemId')), true);
577
+ // An empty id is most often the quick start's tag pasted before its
578
+ // ITEM_ID was set: the line says which constant to fill in.
579
+ const rule = itemId === '' ? "itemId is empty, nothing sent: set ITEM_ID in recapi's tag to this page's product id" : idRule('itemId');
580
+ report(new RecapiError('invalid_request', rule), true);
573
581
  return;
574
582
  }
583
+ // The landing view: without consent nothing on the device remembers
584
+ // the list the visitor clicked, so the card's link carried its id. A
585
+ // page that passes the key reads the address itself (the shop rows).
586
+ if (level > 0 && !Object.hasOwn(options, 'recommendationId')) recommendationId = landed() ?? undefined;
575
587
  if (quiet) return;
576
588
  const t = now();
577
589
  let attributed = recommendationId;
@@ -780,8 +792,63 @@ export function createClient(options) {
780
792
  globalThis.document?.removeEventListener?.('visibilitychange', onVisibility);
781
793
  globalThis.window?.removeEventListener?.('pagehide', flushOnHide);
782
794
  return flush();
795
+ },
796
+
797
+ /**
798
+ * Fills `slot` (an element or a selector) with a row of up to 4 product
799
+ * cards, drawn from each item's `name`, `url`, `picture`, `price` (and
800
+ * `currency`) metadata, once it comes within 400px of the screen. Each
801
+ * link carries its list's id. Rows asked for together share one call. The
802
+ * row hides when no card can be drawn; under the `bought_together`
803
+ * placement, `heading` shows only over a product bought with this one.
804
+ * Does nothing outside a browser.
805
+ *
806
+ * @param {Element | string} slot
807
+ * @param {{ placement?: string, contextItemId?: string, heading?: string }} [options]
808
+ */
809
+ row(slot, options) {
810
+ if (typeof globalThis.document === 'undefined') return;
811
+ // Rows called in one task still reach the drawer in one task, in order.
812
+ drawRow ??= import('./row.js').then(({ rows }) => rows(client));
813
+ drawRow.then((draw) => draw(slot, options), (error) => globalThis.console?.warn('recapi: the row failed to load:', error));
783
814
  }
784
815
  };
816
+ return client;
817
+ }
818
+
819
+ /**
820
+ * The shape of an id the API makes (internal/ids: rec_ and hex), the only one
821
+ * read from an address: any other value is the site's own. Internal, shared
822
+ * with row.js; index.js doesn't export it.
823
+ */
824
+ export const REC_ID = /^rec_[0-9a-f]+$/;
825
+
826
+ /**
827
+ * The recommendation id a card's link brought to this page, taken out of the
828
+ * address so a copied or shared link doesn't credit strangers' visits; null
829
+ * when there is none, or outside a browser. The fragment first (no server or
830
+ * page cache sees it), then `?rec=`; the address keeps everything else.
831
+ */
832
+ function landed() {
833
+ const { location: here, history: past } = globalThis;
834
+ if (typeof here?.href !== 'string' || typeof past?.replaceState !== 'function') return null;
835
+ const url = new URL(here.href);
836
+ let rec = null;
837
+ if (REC_ID.test(url.hash.slice(1))) {
838
+ rec = url.hash.slice(1);
839
+ url.hash = '';
840
+ } else if (REC_ID.test(url.searchParams.get('rec') ?? '')) {
841
+ // ?rec=1 or ?rec=newest is the site's own parameter: it stays, and isn't sent.
842
+ rec = url.searchParams.get('rec');
843
+ // Not URLSearchParams.toString(): the site's other parameters keep their exact text.
844
+ const query = url.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
845
+ url.search = query;
846
+ }
847
+ if (rec === null) return null;
848
+ try {
849
+ past.replaceState(past.state, '', url.href.replace(/#$/, ''));
850
+ } catch {}
851
+ return rec;
785
852
  }
786
853
 
787
854
  /**
package/src/row.js ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * The ready row of product cards (`recapi.row()`). The Shopify, WooCommerce
3
+ * and Magento rows follow the same rules; a site of any other kind gets them
4
+ * from one call instead of writing them. Loaded by the first `row()` call
5
+ * only: a site that draws its own list never downloads it. The page a card
6
+ * opens reads the link's id back with client.js's `landed()`.
7
+ *
8
+ * @module row
9
+ */
10
+
11
+ import { REC_ID } from './client.js';
12
+
13
+ /** A row shows 4 cards: recapi counts every item of a list as shown. */
14
+ const ROW = 4;
15
+
16
+ // :where() weighs nothing, so any rule of the site's restyles the cards. Four
17
+ // across, two where four would be narrower than 150px (a phone). The height
18
+ // is held while the list loads, so the page doesn't jump.
19
+ const CSS = ':where(.recapi-row[aria-busy=true]){min-height:20rem}' +
20
+ ':where(.recapi-row ul){display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start;list-style:none;margin:0;padding:0}' +
21
+ ':where(.recapi-row a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}' +
22
+ ':where(.recapi-row img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}' +
23
+ ':where(.recapi-row .recapi-price){font-weight:600}';
24
+
25
+ const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
26
+
27
+ /** Only http(s) addresses: a `javascript:` link in metadata must never reach the page. */
28
+ function web(address) {
29
+ if (typeof address !== 'string') return null;
30
+ try {
31
+ const url = new URL(address, location.href);
32
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * A card's link with its list's id: in the fragment, unless the address has
40
+ * its own (the site's, not ours to overwrite), it is the page already open (a
41
+ * fragment wouldn't load it, so no view), or the id isn't one `landed()` reads
42
+ * from a fragment.
43
+ */
44
+ function carry(url, recommendationId) {
45
+ if (!recommendationId) return url;
46
+ const open = url.href.split('#')[0] === location.href.split('#')[0];
47
+ if (url.hash || open || !REC_ID.test(recommendationId)) url.searchParams.set('rec', recommendationId);
48
+ else url.hash = recommendationId;
49
+ return url;
50
+ }
51
+
52
+ /** The page's currency, as shops print it for search engines. */
53
+ function pageCurrency() {
54
+ const tag = document.querySelector('meta[property="product:price:currency"],meta[property="og:price:currency"],meta[itemprop="priceCurrency"]');
55
+ return tag?.getAttribute('content') || null;
56
+ }
57
+
58
+ /**
59
+ * The client's `row()`: rows asked for in the same task share one call
60
+ * (billed as one, no product on two rows), made once any of them comes
61
+ * within 400px of the screen. State lives here, per client, never at module
62
+ * level: two copies of this file may load side by side.
63
+ *
64
+ * @param {{ recommendLists: Function }} client
65
+ */
66
+ export function rows(client) {
67
+ let group = null;
68
+ let sheet = false;
69
+ let unpriced = false;
70
+
71
+ const style = () => {
72
+ if (sheet) return;
73
+ sheet = true;
74
+ // A constructed sheet passes a site's `style-src 'self'` CSP, which
75
+ // refuses a <style> element; browsers before Safari 16.4 get the element.
76
+ try {
77
+ const css = new CSSStyleSheet();
78
+ css.replaceSync(CSS);
79
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, css];
80
+ } catch {
81
+ const el = document.createElement('style');
82
+ el.textContent = CSS;
83
+ document.head.append(el);
84
+ }
85
+ };
86
+
87
+ const hide = (el) => {
88
+ el.removeAttribute('aria-busy');
89
+ // Not only [hidden]: any display rule of the site's beats that one.
90
+ el.hidden = true;
91
+ el.style.setProperty('display', 'none', 'important');
92
+ };
93
+
94
+ const card = ({ metadata: m }, recommendationId, money) => {
95
+ const link = m && m.available !== false && typeof m.name === 'string' ? web(m.url) : null;
96
+ if (!link) return null;
97
+ let price = typeof m.price === 'string' ? m.price : '';
98
+ if (typeof m.price === 'number') {
99
+ const currency = typeof m.currency === 'string' ? m.currency : money;
100
+ try {
101
+ price = new Intl.NumberFormat(document.documentElement.lang || undefined, { style: 'currency', currency }).format(m.price);
102
+ } catch {
103
+ unpriced = true;
104
+ }
105
+ }
106
+ const picture = web(m.picture);
107
+ return `<li><a href="${escape(carry(link, recommendationId).href)}">` +
108
+ `${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}` +
109
+ `<span class="recapi-name">${escape(m.name)}</span>` +
110
+ `${price ? `<span class="recapi-price">${escape(price)}</span>` : ''}</a></li>`;
111
+ };
112
+
113
+ const draw = (row, list) => {
114
+ const { el, placement, heading } = row;
115
+ // A popular fallback is not what was bought together: that row stays away.
116
+ const together = placement === 'bought_together';
117
+ const money = pageCurrency();
118
+ const cards = list.fallback && together ? [] : list.items.map((item) => ({ html: card(item, list.recommendationId, money), why: item.why })).filter(({ html }) => html);
119
+ if (!cards.length) {
120
+ if (list.items.length) {
121
+ const missing = ['name', 'url'].filter((key) => list.items.every(({ metadata }) => typeof metadata?.[key] !== 'string'));
122
+ console.warn(`recapi: no card to draw: send each item's metadata with ${missing.join(' and ') || 'a name and an http(s) url'} (PUT /v1/items)`);
123
+ }
124
+ return hide(el);
125
+ }
126
+ // The title only over a real pair: a product nobody bought with another
127
+ // yet gets similar ones, true cards under a false title.
128
+ const titled = heading && (!together || cards.some(({ why }) => why === 'bought_together'));
129
+ el.innerHTML = `${titled ? `<h2 class="recapi-heading">${escape(heading)}</h2>` : ''}<ul role="list">${cards.map(({ html }) => html).join('')}</ul>`;
130
+ el.removeAttribute('aria-busy');
131
+ };
132
+
133
+ const fill = async (members) => {
134
+ try {
135
+ const lists = await client.recommendLists({
136
+ lists: members.map(({ placement, contextItemId }) => ({
137
+ count: ROW,
138
+ ...(placement ? { placement } : {}),
139
+ ...(contextItemId ? { contextItemId } : {})
140
+ }))
141
+ });
142
+ members.forEach((row, k) => draw(row, lists[k]));
143
+ if (unpriced) {
144
+ unpriced = false;
145
+ console.warn('recapi: prices left out: a number needs a currency, in the item\'s metadata (currency: \'EUR\') or the page\'s <meta property="product:price:currency" content="EUR">');
146
+ }
147
+ } catch (error) {
148
+ // recommendLists() rejects only on a bad request: the page loses no more than its rows.
149
+ members.forEach(({ el }) => hide(el));
150
+ console.warn('recapi:', error);
151
+ }
152
+ };
153
+
154
+ const watch = (members) => {
155
+ if (typeof IntersectionObserver !== 'function') return fill(members);
156
+ // Each list is billed and counted as shown: a visitor who never scrolls
157
+ // down saw none.
158
+ const observer = new IntersectionObserver((entries) => {
159
+ if (!entries.some((entry) => entry.isIntersecting)) return undefined;
160
+ observer.disconnect();
161
+ return fill(members);
162
+ }, { rootMargin: '0px 0px 400px 0px' });
163
+ for (const { el } of members) observer.observe(el);
164
+ return undefined;
165
+ };
166
+
167
+ return (slot, { placement, contextItemId, heading } = {}) => {
168
+ const el = typeof slot === 'string' ? document.querySelector(slot) : slot;
169
+ if (!el) {
170
+ console.warn(`recapi: no element ${slot} on this page for the row`);
171
+ return;
172
+ }
173
+ style();
174
+ el.classList.add('recapi-row');
175
+ el.setAttribute('aria-busy', 'true');
176
+ if (!group) {
177
+ group = [];
178
+ queueMicrotask(() => {
179
+ const members = group;
180
+ group = null;
181
+ watch(members);
182
+ });
183
+ }
184
+ // The same slot twice in one task is one row, with the last options.
185
+ group = [...group.filter((row) => row.el !== el), { el, placement, contextItemId, heading }];
186
+ };
187
+ }