@recapi/client 0.10.0 → 0.11.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.
Files changed (3) hide show
  1. package/README.md +62 -19
  2. package/package.json +5 -1
  3. package/src/shopify.js +44 -20
package/README.md CHANGED
@@ -19,7 +19,7 @@ needs a newer browser moves this floor and says so under [Changes](#changes).
19
19
 
20
20
  On every change to the library, CI runs what a shop page relies on in
21
21
  Chromium, Firefox and WebKit, Safari's engine
22
- ([`scripts/e2e/browsers.test.js`](../../scripts/e2e/browsers.test.js)): the
22
+ (recapi's browser test suite): the
23
23
  lists of `recommend()` and `popular()`, a view and a cart credited to the
24
24
  recommendation, the history after a reload, the queued events sent when the
25
25
  page is left or hidden, consent and Global Privacy Control. That WebKit is
@@ -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.10.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.11.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).
@@ -159,8 +159,8 @@ nothing to paste again. A file of its own rather than more exports of
159
159
  products (not after the popular fallback, nor after a list shorter than 4,
160
160
  which is all recapi has). It asks through `recommendLists()`, the call that
161
161
  takes all of a page's rows ([Several rows in one call](#several-rows-in-one-call)):
162
- the page has one row, so it costs one call (two with a top-up), billed as
163
- one recommendation each. Each row asks for its own placement: `product` on
162
+ a page costs one call (two with a top-up), billed as one recommendation
163
+ each, a product page's second row included (below). Each row asks for its own placement: `product` on
164
164
  product pages, `cart` on the cart page (Shopify's `request.page_type`),
165
165
  `section` elsewhere, so the Overview's "By placement" and a lift test tell
166
166
  them apart; one not configured in the dashboard serves as `default`, with
@@ -168,11 +168,29 @@ nothing to paste again. A file of its own rather than more exports of
168
168
  snippet keeps it, with every row on `default` and 6 products asked for,
169
169
  until it pastes this one: its served lists and CTR then read on 4 products
170
170
  a list, and "By placement" splits `default` into the rows above.
171
+
172
+ From 0.11.0 a product page has a second row, under the first: what
173
+ shoppers bought with the product on screen, placement `bought_together`,
174
+ which recapi serves as its Bought together list until the shop gives that
175
+ placement settings of its own. It goes in the same call as the first row,
176
+ so it costs nothing more, and the API keeps a product off both rows. Its
177
+ cards go in a `<div id="recapi-bought-together">` the snippet adds after the
178
+ slot, styled like the first row, under an `<h2 class="recapi-heading">`
179
+ holding the `boughtTogether` option: "Often bought together" by default,
180
+ any text of the shop's, `''` for no title, `false` for no second row.
181
+ Pieces pasted before 0.11.0 get the row too, with the default title.
182
+
183
+ Each row shows or hides on its own: an empty first row hides its slot and
184
+ leaves the second; a short row is topped up in the one more call, with
185
+ only the short rows, without any product either row listed. A refused top-up
186
+ (a key revoked mid-page) keeps the cards already drawn. The second row
187
+ never shows the popular fallback (recapi slow, down or at a limit): popular
188
+ items are not what was bought together.
171
189
  Each card shows the picture (resized by Shopify's
172
190
  CDN with `?width=400`), the title and `price_min` formatted with
173
191
  `Intl.NumberFormat` in `Shopify.currency.active` and the page's `lang`
174
192
  (no price if either is missing). An item whose
175
- [metadata](../../docs/api.md#item-metadata) has a `name` and an http(s)
193
+ [metadata](https://recapi.io/docs/api#item-metadata) has a `name` and an http(s)
176
194
  `url` skips that lookup: its card is drawn from `name`, `url`, `picture`
177
195
  (http(s) only) and `price` (text shown as it is, or a number in the
178
196
  shop's currency, `{{ shop.currency }}`, shown only to visitors browsing in
@@ -181,7 +199,7 @@ nothing to paste again. A file of its own rather than more exports of
181
199
  snippet can't send metadata: the shop sends it with `PUT /v1/items`, and
182
200
  marks a sold-out product inactive there, since no lookup checks it. The
183
201
  products export upload and the product webhooks (the quick start's step 4,
184
- [API](../../docs/api.md#post-v1shopifywebhooks--shopifys-product-webhooks))
202
+ [API](https://recapi.io/docs/api#post-v1shopifywebhooks--shopifys-product-webhooks))
185
203
  fill it without code; a card whose metadata says `available: false` (maybe
186
204
  sold out) is looked up instead. A default style makes them a product row
187
205
  in the theme's colours and fonts; all its selectors sit inside
@@ -258,7 +276,7 @@ may be added, never renamed or dropped, as shops never paste again.
258
276
 
259
277
  | Call | Options |
260
278
  |---|---|
261
- | `shopifyTheme(options)` (theme) | `apiKey`, `baseUrl`, `project`, `platform`; `product` (`handle`, `title`, `type`, `tags`: Liquid's `product`, all `null` off a product page); `shopCurrency`; `customerId` (`''` for a guest); `pageType` (`request.page_type`). Resolves once the page's work is set up. |
279
+ | `shopifyTheme(options)` (theme) | `apiKey`, `baseUrl`, `project`, `platform`; `product` (`handle`, `title`, `type`, `tags`: Liquid's `product`, all `null` off a product page); `shopCurrency`; `customerId` (`''` for a guest); `pageType` (`request.page_type`); `boughtTogether` (from 0.11.0: the product page's second row's title, `false` for none). Resolves once the page's work is set up. |
262
280
  | `shopifyPixel(options, name, event)` (pixel) | `apiKey`, `baseUrl`, `project`, `platform`, `browser` (the sandbox's); `name` is the subscribed event's, `event` Shopify's. Other names are ignored. |
263
281
 
264
282
  `test/shopify.test.js` runs both pieces with `src/shopify.js` as the quick
@@ -355,6 +373,18 @@ placement" and a lift test tell them apart. A placement not configured in
355
373
  the dashboard serves as `default`, with its settings and its running lift
356
374
  test, so a shop that set `default` up keeps it.
357
375
 
376
+ A product page has a second row under the first: "Often bought together"
377
+ (translatable in the `recapi` text domain, reworded with the
378
+ `recapi_bought_together_heading` filter), under the `bought_together`
379
+ placement, which serves the Bought together list type until the shop
380
+ configures it. Both lists come from the same `recommendLists` call, billed
381
+ as one, the first row first so no product is on both. The script adds the
382
+ row as `<div id="recapi-bought-together">` (with its heading) right after
383
+ the first row's div once it has cards: the printed page doesn't change,
384
+ and a row with nothing to show leaves nothing. One row empty never hides
385
+ the other. *WooCommerce → recapi* turns it off ("Your product pages",
386
+ option `recapi_bought_together`); the cart and shortcode rows never have it.
387
+
358
388
  The widget fills it like the Shopify snippet's, once it nears the screen,
359
389
  asking for the 4 products it shows (recapi counts every product of a list
360
390
  as shown, so a spare would get an impression and could be credited a view it
@@ -363,11 +393,14 @@ never caused), loading them in one request to WooCommerce's public Store API
363
393
  out of stock. A full list that leaves a gap that way (without a secret key
364
394
  recapi may not know a product sold out) is topped up once with a second
365
395
  list of as many products, excluding the first's; a fallback list is not.
396
+ One more call tops up every row left short, excluding every product either
397
+ row listed, and if it is refused (a key revoked mid-page) the rows keep the
398
+ cards they had.
366
399
  The row asks through `recommendLists()`, the call that takes all of a page's
367
400
  rows, billed as one recommendation with no product on two rows ([Several
368
401
  rows in one call](#several-rows-in-one-call)). A page has one recapi row (the
369
402
  product page's spot, a block and `[recapi]` never show two), so a page costs
370
- one call, two only when the top-up runs. Items whose [metadata](../../docs/api.md#item-metadata)
403
+ one call, two only when the top-up runs. Items whose [metadata](https://recapi.io/docs/api#item-metadata)
371
404
  has a `name` and an http(s) `url` are left out of that request and drawn
372
405
  from it, as in the Shopify snippet (a number `price` is in the shop's
373
406
  currency, `woocommerce_currency`, and shown only while the visitor browses
@@ -477,7 +510,7 @@ install has neither header's effect: both are comments there.
477
510
 
478
511
  ### Magento
479
512
 
480
- The Magento 2 module ([`sdk/php/magento`](../php/magento/README.md)) prints
513
+ The Magento 2 module ([guide](https://recapi.io/docs/magento)) prints
481
514
  the SDK on every storefront page for views and add-to-carts, and sends
482
515
  orders from the server with the PHP library. With consent, its script
483
516
  mirrors the visitor's id and clicked recommendations into a first-party
@@ -611,7 +644,7 @@ the library as is.
611
644
 
612
645
  ### Showing why an item is listed
613
646
 
614
- Every item carries `why`, a short [reason code](../../docs/api.md#reason-codes)
647
+ Every item carries `why`, a short [reason code](https://recapi.io/docs/api#reason-codes)
615
648
  that names no item of the visitor's history, so any page can show it. Pick
616
649
  your own words, and show no label for a code you don't know (new ones may
617
650
  come):
@@ -650,13 +683,13 @@ for (const item of items) {
650
683
  ### Client methods
651
684
 
652
685
  - **`track(itemId, level, { recommendationId? })`**: `level` is any integer
653
- 0–10 of the [recommended scale](../../docs/api.md#interaction-levels) (3
686
+ 0–10 of the [recommended scale](https://recapi.io/docs/api#interaction-levels) (3
654
687
  opened, 5 strong interest, 10 the action that matters most), or one of its
655
688
  shop names `'view'`, `'cart'` and `'purchase'` (3, 5 and 10). `'reject'`
656
689
  (or any level -1 to -10) is an explicit "not interested": the item is
657
690
  never recommended to this user again until a positive event on it. Use
658
691
  it for a rejection control only, never for skips or bounces
659
- ([Rejections](../../docs/api.md#rejections)). Updates the
692
+ ([Rejections](https://recapi.io/docs/api#rejections)). Updates the
660
693
  local history at once and queues the event with `anon_id`, `user_id`, a
661
694
  timestamp and a fresh `event_id` (the idempotency
662
695
  key, reused on retries). Level 0 means an impression: it is sent but does
@@ -669,7 +702,7 @@ for (const item of items) {
669
702
  - **`recommend({ count, tagsAny, tagsAll, exclude, contextItemId, placement, discovery })`**
670
703
  resolves to `{ recommendationId, fallback, items: [{ itemId, score, slot, why, metadata }] }`.
671
704
  `metadata` is the object you stored with the item
672
- ([Item metadata](../../docs/api.md#item-metadata): name, picture, link,
705
+ ([Item metadata](https://recapi.io/docs/api#item-metadata): name, picture, link,
673
706
  price…), absent when it has none, so you can render the list without a
674
707
  lookup. `why` is the item's [reason code](#showing-why-an-item-is-listed).
675
708
  It never retries and waits at most 1.5 s (less if `timeoutMs` is lower):
@@ -714,7 +747,7 @@ const [similar, more] = await recapi.recommendLists({
714
747
  });
715
748
  ```
716
749
 
717
- ### Errors
750
+ ### Errors and troubleshooting
718
751
 
719
752
  Every failure is a `RecapiError` with `code`, `status` and `message`. The
720
753
  API error body supplies these when present. Client-side codes are
@@ -725,6 +758,10 @@ transient failures apart. `recommend()` and `popular()` resolve with a
725
758
  list instead of rejecting on `network`, `timeout`, 5xx, 429, 401 and 403
726
759
  errors, and report the error to `onError` (see [Fallback](#fallback)).
727
760
 
761
+ Each error code, its cause and its fix: [Errors](https://recapi.io/docs/errors).
762
+ No lists yet, empty lists, only popular items, key errors: [Troubleshooting](https://recapi.io/docs/troubleshooting).
763
+ Shops: the [Shopify](https://recapi.io/docs/shopify), [WooCommerce](https://recapi.io/docs/woocommerce) and [Magento](https://recapi.io/docs/magento) guides.
764
+
728
765
  ### Fallback
729
766
 
730
767
  When recapi does not answer `recommend()` within 1.5 s, cannot be
@@ -770,8 +807,8 @@ untouched. An empty or `null` `contextItemId` just means none.
770
807
 
771
808
  ### History
772
809
 
773
- The history follows [docs/history-spec.md](../../docs/history-spec.md)
774
- exactly, and the shared vectors in `spec/history_vectors.json` check it.
810
+ The history follows the history spec all recapi libraries share, and its
811
+ test vectors check it.
775
812
  Each item has a score that decays with a 7-day half-life. The SDK keeps
776
813
  the 50 heaviest items plus an ordered list of the 20 most recent distinct
777
814
  items. Requests carry `history: [[item_id, weight, age_s], …]` and
@@ -1011,6 +1048,12 @@ minifier, to keep zero dev dependencies.
1011
1048
 
1012
1049
  ## Changes
1013
1050
 
1051
+ - 2026-11-19: version 0.11.1. No code change: this page's links lead to
1052
+ the public docs, and an errors section names the errors and
1053
+ troubleshooting pages.
1054
+ - 2026-11-19: version 0.11.0. The Shopify snippet's product pages get a
1055
+ second row, bought together, in the same call (`boughtTogether` turns it
1056
+ off or retitles it), and a refused top-up keeps the cards already drawn.
1014
1057
  - 2026-11-18: version 0.10.0. `shopify.js`, served beside `index.js`
1015
1058
  with its day of cache: the code of the Shopify pieces, which now hold only
1016
1059
  the shop's keys and Liquid values, so later fixes reach a shop with no new
@@ -1111,7 +1154,7 @@ minifier, to keep zero dev dependencies.
1111
1154
 
1112
1155
  ```sh
1113
1156
  npm test # node --test, zero dev dependencies
1114
- ../../scripts/node18.sh --test test/*.test.js # the same on Node 18, the floor
1157
+ "$(git rev-parse --show-toplevel)/scripts/node18.sh" --test test/*.test.js # the same on Node 18, the floor
1115
1158
  ```
1116
1159
 
1117
1160
  `make test` and CI run the tests on Node 18 as well as the current Node,
@@ -1121,7 +1164,7 @@ means changing `engines`, this README's first lines and
1121
1164
  `docs/development.md` together.
1122
1165
 
1123
1166
  The same steps in real browsers (Chromium, Firefox, WebKit): see
1124
- [Testing](../../docs/development.md#testing).
1167
+ "Testing" in the repository's development guide.
1125
1168
 
1126
1169
  The API embeds `src/*.js` (module `recapi/sdkjs`, `embed.go`) and serves
1127
1170
  them at `/sdk/<version>/`, where browsers cache every file but `index.js` for
@@ -1132,7 +1175,7 @@ each file's exports), and change the `/sdk/<version>/` paths in this
1132
1175
  README and `docs/api.md` (the quick start follows by itself). Never edit
1133
1176
  an existing entry of `published.json`.
1134
1177
  Once production runs that version, the release service has GitHub publish
1135
- it to npm as `@recapi/client` ([deployment.md](../../docs/deployment.md#publishing-the-javascript-library)):
1178
+ it to npm as `@recapi/client`:
1136
1179
  nobody runs `npm publish` by hand.
1137
1180
 
1138
1181
  Every older path, whatever its version number, redirects to the new
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "description": "Browser and Node client for the recapi recommendation API: local decayed history, event batching, attribution.",
5
+ "homepage": "https://recapi.io/docs",
6
+ "bugs": {
7
+ "url": "https://recapi.io/contact"
8
+ },
5
9
  "type": "module",
6
10
  "main": "./src/index.js",
7
11
  "types": "./index.d.ts",
package/src/shopify.js CHANGED
@@ -22,6 +22,7 @@ import { createClient, localStorageAdapter, memoryStorage } from './index.js';
22
22
  *
23
23
  * @param {{ apiKey: string, baseUrl: string, project: string, platform: string,
24
24
  * shopCurrency?: string|null, pageType?: string|null, customerId?: string|number|null,
25
+ * boughtTogether?: string|false,
25
26
  * product?: { handle: string|null, title?: string|null, type?: string|null, tags?: string[]|null }|null }} options
26
27
  */
27
28
  export async function shopifyTheme(options) {
@@ -193,12 +194,13 @@ export async function shopifyTheme(options) {
193
194
  const slot = document.getElementById('recapi-recommendations');
194
195
  // A product row in the theme's colours and fonts. :where() weighs
195
196
  // nothing, so any rule of the theme's restyles the cards.
196
- const style = '<style>' +
197
- ':where(#recapi-recommendations){display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:1rem;align-items:start;align-content:start}' +
198
- ':where(#recapi-recommendations a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}' +
199
- ':where(#recapi-recommendations img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}' +
200
- ':where(#recapi-recommendations .recapi-price){font-weight:600}' +
197
+ const styleOf = (id) => '<style>' +
198
+ `:where(#${id}){display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:1rem;align-items:start;align-content:start}` +
199
+ `:where(#${id} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
200
+ `:where(#${id} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
201
+ `:where(#${id} .recapi-price){font-weight:600}` +
201
202
  '</style>';
203
+ const style = styleOf('recapi-recommendations');
202
204
  // Dawn and the themes built on it hide every empty div (div:empty
203
205
  // { display: none }): a slot pasted empty, as the quick start once
204
206
  // printed it, has no box, never comes near the screen, and the row would
@@ -226,12 +228,23 @@ export async function shopifyTheme(options) {
226
228
  // events and may not know one sold out or was deleted; one more list,
227
229
  // without the products already listed, then fills the gap.
228
230
  const ROW = 4;
229
- // Through the call that takes all of a page's rows (billed as one, the
230
- // history sent once, no product on two rows): the page has this one.
231
- const ask = async (count, exclude) => (await recapi.recommendLists({
232
- lists: [{ count, placement, ...(handle ? { contextItemId: handle } : {}) }],
231
+ // A product page has a second row under the first: what shoppers bought
232
+ // with the product on screen, under its own placement, which recapi serves
233
+ // as bought together until the shop gives it settings of its own. The
234
+ // option is its title; false turns it off. Pieces pasted before it get the
235
+ // row too, with this title.
236
+ const together = handle && options.boughtTogether !== false
237
+ ? (typeof options.boughtTogether === 'string' ? options.boughtTogether : 'Often bought together')
238
+ : null;
239
+ const rows = [{ placement, ...(handle ? { contextItemId: handle } : {}) }];
240
+ if (together !== null) rows.push({ placement: 'bought_together', contextItemId: handle });
241
+ // Through the call that takes all of a page's rows: billed as one, the
242
+ // history sent once, and no product on two rows, the first row's first.
243
+ // `counts` holds [row, count] pairs, the lists come back in their order.
244
+ const ask = (counts, exclude) => recapi.recommendLists({
245
+ lists: counts.map(([row, count]) => ({ count, ...rows[row] })),
233
246
  ...(exclude.length ? { exclude } : {})
234
- }))[0];
247
+ });
235
248
  const draw = async () => {
236
249
  const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
237
250
  // Prices are in the currency's subunit (100000 is ¥1,000), in the
@@ -297,20 +310,31 @@ export async function shopifyTheme(options) {
297
310
  const response = await fetch(`${root}products/${encodeURIComponent(itemId)}.js`).catch(() => null);
298
311
  return fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId);
299
312
  }))).filter(Boolean);
300
- const list = await ask(ROW, []);
301
- let cards = await cardsOf(list);
302
- // Only a full list that couldn't fill the row: a shorter one means recapi
313
+ const lists = await ask(rows.map((_, row) => [row, ROW]), []);
314
+ const cards = await Promise.all(lists.map(cardsOf));
315
+ // Only a full list that couldn't fill its row: a shorter one means recapi
303
316
  // has no more to give, and a fallback (recapi slow, down or at a limit)
304
- // would only wait again.
305
- if (cards.length < ROW && list.items.length >= ROW && !list.fallback) {
306
- const more = await ask(ROW - cards.length, list.items.map(({ itemId }) => itemId));
307
- cards = [...cards, ...await cardsOf(more)];
317
+ // would only wait again. One more call for the short rows, without any
318
+ // product either row listed.
319
+ const short = lists.map((_, row) => row).filter((row) => cards[row].length < ROW && lists[row].items.length >= ROW && !lists[row].fallback);
320
+ if (short.length) {
321
+ // Refused (a key revoked mid-page): the rows keep the cards they have.
322
+ const more = await ask(short.map((row) => [row, ROW - cards[row].length]), lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)))
323
+ .catch((error) => { console.warn('recapi:', error); return []; });
324
+ await Promise.all(more.map(async (list, k) => { cards[short[k]] = [...cards[short[k]], ...await cardsOf(list)]; }));
308
325
  }
309
- cards = cards.slice(0, ROW);
310
- if (cards.length) slot.innerHTML = style + cards.join('');
326
+ const [first, second = []] = cards.map((row) => row.slice(0, ROW));
327
+ if (first.length) slot.innerHTML = style + first.join('');
311
328
  else hide();
329
+ // Each row shows or hides on its own. A popular fallback is not what was
330
+ // bought together, so that row then stays away. The theme's own h2 rule
331
+ // styles its title.
332
+ if (second.length && !lists[1].fallback) {
333
+ const title = together ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
334
+ slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${second.join('')}</div></div>`);
335
+ }
312
336
  };
313
- // recommendLists() rejects only on a bad request: a page still loses no more than the row.
337
+ // recommendLists() rejects only on a bad request: a page still loses no more than its rows.
314
338
  const fill = () => (drawing = draw().catch((error) => {
315
339
  hide();
316
340
  console.warn('recapi:', error);