@recapi/client 0.17.2 → 0.18.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.17.2/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.18.1/index.js';
39
39
 
40
40
  const ITEM_ID = ''; // this page's product id
41
41
 
@@ -90,20 +90,18 @@ const recapi = createClient({
90
90
  // itemId is that page's own id: an empty one sends nothing.
91
91
  recapi.track(itemId, 'view');
92
92
 
93
- // Show recommendations. If recapi is slow, failing or at your plan's limit,
94
- // recommend() resolves with popular items instead, and with an empty list if
95
- // those fail too or your key is refused (hide the slot): no try/catch needed. Give the widget's
96
- // container a CSS min-height so the page doesn't jump when the items arrive.
97
- // Below the fold, ask only once it nears the screen: each list is billed
98
- // and counted as shown, and many visitors never scroll that far.
99
- const slot = document.getElementById('recommendations');
100
- const observer = new IntersectionObserver(async (entries) => {
101
- if (!entries.some((entry) => entry.isIntersecting)) return;
102
- observer.disconnect();
103
- const { items } = await recapi.recommend({ count: 8, tagsAny: ['sports'] });
104
- render(slot, items); // [{ itemId, score, slot, why, metadata }]
105
- }, { rootMargin: '0px 0px 400px 0px' });
106
- observer.observe(slot);
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'] });
107
105
 
108
106
  // Later, the user clicks a recommended item and lands on its page (a
109
107
  // view). No need to pass the recommendation id: the SDK remembers which
@@ -296,6 +294,13 @@ fixture, and a change to the served code must keep every older piece
296
294
  working. The quick start fills in the current version, your address and your
297
295
  project (`jssdk.Shopify`).
298
296
 
297
+ `shopify.js` keeps what only Shopify gives: the page's data, the product
298
+ lookup for items without metadata, the currency, the consent banner, the
299
+ pasted options. The rules every row shares (lazy ask, link with the list's
300
+ id, hiding, the bought-together title, card styles) come from `cards.js`,
301
+ which [the ready row](#the-ready-row) uses too. Each piece's rows are pinned
302
+ to the byte in `test/fixtures/shopify/<version>/rows.txt`.
303
+
299
304
  Both files name themselves (`platform: 'shopify/<version>'`, sent as
300
305
  `?platform=` on every call), so recapi words its setup hints for Shopify.
301
306
 
@@ -778,6 +783,8 @@ for (const item of items) {
778
783
  a secret key: call the API from your backend for that.
779
784
  - **`recommendLists({ lists, exclude, allowRepeats })`**: several rows in
780
785
  one call, see [below](#several-rows-in-one-call).
786
+ - **`row(slot, { placement, contextItemId, heading })`**: a ready row, see
787
+ [The ready row](#the-ready-row).
781
788
  - **`popular({ tagsAny, tagsAll, count })`** resolves to `{ items: [{ itemId, score, why, metadata }] }`.
782
789
  A public key goes in `?key=`, so the response can be cached by a CDN.
783
790
  [How the key is sent](#how-the-key-is-sent) gives the reason for the rest.
@@ -813,6 +820,32 @@ const [similar, more] = await recapi.recommendLists({
813
820
  });
814
821
  ```
815
822
 
823
+ ### The ready row
824
+
825
+ `row(slot, { placement, contextItemId, heading })` fills `slot` (an element
826
+ or a selector) with up to 4 cards, the shop rows' rules in one call:
827
+
828
+ - It holds the slot's height and asks only once the slot is within 400px
829
+ of the screen. Rows called together share one billed call, with no
830
+ product on two rows.
831
+ - A card needs the item's `name` and an http(s) `url` metadata; `picture`
832
+ and `price` show when present. A number price takes the item's `currency`,
833
+ else the page's `<meta property="product:price:currency">`. An item with
834
+ `available: false` is skipped.
835
+ - Each link carries its list's id, which the page it opens reads (see
836
+ [Consent](#consent-and-eprivacy)).
837
+ - The row hides when no card can be drawn; the console names the missing
838
+ keys. Under the `bought_together` placement, `heading` shows only over a
839
+ product bought with this one, and the row stays away when recapi answers
840
+ with popular items.
841
+ - Its styles weigh nothing (`:where`), so any rule of yours restyles it
842
+ (`.recapi-row ul`, `a`, `img`, `.recapi-heading`, `.recapi-name`,
843
+ `.recapi-price`), and pass a `style-src 'self'` CSP.
844
+
845
+ There are no other options: for another look, draw `recommend()`'s list.
846
+ The file (`row.js`, and `cards.js` it shares with the shop rows) loads on
847
+ the first call only.
848
+
816
849
  ### Errors and troubleshooting
817
850
 
818
851
  Every failure is a `RecapiError` with `code`, `status` and `message`. The
@@ -1036,27 +1069,14 @@ A site that needs no banner (outside the EU, or with its own legal basis)
1036
1069
  passes `consent: true`. Without consent, the SDK never reads or writes storage
1037
1070
  and creates no anonymous id. The history and the attribution map live in memory for the
1038
1071
  current page only. A single-page app keeps attribution. On a multi-page
1039
- site, a click that loads the item's page is not attributed unless you
1040
- pass the id yourself, for example in the link. A fragment (`#${recommendationId}`,
1041
- read from `location.hash`) avoids a page cache miss, as the shop rows above do;
1042
- a query also reaches pages that read the id on the server:
1043
-
1044
- ```js
1045
- // On the listing page: link each item with its recommendation id
1046
- // (null when the list is the popular fallback: then leave it out of the link).
1047
- const { recommendationId, items } = await recapi.recommend({ count: 8 });
1048
- // href = recommendationId ? `/p/${item.itemId}?rec=${recommendationId}` : `/p/${item.itemId}`
1049
-
1050
- // On the item's page:
1051
- const url = new URL(location.href);
1052
- const rec = url.searchParams.get('rec');
1053
- recapi.track('item-77', 'view', { recommendationId: rec }); // null: automatic attribution
1054
- // Then drop it, so a copied or shared address doesn't credit strangers to that list.
1055
- if (rec !== null) {
1056
- url.searchParams.delete('rec');
1057
- history.replaceState(history.state, '', url);
1058
- }
1059
- ```
1072
+ site, a card's link carries its list's id: `row()` writes it, and the page
1073
+ it opens credits it with its first `track()` above level 0 that passes no
1074
+ `recommendationId`, then takes it out of the address so a shared link
1075
+ credits nobody. A list you draw yourself carries it the same way: end each
1076
+ link with `#${recommendationId}` (no fragment when it is null, a fallback).
1077
+ `?rec=<id>` is read too, for pages that need the id on the server. Either
1078
+ way only an id recapi makes (`rec_` and hex digits) is read: any other
1079
+ `#…` or `?rec=` value is the site's own and stays.
1060
1080
 
1061
1081
  Events are still sent, without `anon_id`. Don't call `track()` if you
1062
1082
  need no network at all. Withdrawing consent deletes the stored data.
@@ -1118,6 +1138,15 @@ minifier, to keep zero dev dependencies.
1118
1138
 
1119
1139
  ## Changes
1120
1140
 
1141
+ - 2026-11-24: version 0.18.1. No visible change: Shopify's row takes the
1142
+ rules it shares with `recapi.row()` from one file, `cards.js`.
1143
+ - 2026-11-24: version 0.18.0. `recapi.row(slot, { placement, contextItemId,
1144
+ heading })` draws a ready row of product cards from the items' metadata
1145
+ ([The ready row](#the-ready-row)). `track()` above level 0 without a
1146
+ `recommendationId` key reads the id a card's link brought (`#rec_…` or
1147
+ `?rec=rec_…`, nothing else) and takes it out of the address, so a click is credited without
1148
+ consent.
1149
+
1121
1150
  - 2026-11-24: version 0.17.2. `track()` with an empty item id (the
1122
1151
  quick start's tag before its `ITEM_ID` is set) still sends nothing, and
1123
1152
  its console line now says to set `ITEM_ID`.
package/index.d.ts CHANGED
@@ -132,6 +132,7 @@ export interface RecommendListsParams {
132
132
  /** An item's reason code: map the ones you want to your own label, show none for an unknown one. */
133
133
  export type ReasonCode =
134
134
  | 'for_you' | 'similar' | 'next' | 'bought_together' | 'trending' | 'popular' | 'new' | 'explore' | 'more'
135
+ | 'viewed_earlier'
135
136
  | (string & {});
136
137
 
137
138
  /** The object stored with the item (`PUT /v1/items`, `metadata`): name, picture, link, price... */
@@ -176,6 +177,14 @@ export interface PopularResult {
176
177
  */
177
178
  export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
178
179
 
180
+ /** `row()`'s only options: a site that wants another look draws `recommend()`'s list itself. */
181
+ export interface RowOptions {
182
+ placement?: string;
183
+ contextItemId?: string;
184
+ /** Printed over the row; under the `bought_together` placement only over a product bought with this one. */
185
+ heading?: string;
186
+ }
187
+
179
188
  export interface RecapiClient {
180
189
  /**
181
190
  * `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 +206,11 @@ export interface RecapiClient {
197
206
  /** This device's anonymous id; null without consent or under Do Not Track. */
198
207
  getAnonId(): string | null;
199
208
  destroy(): Promise<void>;
209
+ /**
210
+ * Draws up to 4 cards from each item's `name`, `url`, `picture`, `price` and `currency` metadata into `slot` once it nears
211
+ * the screen, each link carrying its list's id. Rows asked for together share one call. Hides when no card can be drawn.
212
+ */
213
+ row(slot: Element | string, options?: RowOptions): void;
200
214
  }
201
215
 
202
216
  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.2",
3
+ "version": "0.18.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/cards.js ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The rules of every recommendation row, recapi.row()'s and the shop
3
+ * platforms': changed here once. Each row keeps its own markup, which shops
4
+ * have styled.
5
+ *
6
+ * @module cards
7
+ */
8
+
9
+ import { REC_ID } from './client.js';
10
+
11
+ /** recapi counts every item of a list as shown: a spare could be credited a view it never caused. */
12
+ export const ROW = 4;
13
+
14
+ // :where() weighs nothing: any rule of the site's restyles the cards. Two
15
+ // across where four would be narrower than 150px (a phone).
16
+ export const GRID = 'display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start';
17
+
18
+ export const cardStyle = (scope) => `:where(${scope} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
19
+ `:where(${scope} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
20
+ `:where(${scope} .recapi-price){font-weight:600}`;
21
+
22
+ export const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
23
+
24
+ /** Only http(s): a `javascript:` link in metadata must never reach the page. */
25
+ export function web(address) {
26
+ if (typeof address !== 'string') return null;
27
+ try {
28
+ const url = new URL(address, location.href);
29
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ export const cardLink = (metadata) => (metadata?.available !== false && typeof metadata?.name === 'string' ? web(metadata.url) : null);
36
+
37
+ /**
38
+ * The list's id in the fragment, which no server or crawler sees, unless the
39
+ * address has its own (not ours to overwrite), it is the page already open (a
40
+ * fragment wouldn't load it, so no view), or the page wouldn't read it back.
41
+ */
42
+ export function carry(url, recommendationId) {
43
+ if (!recommendationId) return url;
44
+ const open = url.href.split('#')[0] === location.href.split('#')[0];
45
+ if (url.hash || open || !REC_ID.test(recommendationId)) url.searchParams.set('rec', recommendationId);
46
+ else url.hash = recommendationId;
47
+ return url;
48
+ }
49
+
50
+ /** The bought-together title only over a real pair: similar products under it would be true cards under a false title. */
51
+ export const paired = (cards) => cards.some(({ why }) => why === 'bought_together');
52
+
53
+ /** Not only [hidden]: any display rule of the site's beats that one. */
54
+ export function hide(el) {
55
+ el.hidden = true;
56
+ el.style.setProperty('display', 'none', 'important');
57
+ }
58
+
59
+ /**
60
+ * `then` once any element comes within 400px of the screen: each list is
61
+ * billed and counted as shown, and a visitor who never scrolls down saw none.
62
+ */
63
+ export function near(elements, then) {
64
+ if (typeof IntersectionObserver !== 'function') return then();
65
+ const observer = new IntersectionObserver((entries) => {
66
+ if (!entries.some((entry) => entry.isIntersecting)) return undefined;
67
+ observer.disconnect();
68
+ return then();
69
+ }, { rootMargin: '0px 0px 400px 0px' });
70
+ for (const el of elements) observer.observe(el);
71
+ return undefined;
72
+ }
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(
@@ -575,6 +580,10 @@ export function createClient(options) {
575
580
  report(new RecapiError('invalid_request', rule), true);
576
581
  return;
577
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;
578
587
  if (quiet) return;
579
588
  const t = now();
580
589
  let attributed = recommendationId;
@@ -783,8 +792,63 @@ export function createClient(options) {
783
792
  globalThis.document?.removeEventListener?.('visibilitychange', onVisibility);
784
793
  globalThis.window?.removeEventListener?.('pagehide', flushOnHide);
785
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));
786
814
  }
787
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;
788
852
  }
789
853
 
790
854
  /**
package/src/row.js ADDED
@@ -0,0 +1,139 @@
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 { GRID, ROW, cardLink, cardStyle, carry, escape, hide, near, paired, web } from './cards.js';
12
+
13
+ // The height is held while the list loads, so the page doesn't jump.
14
+ const CSS = ':where(.recapi-row[aria-busy=true]){min-height:20rem}' +
15
+ `:where(.recapi-row ul){${GRID};list-style:none;margin:0;padding:0}${cardStyle('.recapi-row')}`;
16
+
17
+ /** The page's currency, as shops print it for search engines. */
18
+ function pageCurrency() {
19
+ const tag = document.querySelector('meta[property="product:price:currency"],meta[property="og:price:currency"],meta[itemprop="priceCurrency"]');
20
+ return tag?.getAttribute('content') || null;
21
+ }
22
+
23
+ /**
24
+ * The client's `row()`: rows asked for in the same task share one call
25
+ * (billed as one, no product on two rows), made once any of them comes
26
+ * within 400px of the screen. State lives here, per client, never at module
27
+ * level: two copies of this file may load side by side.
28
+ *
29
+ * @param {{ recommendLists: Function }} client
30
+ */
31
+ export function rows(client) {
32
+ let group = null;
33
+ let sheet = false;
34
+ let unpriced = false;
35
+
36
+ const style = () => {
37
+ if (sheet) return;
38
+ sheet = true;
39
+ // A constructed sheet passes a site's `style-src 'self'` CSP, which
40
+ // refuses a <style> element; browsers before Safari 16.4 get the element.
41
+ try {
42
+ const css = new CSSStyleSheet();
43
+ css.replaceSync(CSS);
44
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, css];
45
+ } catch {
46
+ const el = document.createElement('style');
47
+ el.textContent = CSS;
48
+ document.head.append(el);
49
+ }
50
+ };
51
+
52
+ const away = (el) => {
53
+ el.removeAttribute('aria-busy');
54
+ hide(el);
55
+ };
56
+
57
+ const card = ({ metadata: m }, recommendationId, money) => {
58
+ const link = cardLink(m);
59
+ if (!link) return null;
60
+ let price = typeof m.price === 'string' ? m.price : '';
61
+ if (typeof m.price === 'number') {
62
+ const currency = typeof m.currency === 'string' ? m.currency : money;
63
+ try {
64
+ price = new Intl.NumberFormat(document.documentElement.lang || undefined, { style: 'currency', currency }).format(m.price);
65
+ } catch {
66
+ unpriced = true;
67
+ }
68
+ }
69
+ const picture = web(m.picture);
70
+ return `<li><a href="${escape(carry(link, recommendationId).href)}">` +
71
+ `${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}` +
72
+ `<span class="recapi-name">${escape(m.name)}</span>` +
73
+ `${price ? `<span class="recapi-price">${escape(price)}</span>` : ''}</a></li>`;
74
+ };
75
+
76
+ const draw = (row, list) => {
77
+ const { el, placement, heading } = row;
78
+ // A popular fallback is not what was bought together: that row stays away.
79
+ const together = placement === 'bought_together';
80
+ const money = pageCurrency();
81
+ const cards = list.fallback && together ? [] : list.items.map((item) => ({ html: card(item, list.recommendationId, money), why: item.why })).filter(({ html }) => html);
82
+ if (!cards.length) {
83
+ if (list.items.length) {
84
+ const missing = ['name', 'url'].filter((key) => list.items.every(({ metadata }) => typeof metadata?.[key] !== 'string'));
85
+ 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)`);
86
+ }
87
+ return away(el);
88
+ }
89
+ const titled = heading && (!together || paired(cards));
90
+ el.innerHTML = `${titled ? `<h2 class="recapi-heading">${escape(heading)}</h2>` : ''}<ul role="list">${cards.map(({ html }) => html).join('')}</ul>`;
91
+ el.removeAttribute('aria-busy');
92
+ };
93
+
94
+ const fill = async (members) => {
95
+ try {
96
+ const lists = await client.recommendLists({
97
+ lists: members.map(({ placement, contextItemId }) => ({
98
+ count: ROW,
99
+ ...(placement ? { placement } : {}),
100
+ ...(contextItemId ? { contextItemId } : {})
101
+ }))
102
+ });
103
+ members.forEach((row, k) => draw(row, lists[k]));
104
+ if (unpriced) {
105
+ unpriced = false;
106
+ 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">');
107
+ }
108
+ } catch (error) {
109
+ // recommendLists() rejects only on a bad request: the page loses no more than its rows.
110
+ members.forEach(({ el }) => away(el));
111
+ console.warn('recapi:', error);
112
+ }
113
+ };
114
+
115
+ // Each list is billed and counted as shown: a visitor who never scrolls
116
+ // down saw none.
117
+ const watch = (members) => near(members.map(({ el }) => el), () => fill(members));
118
+
119
+ return (slot, { placement, contextItemId, heading } = {}) => {
120
+ const el = typeof slot === 'string' ? document.querySelector(slot) : slot;
121
+ if (!el) {
122
+ console.warn(`recapi: no element ${slot} on this page for the row`);
123
+ return;
124
+ }
125
+ style();
126
+ el.classList.add('recapi-row');
127
+ el.setAttribute('aria-busy', 'true');
128
+ if (!group) {
129
+ group = [];
130
+ queueMicrotask(() => {
131
+ const members = group;
132
+ group = null;
133
+ watch(members);
134
+ });
135
+ }
136
+ // The same slot twice in one task is one row, with the last options.
137
+ group = [...group.filter((row) => row.el !== el), { el, placement, contextItemId, heading }];
138
+ };
139
+ }
package/src/shopify.js CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import { createClient, localStorageAdapter, memoryStorage } from './index.js';
16
+ import { GRID, ROW, cardLink, cardStyle, carry, escape, hide, near, paired, web } from './cards.js';
16
17
 
17
18
  /**
18
19
  * The theme's piece: the visitor's consent, the cart attribute the pixel
@@ -96,14 +97,11 @@ export async function shopifyTheme(options) {
96
97
  const { shopCurrency } = options;
97
98
  if (options.customerId) recapi.identify(String(options.customerId));
98
99
 
99
- // What the shop's admin says the product is: recapi names the product from
100
- // it when the shop sent no catalog (no products export, no webhook), so a
101
- // shop that only pasted this snippet gets similar products by name. Only
102
- // words: recapi never lets them overwrite what the shop sent itself. Sent
103
- // once per product per browser, again when the shop changes them. They say
104
- // nothing about the visitor, so they go with or without consent; what was
105
- // sent is remembered only where recapi may store (else once per page view,
106
- // which recapi writes only when the words changed).
100
+ // What the shop's admin says the product is: recapi names products from it
101
+ // when the shop sent no catalog (no export, no webhook), never over what
102
+ // the shop sent. Nothing about the visitor, so sent with or without
103
+ // consent: once per product per browser where recapi may store, else once
104
+ // per view (recapi writes only words that changed).
107
105
  const product = handle && { handle, title: options.product.title ?? null, type: options.product.type ?? null, tags: options.product.tags ?? null };
108
106
  const describe = () => {
109
107
  const body = JSON.stringify({ products: [product] });
@@ -139,15 +137,12 @@ export async function shopifyTheme(options) {
139
137
  body,
140
138
  keepalive
141
139
  });
142
- // While recapi has no catalog from the shop, it asks, in the answer above,
143
- // for a page of the shop's own product list, which every Shopify storefront
144
- // serves at /products.json to its visitors: a page of 250 products per page
145
- // view, so a shop that only pasted this snippet has its whole catalog named
146
- // after a few product views, its owner's own click-through included. recapi
147
- // keeps the progress, so this needs nothing stored on the device, and hands
148
- // each page to one browser at a time. Only once the browser is idle and the
149
- // row (when it is being drawn) is on the page; a refused or failed read
150
- // waits for the next page view, which gets the same page again.
140
+ // While recapi has no catalog from the shop, its answer above asks for a
141
+ // page of the shop's /products.json, which every storefront serves its
142
+ // visitors: 250 products a view, so a bare shop is named after a few views.
143
+ // recapi keeps the progress and hands each page to one browser at a time.
144
+ // Only once the browser is idle and the row drawn; a failed read waits for
145
+ // the next view, which gets the same page.
151
146
  let drawing = null;
152
147
  const idle = (callback) => (window.requestIdleCallback ? window.requestIdleCallback(callback, { timeout: 10000 }) : setTimeout(callback, 2000));
153
148
  const relay = async (page) => {
@@ -169,11 +164,8 @@ export async function shopifyTheme(options) {
169
164
  await seen(JSON.stringify({ page, products }), false).catch(() => null);
170
165
  };
171
166
  if (product && !editor) describe();
172
- // A card's link carries its recommendation: without consent nothing on the
173
- // device remembers which list showed the product. In the fragment, which no
174
- // server or crawler sees: each list's new ?rec= looks like another page.
175
- // ?rec= is still read: links already out there, and the cards that can't use
176
- // a fragment (below).
167
+ // A card's link carries its list's id (cards.js carry): without consent
168
+ // nothing on the device remembers which list showed the product.
177
169
  const inFragment = /^#rec_[0-9a-f]+$/;
178
170
  const viewed = () => {
179
171
  const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
@@ -196,53 +188,30 @@ export async function shopifyTheme(options) {
196
188
 
197
189
  // Fills <div id="recapi-recommendations">&nbsp;</div> wherever the theme has one.
198
190
  const slot = document.getElementById('recapi-recommendations');
199
- // A product row in the theme's colours and fonts. :where() weighs
200
- // nothing, so any rule of the theme's restyles the cards. Four cards
201
- // across, as the theme's product grids show them, two where four would be
202
- // narrower than 150px (a phone). The page-width rule is for themes with
203
- // no page-width class of their own (below).
204
- const styleOf = (id) => '<style>' +
205
- `:where(#${id}){display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start;align-content:start}` +
191
+ // A product row in the theme's colours and fonts. The page-width rule is
192
+ // for themes with no page-width class of their own (below).
193
+ const styleOf = (id) => `<style>:where(#${id}){${GRID};align-content:start}` +
206
194
  ':where(#recapi-recommendations.page-width,.recapi-bought-together.page-width){box-sizing:border-box;max-width:var(--page-width,1200px);margin-inline:auto;padding-inline:1.5rem}' +
207
- `:where(#${id} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
208
- `:where(#${id} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
209
- `:where(#${id} .recapi-price){font-weight:600}` +
210
- '</style>';
195
+ `${cardStyle(`#${id}`)}</style>`;
211
196
  const style = styleOf('recapi-recommendations');
212
- // Dawn's Custom Liquid section spans the whole screen (no page-width box),
213
- // so a row there took 15 narrow columns from the left edge: it keeps to
214
- // the page width through the theme's own page-width class (Dawn's max-width
215
- // and side margins). Horizon's puts its content in the page's column
216
- // (section--page-width) unless the shop chose full width.
197
+ // Dawn's Custom Liquid section spans the whole screen: a row there took 15
198
+ // narrow columns, so it takes the theme's page-width class. Horizon's
199
+ // section--page-width keeps to the page's column already.
217
200
  const wide = slot && !slot.closest('.page-width, .section--page-width');
218
201
  if (wide) slot.classList.add('page-width');
219
- // Dawn and the themes built on it hide every empty div (div:empty
220
- // { display: none }): a slot pasted empty, as the quick start once
221
- // printed it, has no box, never comes near the screen, and the row would
222
- // never load. Its style, there at once, makes it not empty. A slot still
223
- // without a box is hidden by the theme or a section around it: the row
224
- // loads if that changes, and the shop's developer is told why it doesn't.
202
+ // Dawn hides every empty div: a slot pasted empty (as the quick start once
203
+ // printed it) would have no box, never come near the screen, never load.
204
+ // Its style, there at once, fills it. A slot still without a box is hidden
205
+ // by the theme: the row loads if that changes, and the developer is told.
225
206
  if (slot && !slot.getClientRects().length) {
226
207
  slot.insertAdjacentHTML('afterbegin', style);
227
208
  if (!slot.getClientRects().length) console.warn('recapi: the page hides #recapi-recommendations (display: none), so the row loads only once it shows');
228
209
  }
229
- // Not only [hidden]: any display rule of the theme's beats that one, and
230
- // would leave a blank where the row should be.
231
- const hide = () => {
232
- slot.hidden = true;
233
- slot.style.setProperty('display', 'none', 'important');
234
- };
235
210
  // Each row its own placement, so the dashboard and the lift test tell them
236
211
  // apart. An unconfigured placement serves as the default one and joins its
237
212
  // lift test, so a shop's settings carry over.
238
213
  const { pageType } = options;
239
214
  const placement = handle ? 'product' : pageType === 'cart' ? 'cart' : 'section';
240
- // The row shows 4 cards. recapi counts every product of a list as shown,
241
- // so a spare asked for would get an impression and could be credited a
242
- // view it never caused: the row asks for 4. recapi learns products from
243
- // events and may not know one sold out or was deleted; one more list,
244
- // without the products already listed, then fills the gap.
245
- const ROW = 4;
246
215
  // A product page has a second row under the first: what shoppers bought
247
216
  // with the product on screen, under its own placement, which recapi serves
248
217
  // as bought together until the shop gives it settings of its own. The
@@ -253,15 +222,13 @@ export async function shopifyTheme(options) {
253
222
  : null;
254
223
  const rows = [{ placement, ...(handle ? { contextItemId: handle } : {}) }];
255
224
  if (together !== null) rows.push({ placement: 'bought_together', contextItemId: handle });
256
- // Through the call that takes all of a page's rows: billed as one, the
257
- // history sent once, and no product on two rows, the first row's first.
258
- // `counts` holds [row, count] pairs, the lists come back in their order.
225
+ // One call for all of a page's rows: billed once, the history sent once,
226
+ // no product on two rows. `counts` holds [row, count] pairs.
259
227
  const ask = (counts, exclude) => recapi.recommendLists({
260
228
  lists: counts.map(([row, count]) => ({ count, ...rows[row] })),
261
229
  ...(exclude.length ? { exclude } : {})
262
230
  });
263
231
  const draw = async () => {
264
- const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
265
232
  // Prices are in the currency's subunit (100000 is ¥1,000), in the
266
233
  // visitor's currency. A number and a symbol need no translation.
267
234
  const currency = window.Shopify?.currency?.active;
@@ -269,33 +236,14 @@ export async function shopifyTheme(options) {
269
236
  let money = null;
270
237
  try { if (currency && lang) money = new Intl.NumberFormat(lang, { style: 'currency', currency }); } catch {}
271
238
  const tag = (amount) => `<span class="recapi-price">${escape(amount)}</span>`;
272
- // Only http(s) addresses: metadata is the shop's, but a javascript: link
273
- // must never reach the page.
274
- const web = (address) => {
275
- try {
276
- const url = new URL(address, location.href);
277
- return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
278
- } catch {
279
- return null;
280
- }
281
- };
282
- // ?rec= only where a fragment can't carry the id: the address has its own
283
- // (a theme's, not ours to overwrite), it's the page already open (a
284
- // fragment wouldn't load it, so no view), or the page wouldn't read it back.
285
- const carry = (url, recommendationId) => {
286
- const open = url.href.split('#')[0] === location.href.split('#')[0];
287
- if (recommendationId && (url.hash || open || !inFragment.test(`#${recommendationId}`))) url.searchParams.set('rec', recommendationId);
288
- else if (recommendationId) url.hash = recommendationId;
289
- return url;
290
- };
291
- // An item's metadata (sent with PUT /v1/items) draws its card when it has
292
- // a name and a link, with no request to Shopify. Its price is text shown
239
+ // An item's metadata draws its card with no request to Shopify. Its price is text shown
293
240
  // as it is, or a number in the shop's currency: a visitor browsing in
294
241
  // another one gets Shopify's converted price from the lookup instead, as
295
242
  // does a product Shopify's webhook marked "available": false: it may be
296
243
  // sold out, or its stock untracked, and only the lookup knows which.
244
+ const anchor = (href, src, name, price) => `<a href="${escape(href)}">${src === null ? '' : `<img src="${escape(src)}" alt="" loading="lazy">`}<span>${escape(name)}</span>${price}</a>`;
297
245
  const fromMetadata = (metadata, recommendationId) => {
298
- const link = metadata?.available !== false && typeof metadata?.url === 'string' && typeof metadata.name === 'string' ? web(metadata.url) : null;
246
+ const link = cardLink(metadata);
299
247
  if (!link) return null;
300
248
  let price = '';
301
249
  if (typeof metadata.price === 'string') price = tag(metadata.price);
@@ -304,8 +252,7 @@ export async function shopifyTheme(options) {
304
252
  if (money) price = tag(money.format(metadata.price));
305
253
  }
306
254
  carry(link, recommendationId);
307
- const picture = typeof metadata.picture === 'string' ? web(metadata.picture) : null;
308
- return `<a href="${escape(link.href)}">${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}<span>${escape(metadata.name)}</span>${price}</a>`;
255
+ return anchor(link.href, web(metadata.picture)?.href ?? null, metadata.name, price);
309
256
  };
310
257
  // Shopify's CDN resizes on ?width=: a card needs no 2048 px original.
311
258
  const image = (src) => (src ? `${src}${src.includes('?') ? '&' : '?'}width=400` : '');
@@ -315,10 +262,10 @@ export async function shopifyTheme(options) {
315
262
  return `${url.pathname}${url.search}${url.hash}`;
316
263
  };
317
264
  const fromProduct = (p, recommendationId) => (p?.available
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>`
265
+ ? anchor(path(p.url, recommendationId), image(p.featured_image), p.title, money && Number.isFinite(p.price_min) ? tag(money.format(p.price_min / 100)) : '')
319
266
  : null);
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.
267
+ // A list's cards in recapi's order, with their reason codes; those
268
+ // without metadata from the product's page data, one request each.
322
269
  const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata, why }) => {
323
270
  let html = fromMetadata(metadata, recommendationId);
324
271
  if (!html) {
@@ -329,19 +276,17 @@ export async function shopifyTheme(options) {
329
276
  }))).filter(Boolean);
330
277
  const lists = await ask(rows.map((_, row) => [row, ROW]), []);
331
278
  const cards = await Promise.all(lists.map(cardsOf));
332
- // Only a full list that couldn't fill its row: a shorter one means recapi
279
+ // recapi may not know a product sold out or was deleted: one more call
280
+ // fills a full list's gaps, without any product listed. A shorter list
333
281
  // has no more to give, and a fallback (recapi slow, down or at a limit)
334
- // would only wait again. One more call for the short rows, without any
335
- // product either row listed.
282
+ // would only wait again.
336
283
  const short = lists.map((_, row) => row).filter((row) => cards[row].length < ROW && lists[row].items.length >= ROW && !lists[row].fallback);
337
284
  if (short.length) {
338
285
  // Refused (a key revoked mid-page): the rows keep the cards they have.
339
286
  const more = await ask(short.map((row) => [row, ROW - cards[row].length]), lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)))
340
287
  .catch((error) => { console.warn('recapi:', error); return []; });
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.
288
+ // A popular top-up fills the first row's gap (what it shows anyway when
289
+ // recapi is down), never bought together's.
345
290
  await Promise.all(more.map(async (list, k) => {
346
291
  if (short[k] === 1 && list.fallback) return;
347
292
  cards[short[k]] = [...cards[short[k]], ...await cardsOf(list)];
@@ -349,39 +294,25 @@ export async function shopifyTheme(options) {
349
294
  }
350
295
  const [first, second = []] = cards.map((row) => row.slice(0, ROW));
351
296
  if (first.length) slot.innerHTML = style + first.map(({ html }) => html).join('');
352
- else hide();
353
- // Each row shows or hides on its own. A popular fallback is not what was
354
- // bought together, so that row then stays away. The theme's own h2 rule
355
- // styles its title.
297
+ else hide(slot);
298
+ // Each row shows or hides on its own; a popular fallback is not what was
299
+ // bought together, so that row stays away.
356
300
  if (second.length && !lists[1].fallback) {
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
301
+ // Without a pair they show untitled, the first row's gap apart, and
360
302
  // 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>`);
303
+ const pair = paired(second);
304
+ const title = together && pair ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
305
+ const more = pair ? '' : '<style>:where(.recapi-bought-together.recapi-more){margin-top:1rem}</style>';
306
+ slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}${pair ? '' : ' recapi-more'}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${more}${second.map(({ html }) => html).join('')}</div></div>`);
365
307
  }
366
308
  };
367
309
  // recommendLists() rejects only on a bad request: a page still loses no more than its rows.
368
310
  const fill = () => (drawing = draw().catch((error) => {
369
- hide();
311
+ hide(slot);
370
312
  console.warn('recapi:', error);
371
313
  }));
372
- // Only once the row comes within 400px of the screen, as Shopify's own
373
- // themes load theirs: each list is billed and counted as shown, and a
374
- // shopper who never scrolls down saw none. The div's min-height holds its
375
- // place meanwhile. The view above went at once.
376
- if (slot && typeof IntersectionObserver !== 'function') await fill();
377
- else if (slot) {
378
- const observer = new IntersectionObserver((entries) => {
379
- if (!entries.some((entry) => entry.isIntersecting)) return undefined;
380
- observer.disconnect();
381
- return fill();
382
- }, { rootMargin: '0px 0px 400px 0px' });
383
- observer.observe(slot);
384
- }
314
+ // The view above went at once.
315
+ if (slot) await near([slot], fill);
385
316
  }
386
317
 
387
318
  // Product URLs end in /products/<handle>, the theme's item id.