@recapi/client 0.10.0 → 0.11.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.
Files changed (3) hide show
  1. package/README.md +40 -4
  2. package/package.json +1 -1
  3. package/src/shopify.js +44 -20
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.10.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.11.0/index.js';
39
39
 
40
40
  const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com', consent: false });
41
41
  // From your cookie banner, once the visitor agrees: recapi.setConsent(true).
@@ -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,6 +168,24 @@ 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`
@@ -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,6 +393,9 @@ 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
@@ -1011,6 +1044,9 @@ minifier, to keep zero dev dependencies.
1011
1044
 
1012
1045
  ## Changes
1013
1046
 
1047
+ - 2026-11-19: version 0.11.0. The Shopify snippet's product pages get a
1048
+ second row, bought together, in the same call (`boughtTogether` turns it
1049
+ off or retitles it), and a refused top-up keeps the cards already drawn.
1014
1050
  - 2026-11-18: version 0.10.0. `shopify.js`, served beside `index.js`
1015
1051
  with its day of cache: the code of the Shopify pieces, which now hold only
1016
1052
  the shop's keys and Liquid values, so later fixes reach a shop with no new
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Browser and Node client for the recapi recommendation API: local decayed history, event batching, attribution.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
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);