@recapi/client 0.6.8 → 0.8.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 +114 -24
- package/index.d.ts +12 -1
- package/package.json +1 -1
- package/src/client.js +107 -43
package/README.md
CHANGED
|
@@ -35,9 +35,11 @@ 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.
|
|
38
|
+
import { createClient } from 'https://api.example.com/sdk/0.8.0/index.js';
|
|
39
39
|
|
|
40
|
-
const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com' });
|
|
40
|
+
const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com', consent: false });
|
|
41
|
+
// From your cookie banner, once the visitor agrees: recapi.setConsent(true).
|
|
42
|
+
// A site that needs no banner passes consent: true instead (see Consent).
|
|
41
43
|
recapi.track('item-42', 'view'); // and the calls of the quick start below
|
|
42
44
|
</script>
|
|
43
45
|
```
|
|
@@ -78,7 +80,8 @@ import { createClient } from '@recapi/client'; // or the /sdk/ URL above
|
|
|
78
80
|
const recapi = createClient({
|
|
79
81
|
apiKey: 'rk_pub_…', // public key only, never a secret key
|
|
80
82
|
baseUrl: 'https://api.example.com',
|
|
81
|
-
placement: 'homepage'
|
|
83
|
+
placement: 'homepage',
|
|
84
|
+
consent: false // until your cookie banner calls recapi.setConsent(true)
|
|
82
85
|
});
|
|
83
86
|
|
|
84
87
|
// The user opened an item: a product, an article, a video… (level 3).
|
|
@@ -244,7 +247,27 @@ every page from `wp_footer`. The product id is the item id. It tracks:
|
|
|
244
247
|
checkout alike: `is_order_received_page()`), with the order key checked,
|
|
245
248
|
nothing for a failed or cancelled payment, and the order marked
|
|
246
249
|
(`_recapi_counted` meta) so a reload prints nothing. A logged-in buyer's
|
|
247
|
-
customer id is passed to `identify()` there
|
|
250
|
+
customer id is passed to `identify()` there, even once the order is
|
|
251
|
+
counted. With a secret key saved (see
|
|
252
|
+
below) the shop's server also sends the order once it is paid, so a buyer
|
|
253
|
+
who pays off-site and never comes back, or blocks scripts, still counts:
|
|
254
|
+
on `woocommerce_payment_complete` and the `processing` and `completed`
|
|
255
|
+
statuses (cash on delivery, a bank transfer received, an order the merchant
|
|
256
|
+
enters), one `POST /v1/events` once the response is out (one try of 2 s, a
|
|
257
|
+
failure logged), each line dated when the order was paid, with an
|
|
258
|
+
`event_id` per order line. Whichever path comes first marks the order, so
|
|
259
|
+
it counts once. The buyer is the customer id, and the visitor id and the
|
|
260
|
+
recommendation of each clicked product from the `recapi` cookie, which the
|
|
261
|
+
script keeps (a day, only with consent, as the Magento module does) while a
|
|
262
|
+
key is saved; a guest without it gets `woocommerce-order-<id>` as
|
|
263
|
+
`anon_id`. The cookie is read only in the buyer's own request (not the
|
|
264
|
+
admin, WP-Cron, or a shop manager's call for another customer), and a
|
|
265
|
+
buyer sending `DNT: 1` or `Sec-GPC: 1` is not sent (the order is marked,
|
|
266
|
+
so a later status change doesn't send it either). Only orders paid since
|
|
267
|
+
the key was saved, or since the first request with a key after the update
|
|
268
|
+
that brought this path (`recapi_orders_since` option), go from the server:
|
|
269
|
+
older ones are in the past-orders file, whose upload skips only purchases
|
|
270
|
+
already sent live, so completing one later would count it twice.
|
|
248
271
|
|
|
249
272
|
The checkout is the shop's own origin, so the purchase reads the state the
|
|
250
273
|
product pages stored and is credited to the recommendation clicked: no
|
|
@@ -276,19 +299,50 @@ The script inserts it as `<h2 class="recapi-heading">` before the div once
|
|
|
276
299
|
the cards fill, as text, so a row that stays hidden leaves no title. The
|
|
277
300
|
shortcode shows none unless given one: `[recapi heading="You may also like"]`.
|
|
278
301
|
|
|
302
|
+
Each row asks for its own placement: `product` on product pages (the
|
|
303
|
+
Related products spot, or `[recapi]` in a product template), `cart` for
|
|
304
|
+
`[recapi]` on the cart page, `shortcode` elsewhere, so the Overview's "By
|
|
305
|
+
placement" and a lift test tell them apart. A placement not configured in
|
|
306
|
+
the dashboard serves as `default`, with its settings and its running lift
|
|
307
|
+
test, so a shop that set `default` up keeps it.
|
|
308
|
+
|
|
279
309
|
The widget fills it like the Shopify snippet's, once it nears the screen,
|
|
280
|
-
|
|
310
|
+
asking for the 4 products it shows (recapi counts every product of a list
|
|
311
|
+
as shown, so a spare would get an impression and could be credited a view it
|
|
312
|
+
never caused), loading them in one request to WooCommerce's public Store API
|
|
281
313
|
(`/wc/store/v1/products?include=…`) and skipping those not purchasable or
|
|
282
|
-
out of stock.
|
|
314
|
+
out of stock. A full list that leaves a gap that way (without a secret key
|
|
315
|
+
recapi may not know a product sold out) is topped up once with a second
|
|
316
|
+
list of as many products, excluding the first's; a fallback list is not. Items whose [metadata](../../docs/api.md#item-metadata)
|
|
283
317
|
has a `name` and an http(s) `url` are left out of that request and drawn
|
|
284
318
|
from it, as in the Shopify snippet (a number `price` is in the shop's
|
|
285
319
|
currency, `woocommerce_currency`, and shown only while the visitor browses
|
|
286
|
-
in it), so a row whose items all carry metadata needs no Store API call.
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
320
|
+
in it), so a row whose items all carry metadata needs no Store API call.
|
|
321
|
+
|
|
322
|
+
Consent: the plugin keeps a visitor id on the device only with the
|
|
323
|
+
visitor's consent, and events without one train nothing, so WooCommerce →
|
|
324
|
+
recapi asks the merchant "How does your shop ask for cookie consent?"
|
|
325
|
+
(option `recapi_consent`):
|
|
326
|
+
|
|
327
|
+
- **A banner that feeds the [WP Consent API](https://wordpress.org/plugins/wp-consent-api/)**
|
|
328
|
+
(`wp-consent-api`, the reading until the merchant answers): Complianz,
|
|
329
|
+
CookieYes and others. `wp_has_consent('statistics')` at load, then
|
|
330
|
+
`wp_listen_for_consent_change`; the API reports allowed where no banner
|
|
331
|
+
manages consent.
|
|
332
|
+
- **Another banner, which calls recapi** (`banner`): once the visitor
|
|
333
|
+
accepts statistics cookies it runs `recapi.setConsent(true)` on every
|
|
334
|
+
page, and `recapi.setConsent(false)` if they withdraw. The page's head
|
|
335
|
+
defines `window.recapi` first, so a banner answering before the plugin's
|
|
336
|
+
module loads is heard.
|
|
337
|
+
- **No cookie banner needed** (`no-banner`): consent from the first page,
|
|
338
|
+
the reading the WP Consent API and Shopify give where no consent is
|
|
339
|
+
required. Do Not Track and Global Privacy Control still keep a visitor
|
|
340
|
+
out.
|
|
341
|
+
|
|
342
|
+
Until the merchant answers, a shop without the WP Consent API stores
|
|
343
|
+
nothing and sends events without an id, as the Shopify snippet does when its
|
|
344
|
+
consent API fails to load; the plugin list and WooCommerce → recapi then
|
|
345
|
+
show a notice that the shop isn't learning yet. It declares compatibility with
|
|
292
346
|
WooCommerce's order tables (HPOS) and checkout blocks when installed as a
|
|
293
347
|
plugin, and registers with the WP Consent API.
|
|
294
348
|
|
|
@@ -327,7 +381,7 @@ so recapi never sees or can guess the email), or without an email
|
|
|
327
381
|
`woocommerce-order-<id>`. Only shop managers (`manage_woocommerce`) with
|
|
328
382
|
the page's nonce get the file, and it reads orders 200 at a time through
|
|
329
383
|
`wc_get_orders` (HPOS or not). The import skips rows already uploaded and
|
|
330
|
-
purchases the
|
|
384
|
+
purchases the plugin already sent.
|
|
331
385
|
|
|
332
386
|
`test/woocommerce.test.js` prints pages through PHP (`test/wordpress.php`
|
|
333
387
|
stands in for WordPress, run by `scripts/php.sh`) and runs the printed
|
|
@@ -336,7 +390,7 @@ your address (`jssdk.WooCommerce`).
|
|
|
336
390
|
|
|
337
391
|
`scripts/e2e_woocommerce.sh` (CI job `woocommerce`) runs the plugin on a
|
|
338
392
|
real, throwaway shop: WordPress and WooCommerce in Docker at pinned
|
|
339
|
-
versions, twice: the newest (WordPress 7.1.4, WooCommerce 11.
|
|
393
|
+
versions, twice: the newest (WordPress 7.1.4, WooCommerce 11.3.0, PHP 8.5)
|
|
340
394
|
and the oldest the plugin's header declares (WordPress 6.3, WooCommerce 8.3,
|
|
341
395
|
PHP 7.4), the plugin taken from the quick start of a new recapi shop with
|
|
342
396
|
its public key pasted, then a guest's browser (Playwright) on a product
|
|
@@ -411,8 +465,10 @@ A client is one visitor, like a browser tab: its history, user id and
|
|
|
411
465
|
attribution belong to whoever it was used for, and one isolate serves many
|
|
412
466
|
requests at once. Share a client only for lists that are no one's, such as
|
|
413
467
|
popular items, and make one per request for a visitor's events and
|
|
414
|
-
recommendations.
|
|
415
|
-
anonymous id
|
|
468
|
+
recommendations. Without consent, the default, a client draws no
|
|
469
|
+
anonymous id, so a client per request doesn't make a new visitor each time;
|
|
470
|
+
it sends the user id you give `identify()`. The recipe says `consent: false`
|
|
471
|
+
anyway, so the visitor's client reads as what it is.
|
|
416
472
|
|
|
417
473
|
```js
|
|
418
474
|
// Cloudflare Workers
|
|
@@ -527,7 +583,7 @@ for (const item of items) {
|
|
|
527
583
|
| `maxBatch` | `100` | events per request (max 1000); a full queue flushes at once |
|
|
528
584
|
| `timeoutMs` | `5000` | per-request timeout; `recommend()` waits 1.5 s at most |
|
|
529
585
|
| `historyConfig` | spec defaults | `{ halfLifeSeconds, topK, recentSize }`; must match the server |
|
|
530
|
-
| `consent` | `
|
|
586
|
+
| `consent` | `false` | storage consent: `false` stores nothing until `setConsent(true)`, see [Consent](#consent-and-eprivacy) |
|
|
531
587
|
| `respectDoNotTrack` | `true` | when DNT or Global Privacy Control is on: store nothing, send no events, see [Do Not Track](#do-not-track) |
|
|
532
588
|
| `onError` | `console.warn` for lost events and lists it answered with a fallback | gets errors from background work (flushes, storage, rejected events) and those `recommend()` and `popular()` fell back from |
|
|
533
589
|
| `now`, `fetch`, `sleep` | `Date.now`, global `fetch`, `setTimeout` | for tests |
|
|
@@ -562,6 +618,8 @@ for (const item of items) {
|
|
|
562
618
|
happens when the call fails. The user's rejected items (the newest 200)
|
|
563
619
|
are added to `exclude`, after yours, up to the API's limit of 500. The SDK does not send `explain`, which needs
|
|
564
620
|
a secret key: call the API from your backend for that.
|
|
621
|
+
- **`recommendLists({ lists, exclude, allowRepeats })`**: several rows in
|
|
622
|
+
one call, see [below](#several-rows-in-one-call).
|
|
565
623
|
- **`popular({ tagsAny, tagsAll, count })`** resolves to `{ items: [{ itemId, score, why, metadata }] }`.
|
|
566
624
|
A public key goes in `?key=`, so the response can be cached by a CDN.
|
|
567
625
|
[How the key is sent](#how-the-key-is-sent) gives the reason for the rest.
|
|
@@ -583,6 +641,20 @@ for (const item of items) {
|
|
|
583
641
|
[Login and logout](#login-and-logout).
|
|
584
642
|
- **`destroy()`** removes listeners and timers, then flushes.
|
|
585
643
|
|
|
644
|
+
### Several rows in one call
|
|
645
|
+
|
|
646
|
+
A page with several rows asks for them in one call: the history is sent once
|
|
647
|
+
and the call is billed as one recommendation. Each list takes `recommend()`'s
|
|
648
|
+
parameters and resolves to its own result, in order, with its own
|
|
649
|
+
`recommendationId`. An item appears on one list only unless `allowRepeats`;
|
|
650
|
+
`exclude` applies to every list. A failure falls back list by list.
|
|
651
|
+
|
|
652
|
+
```js
|
|
653
|
+
const [similar, more] = await recapi.recommendLists({
|
|
654
|
+
lists: [{ placement: 'product', count: 4, contextItemId: 'item-42' }, { placement: 'more', count: 8 }]
|
|
655
|
+
});
|
|
656
|
+
```
|
|
657
|
+
|
|
586
658
|
### Errors
|
|
587
659
|
|
|
588
660
|
Every failure is a `RecapiError` with `code`, `status` and `message`. The
|
|
@@ -785,16 +857,18 @@ so a batch already in flight when the user navigates away still arrives.
|
|
|
785
857
|
|
|
786
858
|
Under the EU ePrivacy Directive (art. 5(3)), storing data on the user's
|
|
787
859
|
device, or reading it back, generally needs prior consent unless it is
|
|
788
|
-
strictly necessary. A recommendation history usually is not.
|
|
789
|
-
|
|
860
|
+
strictly necessary. A recommendation history usually is not. So the SDK
|
|
861
|
+
stores nothing until it is told the visitor consented: `consent` defaults to
|
|
862
|
+
`false`. Wire it to your consent banner:
|
|
790
863
|
|
|
791
864
|
```js
|
|
792
865
|
const recapi = createClient({ apiKey, baseUrl, consent: cmp.hasConsent('personalisation') });
|
|
793
866
|
cmp.onChange((granted) => recapi.setConsent(granted));
|
|
794
867
|
```
|
|
795
868
|
|
|
796
|
-
|
|
797
|
-
|
|
869
|
+
A site that needs no banner (outside the EU, or with its own legal basis)
|
|
870
|
+
passes `consent: true`. Without consent, the SDK never reads or writes storage
|
|
871
|
+
and creates no anonymous id. The history and the attribution map live in memory for the
|
|
798
872
|
current page only. A single-page app keeps attribution. On a multi-page
|
|
799
873
|
site, a click that loads the item's page is not attributed unless you
|
|
800
874
|
pass the id yourself, for example in the link. A fragment (`#${recommendationId}`,
|
|
@@ -852,7 +926,9 @@ const storage = {
|
|
|
852
926
|
setItem: (k, v) => { cache.set(k, v); AsyncStorage.setItem(k, v); },
|
|
853
927
|
removeItem: (k) => { cache.delete(k); AsyncStorage.removeItem(k); }
|
|
854
928
|
};
|
|
855
|
-
|
|
929
|
+
// An app asks for consent as a site does: pass the user's answer, and call
|
|
930
|
+
// client.setConsent() when it changes (see Consent).
|
|
931
|
+
const client = createClient({ apiKey, baseUrl, project: 'myproject', storage, consent: true });
|
|
856
932
|
```
|
|
857
933
|
|
|
858
934
|
React Native has no page-hide event, so send the queue when the app leaves
|
|
@@ -868,14 +944,28 @@ key on a format change makes old data invisible.
|
|
|
868
944
|
## Size budget
|
|
869
945
|
|
|
870
946
|
Budget: **6 KB gzip** after minification. The sources ship unminified with
|
|
871
|
-
full JSDoc:
|
|
947
|
+
full JSDoc: 66 KB raw in five files, 21 KB as the API serves them (gzip -9),
|
|
872
948
|
and the browser caches them. With comments stripped and no
|
|
873
|
-
minification they are
|
|
949
|
+
minification they are 9 KB gzip. A bundler's minifier should bring
|
|
874
950
|
that under the budget, but this has not been measured: the repo has no
|
|
875
951
|
minifier, to keep zero dev dependencies.
|
|
876
952
|
|
|
877
953
|
## Changes
|
|
878
954
|
|
|
955
|
+
- 2026-11-14: version 0.8.0. `recommendLists()` asks for a page's rows in one
|
|
956
|
+
call, billed as one recommendation ([Several rows in one call](#several-rows-in-one-call)).
|
|
957
|
+
- 2026-11-11: version 0.7.0. `consent` defaults to `false`: a client stores
|
|
958
|
+
nothing on the device and sends no `anon_id` until `consent: true` or
|
|
959
|
+
`setConsent(true)`, so a tag pasted as is keeps the promise that our script
|
|
960
|
+
stores nothing until the visitor consents. Before, it defaulted to `true`.
|
|
961
|
+
A site that wires no banner keeps the history for the current page only,
|
|
962
|
+
and a click that opens a new page goes uncredited, until it adds the line
|
|
963
|
+
([Consent](#consent-and-eprivacy)). Older versions' paths redirect to this
|
|
964
|
+
one, so tags pasted earlier get it too. The Shopify snippet, the WooCommerce
|
|
965
|
+
plugin and the Magento module pass their banner's answer and are unchanged.
|
|
966
|
+
The Shopify pixel, which runs only with Analytics consent, now passes
|
|
967
|
+
`consent: true`: a pixel pasted before this version credits purchases
|
|
968
|
+
without the visitor's id until it is pasted again from the quick start.
|
|
879
969
|
- 2026-11-07: version 0.6.8. A saved time ahead of the clock reads as now and a
|
|
880
970
|
damaged weight is sent as the API's limit (1e6). A device whose clock ran months
|
|
881
971
|
ahead and was then corrected used to get a 400 on every list until the entry had
|
package/index.d.ts
CHANGED
|
@@ -76,7 +76,7 @@ export interface ClientOptions {
|
|
|
76
76
|
/** Per-request timeout, default 5000; `recommend()` waits at most 1500. */
|
|
77
77
|
timeoutMs?: number;
|
|
78
78
|
historyConfig?: Partial<HistoryConfig>;
|
|
79
|
-
/** Initial storage consent, default `true`. */
|
|
79
|
+
/** Initial storage consent, default `false`: nothing is stored until `true` or `setConsent(true)`. */
|
|
80
80
|
consent?: boolean;
|
|
81
81
|
/**
|
|
82
82
|
* Default `true`: when Do Not Track / Global Privacy Control is on, store
|
|
@@ -106,6 +106,15 @@ export interface RecommendParams {
|
|
|
106
106
|
discovery?: number;
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
export interface RecommendListsParams {
|
|
110
|
+
/** One result per list, in order; each list's `exclude` applies to it alone. */
|
|
111
|
+
lists: RecommendParams[];
|
|
112
|
+
/** Applies to every list. */
|
|
113
|
+
exclude?: string[];
|
|
114
|
+
/** Lets an item appear on more than one list. */
|
|
115
|
+
allowRepeats?: boolean;
|
|
116
|
+
}
|
|
117
|
+
|
|
109
118
|
/** An item's reason code: map the ones you want to your own label, show none for an unknown one. */
|
|
110
119
|
export type ReasonCode =
|
|
111
120
|
| 'for_you' | 'similar' | 'next' | 'bought_together' | 'trending' | 'popular' | 'new' | 'explore' | 'more'
|
|
@@ -157,6 +166,8 @@ export interface RecapiClient {
|
|
|
157
166
|
track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null }): void;
|
|
158
167
|
/** 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
168
|
recommend(params?: RecommendParams): Promise<RecommendResult>;
|
|
169
|
+
/** Several lists in one call, billed as one recommendation; falls back as `recommend()` does, list by list. */
|
|
170
|
+
recommendLists(params: RecommendListsParams): Promise<RecommendResult[]>;
|
|
160
171
|
/** 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
172
|
popular(params?: PopularParams): Promise<PopularResult>;
|
|
162
173
|
identify(userId: string, options?: { history?: ServerSnapshot }): void;
|
package/package.json
CHANGED
package/src/client.js
CHANGED
|
@@ -82,7 +82,7 @@ const PUBLIC_KEY_PREFIX = 'rk_pub_';
|
|
|
82
82
|
* @property {number} [maxBatch]
|
|
83
83
|
* @property {number} [timeoutMs] Per-request timeout.
|
|
84
84
|
* @property {Partial<HistoryConfig>} [historyConfig]
|
|
85
|
-
* @property {boolean} [consent] Initial storage consent (default `
|
|
85
|
+
* @property {boolean} [consent] Initial storage consent (default `false`).
|
|
86
86
|
* @property {boolean} [respectDoNotTrack] When the browser sends Do Not
|
|
87
87
|
* Track or Global Privacy Control (default `true`): store nothing, send no
|
|
88
88
|
* events and no visitor ids; recommendations are still asked for.
|
|
@@ -179,7 +179,9 @@ export function createClient(options) {
|
|
|
179
179
|
// the visitor's standing one. `respectDoNotTrack: false` is for a site with
|
|
180
180
|
// its own legal basis.
|
|
181
181
|
const quiet = (options.respectDoNotTrack ?? true) && doNotTrackEnabled();
|
|
182
|
-
|
|
182
|
+
// Without an answer from the site's banner the client stores nothing, so a
|
|
183
|
+
// snippet pasted as is keeps the homepage's promise (ePrivacy art. 5(3)).
|
|
184
|
+
let consent = !quiet && (options.consent ?? false);
|
|
183
185
|
|
|
184
186
|
/** @type {HistoryState} */
|
|
185
187
|
let history = emptyHistory();
|
|
@@ -358,11 +360,30 @@ export function createClient(options) {
|
|
|
358
360
|
return chain;
|
|
359
361
|
}
|
|
360
362
|
|
|
361
|
-
/**
|
|
362
|
-
|
|
363
|
+
/**
|
|
364
|
+
* `POST /v1/recommendations` for `recommend()` (`call` undefined: one list)
|
|
365
|
+
* or `recommendLists()` (its `exclude` and `allowRepeats`); remembers each
|
|
366
|
+
* shown item under its own list's recommendation for attribution.
|
|
367
|
+
*/
|
|
368
|
+
async function personalised(rows, call, deadline) {
|
|
363
369
|
if (consent) reload();
|
|
364
370
|
const wire = toWire(history, now(), config);
|
|
365
371
|
const sentEmpty = wire.history.length === 0;
|
|
372
|
+
const row = (params, exclude) => ({
|
|
373
|
+
placement: params.placement ?? defaultPlacement,
|
|
374
|
+
count: params.count,
|
|
375
|
+
tags_any: params.tagsAny,
|
|
376
|
+
tags_all: params.tagsAll,
|
|
377
|
+
exclude,
|
|
378
|
+
context_item_id: params.contextItemId
|
|
379
|
+
});
|
|
380
|
+
const shared = call === undefined
|
|
381
|
+
? row(rows[0], withRejected(rows[0].exclude, wire.rejected))
|
|
382
|
+
: {
|
|
383
|
+
placements: rows.map((params) => compact({ ...row(params, params.exclude), discovery: params.discovery })),
|
|
384
|
+
exclude: withRejected(call.exclude, wire.rejected),
|
|
385
|
+
allow_repeats: call.allowRepeats ? true : undefined
|
|
386
|
+
};
|
|
366
387
|
const response = await transport.request({
|
|
367
388
|
method: 'POST',
|
|
368
389
|
path: '/v1/recommendations',
|
|
@@ -371,28 +392,31 @@ export function createClient(options) {
|
|
|
371
392
|
body: compact({
|
|
372
393
|
user_id: userId ?? undefined,
|
|
373
394
|
anon_id: anonId ?? undefined,
|
|
374
|
-
|
|
375
|
-
count: params.count,
|
|
376
|
-
tags_any: params.tagsAny,
|
|
377
|
-
tags_all: params.tagsAll,
|
|
378
|
-
exclude: withRejected(params.exclude, wire.rejected),
|
|
379
|
-
context_item_id: params.contextItemId,
|
|
395
|
+
...shared,
|
|
380
396
|
history: wire.history,
|
|
381
397
|
recent: wire.recent,
|
|
382
|
-
discovery:
|
|
398
|
+
discovery: call === undefined ? rows[0].discovery : undefined
|
|
383
399
|
})
|
|
384
400
|
});
|
|
385
|
-
|
|
401
|
+
const lists = call === undefined ? [response] : response?.lists;
|
|
402
|
+
if (!Array.isArray(lists) || lists.length !== rows.length ||
|
|
403
|
+
!lists.every((list) => typeof list?.recommendation_id === 'string' && Array.isArray(list.items))) {
|
|
386
404
|
throw new RecapiError('invalid_response', 'malformed recommendations response');
|
|
387
405
|
}
|
|
388
406
|
|
|
389
|
-
const
|
|
390
|
-
|
|
407
|
+
const results = lists.map((list) => ({
|
|
408
|
+
recommendationId: list.recommendation_id,
|
|
409
|
+
fallback: false,
|
|
410
|
+
items: list.items.map((item) => toItem(item, item.slot))
|
|
411
|
+
}));
|
|
391
412
|
mutate(() => {
|
|
392
413
|
const t = now();
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
414
|
+
// An item on two lists (allowRepeats) is credited to the last one.
|
|
415
|
+
for (const { recommendationId, items } of results) {
|
|
416
|
+
for (const { itemId } of items) {
|
|
417
|
+
shown.delete(itemId);
|
|
418
|
+
shown.set(itemId, [recommendationId, t]);
|
|
419
|
+
}
|
|
396
420
|
}
|
|
397
421
|
while (shown.size > MAX_SHOWN_ITEMS) shown.delete(shown.keys().next().value);
|
|
398
422
|
// A snapshot is only trusted when we sent nothing, and merged once: a
|
|
@@ -406,7 +430,7 @@ export function createClient(options) {
|
|
|
406
430
|
restored = true;
|
|
407
431
|
}
|
|
408
432
|
});
|
|
409
|
-
return
|
|
433
|
+
return results;
|
|
410
434
|
}
|
|
411
435
|
|
|
412
436
|
/**
|
|
@@ -427,22 +451,54 @@ export function createClient(options) {
|
|
|
427
451
|
.map((item) => toItem(item, 'backfill'));
|
|
428
452
|
}
|
|
429
453
|
|
|
430
|
-
/**
|
|
431
|
-
|
|
454
|
+
/**
|
|
455
|
+
* What `recommend()` and `recommendLists()` answer instead of lists of
|
|
456
|
+
* their own: popular items, a request per list skipping the call's
|
|
457
|
+
* `exclude` and, unless `allowRepeats`, the earlier lists' items; once
|
|
458
|
+
* popular fails, the lists after it are empty without asking.
|
|
459
|
+
*/
|
|
460
|
+
async function listsInstead(error, rows, { exclude = [], allowRepeats = false } = {}, deadline) {
|
|
432
461
|
reportList(error);
|
|
433
|
-
let items = [];
|
|
434
462
|
// A refused key would be refused the popular list too.
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
463
|
+
let failed = keyRefused(error);
|
|
464
|
+
const listed = [];
|
|
465
|
+
const results = [];
|
|
466
|
+
for (const params of rows) {
|
|
467
|
+
let items = [];
|
|
468
|
+
if (!failed) {
|
|
469
|
+
try {
|
|
470
|
+
items = await popularFallback({ ...params, exclude: [...exclude, ...(params.exclude ?? []), ...listed] }, deadline);
|
|
471
|
+
} catch (fallbackError) {
|
|
472
|
+
// Down altogether, or the limit covers popular too. The page awaits
|
|
473
|
+
// recommend() without a catch (the README says it may), so an empty
|
|
474
|
+
// list it can hide beats a rejection that breaks it.
|
|
475
|
+
reportList(fallbackError);
|
|
476
|
+
failed = true;
|
|
477
|
+
}
|
|
443
478
|
}
|
|
479
|
+
if (!allowRepeats) listed.push(...items.map(({ itemId }) => itemId));
|
|
480
|
+
results.push({ recommendationId: null, fallback: true, items });
|
|
481
|
+
}
|
|
482
|
+
return results;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** `recommend()` for one list (`call` undefined) and `recommendLists()`. */
|
|
486
|
+
async function recommendRows(rows, call) {
|
|
487
|
+
start();
|
|
488
|
+
const deadline = Math.min(timeoutMs, RECOMMEND_TIMEOUT_MS);
|
|
489
|
+
if (!rows.every((params) => usableContext(params.contextItemId))) {
|
|
490
|
+
// Unlike a failed call, nothing has read the stored rejections yet.
|
|
491
|
+
if (consent) reload();
|
|
492
|
+
const error = new RecapiError('invalid_request', idRule('contextItemId'));
|
|
493
|
+
const usable = rows.map((params) => (usableContext(params.contextItemId) ? params : { ...params, contextItemId: undefined }));
|
|
494
|
+
return listsInstead(error, usable, call, deadline);
|
|
495
|
+
}
|
|
496
|
+
try {
|
|
497
|
+
return await personalised(rows, call, deadline);
|
|
498
|
+
} catch (error) {
|
|
499
|
+
if (!sparesThePage(error)) throw error;
|
|
500
|
+
return listsInstead(error, rows, call, deadline);
|
|
444
501
|
}
|
|
445
|
-
return { recommendationId: null, fallback: true, items };
|
|
446
502
|
}
|
|
447
503
|
|
|
448
504
|
/**
|
|
@@ -547,20 +603,28 @@ export function createClient(options) {
|
|
|
547
603
|
* items: Array<{ itemId: string, score: number, slot: string, why?: string, metadata?: object }> }>}
|
|
548
604
|
*/
|
|
549
605
|
async recommend(params = {}) {
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
606
|
+
return (await recommendRows([params]))[0];
|
|
607
|
+
},
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* Several lists (a page's rows) from one call, billed as one
|
|
611
|
+
* recommendation and sending the history once: one result per entry of
|
|
612
|
+
* `lists`, in order, each with its own `recommendationId`. A list holds
|
|
613
|
+
* none of the items of the lists before it unless `allowRepeats`.
|
|
614
|
+
* `exclude` applies to every list, a list's own `exclude` to it alone.
|
|
615
|
+
* Fails and falls back as `recommend()` does, list by list: once the
|
|
616
|
+
* popular request fails, the lists after it are empty.
|
|
617
|
+
*
|
|
618
|
+
* @param {{ lists: Array<{ count?: number, tagsAny?: string[], tagsAll?: string[], exclude?: string[],
|
|
619
|
+
* contextItemId?: string, placement?: string, discovery?: number }>, exclude?: string[], allowRepeats?: boolean }} params
|
|
620
|
+
* @returns {Promise<Array<{ recommendationId: string | null, fallback: boolean,
|
|
621
|
+
* items: Array<{ itemId: string, score: number, slot: string, why?: string, metadata?: object }> }>>}
|
|
622
|
+
*/
|
|
623
|
+
async recommendLists({ lists, exclude, allowRepeats = false } = {}) {
|
|
624
|
+
if (!Array.isArray(lists) || lists.length === 0) {
|
|
625
|
+
throw new RecapiError('invalid_request', 'at least one list is required');
|
|
563
626
|
}
|
|
627
|
+
return recommendRows(lists, { exclude, allowRepeats });
|
|
564
628
|
},
|
|
565
629
|
|
|
566
630
|
/**
|