@recapi/client 0.7.0 → 0.9.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,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.7.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.9.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).
@@ -134,7 +134,9 @@ in two places, both shown with your address in the dashboard's quick start:
134
134
  is the item id. recapi has no catalog of a Shopify shop, so the snippet
135
135
  asks for 6 and skips products that are sold out (`available: false`) or
136
136
  deleted (404). All 6 count as one served list: CTR and lift are per list,
137
- so they are unchanged. Each card shows the picture (resized by Shopify's
137
+ so they are unchanged. It asks through `recommendLists()`, the call that
138
+ takes all of a page's rows ([Several rows in one call](#several-rows-in-one-call)):
139
+ the page has one row, so it costs one call, billed as one recommendation. Each card shows the picture (resized by Shopify's
138
140
  CDN with `?width=400`), the title and `price_min` formatted with
139
141
  `Intl.NumberFormat` in `Shopify.currency.active` and the page's `lang`
140
142
  (no price if either is missing). An item whose
@@ -225,6 +227,9 @@ them needs no new SDK version (they import the served one), but it changes
225
227
  what every new Shopify shop pastes. The quick start fills in the current
226
228
  version, your address and your project (`jssdk.Shopify`).
227
229
 
230
+ Both files name themselves (`platform: 'shopify/<version>'`, sent as
231
+ `?platform=` on every call), so recapi words its setup hints for Shopify.
232
+
228
233
  ### WooCommerce
229
234
 
230
235
  [`woocommerce/recapi.php`](woocommerce/recapi.php) is a one-file WordPress
@@ -247,7 +252,27 @@ every page from `wp_footer`. The product id is the item id. It tracks:
247
252
  checkout alike: `is_order_received_page()`), with the order key checked,
248
253
  nothing for a failed or cancelled payment, and the order marked
249
254
  (`_recapi_counted` meta) so a reload prints nothing. A logged-in buyer's
250
- customer id is passed to `identify()` there.
255
+ customer id is passed to `identify()` there, even once the order is
256
+ counted. With a secret key saved (see
257
+ below) the shop's server also sends the order once it is paid, so a buyer
258
+ who pays off-site and never comes back, or blocks scripts, still counts:
259
+ on `woocommerce_payment_complete` and the `processing` and `completed`
260
+ statuses (cash on delivery, a bank transfer received, an order the merchant
261
+ enters), one `POST /v1/events` once the response is out (one try of 2 s, a
262
+ failure logged), each line dated when the order was paid, with an
263
+ `event_id` per order line. Whichever path comes first marks the order, so
264
+ it counts once. The buyer is the customer id, and the visitor id and the
265
+ recommendation of each clicked product from the `recapi` cookie, which the
266
+ script keeps (a day, only with consent, as the Magento module does) while a
267
+ key is saved; a guest without it gets `woocommerce-order-<id>` as
268
+ `anon_id`. The cookie is read only in the buyer's own request (not the
269
+ admin, WP-Cron, or a shop manager's call for another customer), and a
270
+ buyer sending `DNT: 1` or `Sec-GPC: 1` is not sent (the order is marked,
271
+ so a later status change doesn't send it either). Only orders paid since
272
+ the key was saved, or since the first request with a key after the update
273
+ that brought this path (`recapi_orders_since` option), go from the server:
274
+ older ones are in the past-orders file, whose upload skips only purchases
275
+ already sent live, so completing one later would count it twice.
251
276
 
252
277
  The checkout is the shop's own origin, so the purchase reads the state the
253
278
  product pages stored and is credited to the recommendation clicked: no
@@ -279,19 +304,55 @@ The script inserts it as `<h2 class="recapi-heading">` before the div once
279
304
  the cards fill, as text, so a row that stays hidden leaves no title. The
280
305
  shortcode shows none unless given one: `[recapi heading="You may also like"]`.
281
306
 
307
+ Each row asks for its own placement: `product` on product pages (the
308
+ Related products spot, or `[recapi]` in a product template), `cart` for
309
+ `[recapi]` on the cart page, `shortcode` elsewhere, so the Overview's "By
310
+ placement" and a lift test tell them apart. A placement not configured in
311
+ the dashboard serves as `default`, with its settings and its running lift
312
+ test, so a shop that set `default` up keeps it.
313
+
282
314
  The widget fills it like the Shopify snippet's, once it nears the screen,
283
- loading the 6 recommended products in one request to WooCommerce's public Store API
315
+ asking for the 4 products it shows (recapi counts every product of a list
316
+ as shown, so a spare would get an impression and could be credited a view it
317
+ never caused), loading them in one request to WooCommerce's public Store API
284
318
  (`/wc/store/v1/products?include=…`) and skipping those not purchasable or
285
- out of stock. Items whose [metadata](../../docs/api.md#item-metadata)
319
+ out of stock. A full list that leaves a gap that way (without a secret key
320
+ recapi may not know a product sold out) is topped up once with a second
321
+ list of as many products, excluding the first's; a fallback list is not.
322
+ The row asks through `recommendLists()`, the call that takes all of a page's
323
+ rows, billed as one recommendation with no product on two rows ([Several
324
+ rows in one call](#several-rows-in-one-call)). A page has one recapi row (the
325
+ product page's spot, a block and `[recapi]` never show two), so a page costs
326
+ one call, two only when the top-up runs. Items whose [metadata](../../docs/api.md#item-metadata)
286
327
  has a `name` and an http(s) `url` are left out of that request and drawn
287
328
  from it, as in the Shopify snippet (a number `price` is in the shop's
288
329
  currency, `woocommerce_currency`, and shown only while the visitor browses
289
- in it), so a row whose items all carry metadata needs no Store API call. Consent comes from the
290
- [WP Consent API](https://wordpress.org/plugins/wp-consent-api/)
291
- (`wp_has_consent('statistics')`, `wp_listen_for_consent_change`), which
292
- banner plugins feed and which reports allowed where no banner manages
293
- consent; without the API the plugin stores nothing, as the Shopify snippet
294
- does when its consent API fails to load. It declares compatibility with
330
+ in it), so a row whose items all carry metadata needs no Store API call.
331
+
332
+ Consent: the plugin keeps a visitor id on the device only with the
333
+ visitor's consent, and events without one train nothing, so WooCommerce →
334
+ recapi asks the merchant "How does your shop ask for cookie consent?"
335
+ (option `recapi_consent`):
336
+
337
+ - **A banner that feeds the [WP Consent API](https://wordpress.org/plugins/wp-consent-api/)**
338
+ (`wp-consent-api`, the reading until the merchant answers): Complianz,
339
+ CookieYes and others. `wp_has_consent('statistics')` at load, then
340
+ `wp_listen_for_consent_change`; the API reports allowed where no banner
341
+ manages consent.
342
+ - **Another banner, which calls recapi** (`banner`): once the visitor
343
+ accepts statistics cookies it runs `recapi.setConsent(true)` on every
344
+ page, and `recapi.setConsent(false)` if they withdraw. The page's head
345
+ defines `window.recapi` first, so a banner answering before the plugin's
346
+ module loads is heard.
347
+ - **No cookie banner needed** (`no-banner`): consent from the first page,
348
+ the reading the WP Consent API and Shopify give where no consent is
349
+ required. Do Not Track and Global Privacy Control still keep a visitor
350
+ out.
351
+
352
+ Until the merchant answers, a shop without the WP Consent API stores
353
+ nothing and sends events without an id, as the Shopify snippet does when its
354
+ consent API fails to load; the plugin list and WooCommerce → recapi then
355
+ show a notice that the shop isn't learning yet. It declares compatibility with
295
356
  WooCommerce's order tables (HPOS) and checkout blocks when installed as a
296
357
  plugin, and registers with the WP Consent API.
297
358
 
@@ -330,16 +391,20 @@ so recapi never sees or can guess the email), or without an email
330
391
  `woocommerce-order-<id>`. Only shop managers (`manage_woocommerce`) with
331
392
  the page's nonce get the file, and it reads orders 200 at a time through
332
393
  `wc_get_orders` (HPOS or not). The import skips rows already uploaded and
333
- purchases the order-received page already sent.
394
+ purchases the plugin already sent.
334
395
 
335
396
  `test/woocommerce.test.js` prints pages through PHP (`test/wordpress.php`
336
397
  stands in for WordPress, run by `scripts/php.sh`) and runs the printed
337
398
  script against the SDK. The quick start fills in the current version and
338
399
  your address (`jssdk.WooCommerce`).
339
400
 
401
+ The plugin names itself, so recapi words its setup hints for WooCommerce: the
402
+ browser script sends `?platform=woocommerce/<version>`, the shop's server
403
+ calls `User-Agent: recapi-woocommerce/<version>`.
404
+
340
405
  `scripts/e2e_woocommerce.sh` (CI job `woocommerce`) runs the plugin on a
341
406
  real, throwaway shop: WordPress and WooCommerce in Docker at pinned
342
- versions, twice: the newest (WordPress 7.1.4, WooCommerce 11.2.1, PHP 8.5)
407
+ versions, twice: the newest (WordPress 7.1.4, WooCommerce 11.3.0, PHP 8.5)
343
408
  and the oldest the plugin's header declares (WordPress 6.3, WooCommerce 8.3,
344
409
  PHP 7.4), the plugin taken from the quick start of a new recapi shop with
345
410
  its public key pasted, then a guest's browser (Playwright) on a product
@@ -526,6 +591,7 @@ for (const item of items) {
526
591
  | `apiKey` | required | `rk_pub_…` in browsers |
527
592
  | `baseUrl` | required | API origin |
528
593
  | `placement` | – | default placement for `recommend()` |
594
+ | `platform` | – | `<name>/<version>` of the integration making the calls (`'woocommerce/0.9.0'`), sent as `?platform=` on every request, never as a header (it would cost a CORS preflight) |
529
595
  | `storage` | localStorage, else memory | any `{ getItem, setItem, removeItem }` synchronous store |
530
596
  | `project` | first 16 chars of `apiKey` | storage namespace: key `recapi:v1:<project>` |
531
597
  | `flushIntervalMs` | `2000` | delay before queued events are sent |
@@ -567,6 +633,8 @@ for (const item of items) {
567
633
  happens when the call fails. The user's rejected items (the newest 200)
568
634
  are added to `exclude`, after yours, up to the API's limit of 500. The SDK does not send `explain`, which needs
569
635
  a secret key: call the API from your backend for that.
636
+ - **`recommendLists({ lists, exclude, allowRepeats })`**: several rows in
637
+ one call, see [below](#several-rows-in-one-call).
570
638
  - **`popular({ tagsAny, tagsAll, count })`** resolves to `{ items: [{ itemId, score, why, metadata }] }`.
571
639
  A public key goes in `?key=`, so the response can be cached by a CDN.
572
640
  [How the key is sent](#how-the-key-is-sent) gives the reason for the rest.
@@ -588,6 +656,20 @@ for (const item of items) {
588
656
  [Login and logout](#login-and-logout).
589
657
  - **`destroy()`** removes listeners and timers, then flushes.
590
658
 
659
+ ### Several rows in one call
660
+
661
+ A page with several rows asks for them in one call: the history is sent once
662
+ and the call is billed as one recommendation. Each list takes `recommend()`'s
663
+ parameters and resolves to its own result, in order, with its own
664
+ `recommendationId`. An item appears on one list only unless `allowRepeats`;
665
+ `exclude` applies to every list. A failure falls back list by list.
666
+
667
+ ```js
668
+ const [similar, more] = await recapi.recommendLists({
669
+ lists: [{ placement: 'product', count: 4, contextItemId: 'item-42' }, { placement: 'more', count: 8 }]
670
+ });
671
+ ```
672
+
591
673
  ### Errors
592
674
 
593
675
  Every failure is a `RecapiError` with `code`, `status` and `message`. The
@@ -877,7 +959,7 @@ key on a format change makes old data invisible.
877
959
  ## Size budget
878
960
 
879
961
  Budget: **6 KB gzip** after minification. The sources ship unminified with
880
- full JSDoc: 61 KB raw in five files, 21 KB as the API serves them (gzip -9),
962
+ full JSDoc: 66 KB raw in five files, 21 KB as the API serves them (gzip -9),
881
963
  and the browser caches them. With comments stripped and no
882
964
  minification they are 9 KB gzip. A bundler's minifier should bring
883
965
  that under the budget, but this has not been measured: the repo has no
@@ -885,6 +967,11 @@ minifier, to keep zero dev dependencies.
885
967
 
886
968
  ## Changes
887
969
 
970
+ - 2026-11-15: version 0.9.0. The `platform` option names the integration
971
+ making the calls (`?platform=woocommerce/0.9.0` on every request), so recapi
972
+ can word its setup hints for the shop's platform. Unset, requests are unchanged.
973
+ - 2026-11-14: version 0.8.0. `recommendLists()` asks for a page's rows in one
974
+ call, billed as one recommendation ([Several rows in one call](#several-rows-in-one-call)).
888
975
  - 2026-11-11: version 0.7.0. `consent` defaults to `false`: a client stores
889
976
  nothing on the device and sends no `anon_id` until `consent: true` or
890
977
  `setConsent(true)`, so a tag pasted as is keeps the promise that our script
package/index.d.ts CHANGED
@@ -69,6 +69,11 @@ export interface ClientOptions {
69
69
  project?: string;
70
70
  /** Default placement for `recommend()`. */
71
71
  placement?: string;
72
+ /**
73
+ * `<name>/<version>` of the integration making the calls, e.g.
74
+ * `'woocommerce/0.9.0'`: sent as `?platform=` on every request.
75
+ */
76
+ platform?: string;
72
77
  /** Default 2000. */
73
78
  flushIntervalMs?: number;
74
79
  /** Default 100, at most 1000. */
@@ -106,6 +111,15 @@ export interface RecommendParams {
106
111
  discovery?: number;
107
112
  }
108
113
 
114
+ export interface RecommendListsParams {
115
+ /** One result per list, in order; each list's `exclude` applies to it alone. */
116
+ lists: RecommendParams[];
117
+ /** Applies to every list. */
118
+ exclude?: string[];
119
+ /** Lets an item appear on more than one list. */
120
+ allowRepeats?: boolean;
121
+ }
122
+
109
123
  /** An item's reason code: map the ones you want to your own label, show none for an unknown one. */
110
124
  export type ReasonCode =
111
125
  | 'for_you' | 'similar' | 'next' | 'bought_together' | 'trending' | 'popular' | 'new' | 'explore' | 'more'
@@ -157,6 +171,8 @@ export interface RecapiClient {
157
171
  track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null }): void;
158
172
  /** Falls back to popular items on a network error, a timeout, a 5xx or a 429 (an empty list if those fail too), to an empty list on a 401 or 403; rejects on a bad request or a reply that isn't the API's. */
159
173
  recommend(params?: RecommendParams): Promise<RecommendResult>;
174
+ /** Several lists in one call, billed as one recommendation; falls back as `recommend()` does, list by list. */
175
+ recommendLists(params: RecommendListsParams): Promise<RecommendResult[]>;
160
176
  /** An empty list on a network error, a timeout, a 5xx, a 429, a 401 or a 403; rejects on a bad request or a reply that isn't the API's. */
161
177
  popular(params?: PopularParams): Promise<PopularResult>;
162
178
  identify(userId: string, options?: { history?: ServerSnapshot }): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.7.0",
3
+ "version": "0.9.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/client.js CHANGED
@@ -78,6 +78,9 @@ const PUBLIC_KEY_PREFIX = 'rk_pub_';
78
78
  * @property {string} [project] Storage namespace; defaults to the first 16
79
79
  * characters of the API key.
80
80
  * @property {string} [placement] Default placement for `recommend()`.
81
+ * @property {string} [platform] `<name>/<version>` of the integration making
82
+ * the calls (`woocommerce/0.9.0`), sent as `?platform=` on each request so
83
+ * recapi can word its setup hints for the shop's platform.
81
84
  * @property {number} [flushIntervalMs]
82
85
  * @property {number} [maxBatch]
83
86
  * @property {number} [timeoutMs] Per-request timeout.
@@ -114,6 +117,7 @@ export function createClient(options) {
114
117
  } = options ?? {};
115
118
  if (typeof apiKey !== 'string' || !apiKey) throw new TypeError('apiKey is required');
116
119
  if (typeof baseUrl !== 'string' || !baseUrl) throw new TypeError('baseUrl is required');
120
+ if (options.platform !== undefined && typeof options.platform !== 'string') throw new TypeError('platform must be a string');
117
121
  const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
118
122
  if (typeof fetchImpl !== 'function') throw new TypeError('fetch is not available; pass options.fetch');
119
123
 
@@ -152,7 +156,7 @@ export function createClient(options) {
152
156
  // A faulty error handler must not fail the page.
153
157
  }
154
158
  };
155
- const transport = createTransport({ baseUrl, apiKey, fetch: fetchImpl, timeoutMs });
159
+ const transport = createTransport({ baseUrl, apiKey, fetch: fetchImpl, timeoutMs, platform: options.platform });
156
160
  // A public key goes in the URL (no CORS preflight; popular() is CDN-cacheable),
157
161
  // any other key in the header (Node with a secret key).
158
162
  const auth = apiKey.startsWith(PUBLIC_KEY_PREFIX) ? 'query' : 'header';
@@ -360,11 +364,30 @@ export function createClient(options) {
360
364
  return chain;
361
365
  }
362
366
 
363
- /** `POST /v1/recommendations`; remembers the shown items for attribution. */
364
- async function personalised(params, deadline) {
367
+ /**
368
+ * `POST /v1/recommendations` for `recommend()` (`call` undefined: one list)
369
+ * or `recommendLists()` (its `exclude` and `allowRepeats`); remembers each
370
+ * shown item under its own list's recommendation for attribution.
371
+ */
372
+ async function personalised(rows, call, deadline) {
365
373
  if (consent) reload();
366
374
  const wire = toWire(history, now(), config);
367
375
  const sentEmpty = wire.history.length === 0;
376
+ const row = (params, exclude) => ({
377
+ placement: params.placement ?? defaultPlacement,
378
+ count: params.count,
379
+ tags_any: params.tagsAny,
380
+ tags_all: params.tagsAll,
381
+ exclude,
382
+ context_item_id: params.contextItemId
383
+ });
384
+ const shared = call === undefined
385
+ ? row(rows[0], withRejected(rows[0].exclude, wire.rejected))
386
+ : {
387
+ placements: rows.map((params) => compact({ ...row(params, params.exclude), discovery: params.discovery })),
388
+ exclude: withRejected(call.exclude, wire.rejected),
389
+ allow_repeats: call.allowRepeats ? true : undefined
390
+ };
368
391
  const response = await transport.request({
369
392
  method: 'POST',
370
393
  path: '/v1/recommendations',
@@ -373,28 +396,31 @@ export function createClient(options) {
373
396
  body: compact({
374
397
  user_id: userId ?? undefined,
375
398
  anon_id: anonId ?? undefined,
376
- placement: params.placement ?? defaultPlacement,
377
- count: params.count,
378
- tags_any: params.tagsAny,
379
- tags_all: params.tagsAll,
380
- exclude: withRejected(params.exclude, wire.rejected),
381
- context_item_id: params.contextItemId,
399
+ ...shared,
382
400
  history: wire.history,
383
401
  recent: wire.recent,
384
- discovery: params.discovery
402
+ discovery: call === undefined ? rows[0].discovery : undefined
385
403
  })
386
404
  });
387
- if (typeof response?.recommendation_id !== 'string' || !Array.isArray(response.items)) {
405
+ const lists = call === undefined ? [response] : response?.lists;
406
+ if (!Array.isArray(lists) || lists.length !== rows.length ||
407
+ !lists.every((list) => typeof list?.recommendation_id === 'string' && Array.isArray(list.items))) {
388
408
  throw new RecapiError('invalid_response', 'malformed recommendations response');
389
409
  }
390
410
 
391
- const recommendationId = response.recommendation_id;
392
- const items = response.items.map((item) => toItem(item, item.slot));
411
+ const results = lists.map((list) => ({
412
+ recommendationId: list.recommendation_id,
413
+ fallback: false,
414
+ items: list.items.map((item) => toItem(item, item.slot))
415
+ }));
393
416
  mutate(() => {
394
417
  const t = now();
395
- for (const { itemId } of items) {
396
- shown.delete(itemId);
397
- shown.set(itemId, [recommendationId, t]);
418
+ // An item on two lists (allowRepeats) is credited to the last one.
419
+ for (const { recommendationId, items } of results) {
420
+ for (const { itemId } of items) {
421
+ shown.delete(itemId);
422
+ shown.set(itemId, [recommendationId, t]);
423
+ }
398
424
  }
399
425
  while (shown.size > MAX_SHOWN_ITEMS) shown.delete(shown.keys().next().value);
400
426
  // A snapshot is only trusted when we sent nothing, and merged once: a
@@ -408,7 +434,7 @@ export function createClient(options) {
408
434
  restored = true;
409
435
  }
410
436
  });
411
- return { recommendationId, fallback: false, items };
437
+ return results;
412
438
  }
413
439
 
414
440
  /**
@@ -429,22 +455,54 @@ export function createClient(options) {
429
455
  .map((item) => toItem(item, 'backfill'));
430
456
  }
431
457
 
432
- /** What `recommend()` answers instead of a list of its own: popular items, or none. */
433
- async function listInstead(error, params, deadline) {
458
+ /**
459
+ * What `recommend()` and `recommendLists()` answer instead of lists of
460
+ * their own: popular items, a request per list skipping the call's
461
+ * `exclude` and, unless `allowRepeats`, the earlier lists' items; once
462
+ * popular fails, the lists after it are empty without asking.
463
+ */
464
+ async function listsInstead(error, rows, { exclude = [], allowRepeats = false } = {}, deadline) {
434
465
  reportList(error);
435
- let items = [];
436
466
  // A refused key would be refused the popular list too.
437
- if (!keyRefused(error)) {
438
- try {
439
- items = await popularFallback(params, deadline);
440
- } catch (fallbackError) {
441
- // Down altogether, or the limit covers popular too. The page awaits
442
- // recommend() without a catch (the README says it may), so an empty
443
- // list it can hide beats a rejection that breaks it.
444
- reportList(fallbackError);
467
+ let failed = keyRefused(error);
468
+ const listed = [];
469
+ const results = [];
470
+ for (const params of rows) {
471
+ let items = [];
472
+ if (!failed) {
473
+ try {
474
+ items = await popularFallback({ ...params, exclude: [...exclude, ...(params.exclude ?? []), ...listed] }, deadline);
475
+ } catch (fallbackError) {
476
+ // Down altogether, or the limit covers popular too. The page awaits
477
+ // recommend() without a catch (the README says it may), so an empty
478
+ // list it can hide beats a rejection that breaks it.
479
+ reportList(fallbackError);
480
+ failed = true;
481
+ }
445
482
  }
483
+ if (!allowRepeats) listed.push(...items.map(({ itemId }) => itemId));
484
+ results.push({ recommendationId: null, fallback: true, items });
485
+ }
486
+ return results;
487
+ }
488
+
489
+ /** `recommend()` for one list (`call` undefined) and `recommendLists()`. */
490
+ async function recommendRows(rows, call) {
491
+ start();
492
+ const deadline = Math.min(timeoutMs, RECOMMEND_TIMEOUT_MS);
493
+ if (!rows.every((params) => usableContext(params.contextItemId))) {
494
+ // Unlike a failed call, nothing has read the stored rejections yet.
495
+ if (consent) reload();
496
+ const error = new RecapiError('invalid_request', idRule('contextItemId'));
497
+ const usable = rows.map((params) => (usableContext(params.contextItemId) ? params : { ...params, contextItemId: undefined }));
498
+ return listsInstead(error, usable, call, deadline);
499
+ }
500
+ try {
501
+ return await personalised(rows, call, deadline);
502
+ } catch (error) {
503
+ if (!sparesThePage(error)) throw error;
504
+ return listsInstead(error, rows, call, deadline);
446
505
  }
447
- return { recommendationId: null, fallback: true, items };
448
506
  }
449
507
 
450
508
  /**
@@ -549,20 +607,28 @@ export function createClient(options) {
549
607
  * items: Array<{ itemId: string, score: number, slot: string, why?: string, metadata?: object }> }>}
550
608
  */
551
609
  async recommend(params = {}) {
552
- start();
553
- const deadline = Math.min(timeoutMs, RECOMMEND_TIMEOUT_MS);
554
- if (!usableContext(params.contextItemId)) {
555
- // Unlike a failed call, nothing has read the stored rejections yet.
556
- if (consent) reload();
557
- const error = new RecapiError('invalid_request', idRule('contextItemId'));
558
- return listInstead(error, { ...params, contextItemId: undefined }, deadline);
559
- }
560
- try {
561
- return await personalised(params, deadline);
562
- } catch (error) {
563
- if (!sparesThePage(error)) throw error;
564
- return listInstead(error, params, deadline);
610
+ return (await recommendRows([params]))[0];
611
+ },
612
+
613
+ /**
614
+ * Several lists (a page's rows) from one call, billed as one
615
+ * recommendation and sending the history once: one result per entry of
616
+ * `lists`, in order, each with its own `recommendationId`. A list holds
617
+ * none of the items of the lists before it unless `allowRepeats`.
618
+ * `exclude` applies to every list, a list's own `exclude` to it alone.
619
+ * Fails and falls back as `recommend()` does, list by list: once the
620
+ * popular request fails, the lists after it are empty.
621
+ *
622
+ * @param {{ lists: Array<{ count?: number, tagsAny?: string[], tagsAll?: string[], exclude?: string[],
623
+ * contextItemId?: string, placement?: string, discovery?: number }>, exclude?: string[], allowRepeats?: boolean }} params
624
+ * @returns {Promise<Array<{ recommendationId: string | null, fallback: boolean,
625
+ * items: Array<{ itemId: string, score: number, slot: string, why?: string, metadata?: object }> }>>}
626
+ */
627
+ async recommendLists({ lists, exclude, allowRepeats = false } = {}) {
628
+ if (!Array.isArray(lists) || lists.length === 0) {
629
+ throw new RecapiError('invalid_request', 'at least one list is required');
565
630
  }
631
+ return recommendRows(lists, { exclude, allowRepeats });
566
632
  },
567
633
 
568
634
  /**
package/src/transport.js CHANGED
@@ -77,10 +77,14 @@ export class RecapiError extends Error {
77
77
  */
78
78
 
79
79
  /**
80
- * @param {{ baseUrl: string, apiKey: string, fetch: typeof fetch, timeoutMs: number }} options
80
+ * `platform` goes in the URL of every request, as `?key=` does and for the
81
+ * same reason: a header of our own would make every browser call ask
82
+ * permission first.
83
+ *
84
+ * @param {{ baseUrl: string, apiKey: string, fetch: typeof fetch, timeoutMs: number, platform?: string }} options
81
85
  * @returns {{ request: (options: RequestOptions) => Promise<any> }}
82
86
  */
83
- export function createTransport({ baseUrl, apiKey, fetch, timeoutMs: defaultTimeoutMs }) {
87
+ export function createTransport({ baseUrl, apiKey, fetch, timeoutMs: defaultTimeoutMs, platform }) {
84
88
  const root = baseUrl.replace(/\/+$/, '');
85
89
 
86
90
  /** @param {RequestOptions} options */
@@ -91,6 +95,7 @@ export function createTransport({ baseUrl, apiKey, fetch, timeoutMs: defaultTime
91
95
  if (value !== undefined) params.append(name, String(value));
92
96
  }
93
97
  if (auth === 'query') params.append('key', apiKey);
98
+ if (platform) params.append('platform', platform);
94
99
  const qs = params.toString();
95
100
  const url = `${root}${path}${qs ? `?${qs}` : ''}`;
96
101