@recapi/client 0.35.0 → 0.36.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
@@ -54,7 +54,7 @@ are, gzipped, and browsers cache them:
54
54
 
55
55
  ```html
56
56
  <script type="module">
57
- import { createClient } from 'https://api.example.com/sdk/0.35.0/index.js';
57
+ import { createClient } from 'https://api.example.com/sdk/0.36.0/index.js';
58
58
 
59
59
  const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com', consent: false });
60
60
  // From your cookie banner, once the visitor agrees: recapi.setConsent(true).
@@ -947,7 +947,7 @@ row, with nothing to set in the dashboard (`BOUGHT_TOGETHER` is the product
947
947
  page's second row).
948
948
 
949
949
  ```js
950
- import { RECENTLY_VIEWED } from 'https://api.example.com/sdk/0.35.0/index.js';
950
+ import { RECENTLY_VIEWED } from 'https://api.example.com/sdk/0.36.0/index.js';
951
951
 
952
952
  const [home, recent] = await recapi.recommendLists({
953
953
  lists: [{ placement: 'home', count: 4 }, { placement: RECENTLY_VIEWED, count: 4 }]
@@ -1277,7 +1277,13 @@ way only an id recapi makes (`rec_` and hex digits) is read: any other
1277
1277
  `#…` or `?rec=` value is the site's own and stays.
1278
1278
 
1279
1279
  Events are still sent, without `anon_id`. Don't call `track()` if you
1280
- need no network at all. Withdrawing consent deletes the stored data.
1280
+ need no network at all. Such an event may name the product page the
1281
+ visitor came from on your shop: `track(itemId, 'view', { contextItemId })`.
1282
+ `track('view')` and the Shopify snippet fill it themselves from the
1283
+ browser's address of the page before, when it is on your shop and can be
1284
+ a product's: never the home page, a search, the cart, the checkout, an
1285
+ order or an account page, nor a query but a product's (`?id=`). It is sent
1286
+ only while the visitor has no id, and read from no storage. Withdrawing consent deletes the stored data.
1281
1287
  Granting it merges the in-memory history into storage.
1282
1288
 
1283
1289
  The entry to paste into a cookie banner tool, and how to keep it from
@@ -1347,16 +1353,16 @@ key on a format change makes old data invisible.
1347
1353
  ## Size budget
1348
1354
 
1349
1355
  What a first visit downloads before the library runs: each entry is one
1350
- file, joined and gzipped as the API serves it (library 0.34.0). A test fails
1356
+ file, joined and gzipped as the API serves it (library 0.36.0). A test fails
1351
1357
  when an entry passes its budget (`go test ./internal/jssdk -run SizeBudget -v`
1352
1358
  in `server/` prints these):
1353
1359
 
1354
1360
  | Entry | Bytes | Gzipped | Budget | Its files as they are |
1355
1361
  |---|--:|--:|--:|--:|
1356
- | `index.js` (the pasted tag) | 42,753 | 17,181 | 18,000 | 6 files, 38,709 |
1357
- | `woocommerce.js` | 52,427 | 20,642 | 20,850 | 9 files, 55,102 |
1358
- | `shopify.js` | 55,286 | 21,741 | 21,950 | 9 files, 58,134 |
1359
- | `magento.js` | 51,737 | 20,389 | 20,600 | 9 files, 54,739 |
1362
+ | `index.js` (the pasted tag) | 43,991 | 17,637 | 18,000 | 6 files, 39,877 |
1363
+ | `woocommerce.js` | 53,871 | 21,177 | 21,450 | 9 files, 56,556 |
1364
+ | `shopify.js` | 56,581 | 22,231 | 22,550 | 9 files, 59,526 |
1365
+ | `magento.js` | 53,180 | 20,905 | 21,200 | 9 files, 56,176 |
1360
1366
 
1361
1367
  `index.js` holds the row too, which it used to fetch at the first `row()`.
1362
1368
 
@@ -1374,6 +1380,9 @@ in `server/` writes the files as served, for `scripts/e2e/chain.mjs /tmp/served`
1374
1380
 
1375
1381
  ## Changes
1376
1382
 
1383
+ - 2026-12-04: version 0.36.0. A visitor without consent can name the
1384
+ product page they came from (`contextItemId` on `track()`);
1385
+ `track('view')` and the Shopify snippet read it from the browser.
1377
1386
  - 2026-12-04: version 0.35.0. On WooCommerce and Magento a marked browser
1378
1387
  also gets the `recapi_own` cookie, so the orders the shop's server sends
1379
1388
  carry `own: true` (plugin 0.35.0, module 0.4.44, which mark staff
package/index.d.ts CHANGED
@@ -204,9 +204,9 @@ export interface RecapiClient {
204
204
  * `value` is what the buyer paid for a purchase's line (a number of at least 0; 0 is a free line), `currency` its ISO 4217 code
205
205
  * (three letters, any case); a currency needs a value. An invalid pair throws `RecapiError('invalid_request')`, as a bad level does.
206
206
  */
207
- track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string; send?: boolean }): void;
207
+ track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string; send?: boolean; contextItemId?: string }): void;
208
208
  /** The page's product, by its address (README "The page's product"): no product markup, nothing is sent. */
209
- track(level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string; send?: boolean }): void;
209
+ track(level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string; send?: boolean; contextItemId?: string }): void;
210
210
  /** 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. */
211
211
  recommend(params?: RecommendParams): Promise<RecommendResult>;
212
212
  /** Several lists in one call, billed as one recommendation; falls back as `recommend()` does, list by list. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.35.0",
3
+ "version": "0.36.0",
4
4
  "description": "Browser and Node client for the recapi recommendation API: local decayed history, event batching, attribution.",
5
5
  "homepage": "https://recapi.io/docs",
6
6
  "bugs": {
package/src/client.js CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  resolveConfig,
19
19
  toWire
20
20
  } from './history.js';
21
- import { REC_ID, bare, followProduct, pageOf, readProduct } from './page.js';
21
+ import { REC_ID, beforeId, bare, cameFrom, followProduct, pageOf, readProduct } from './page.js';
22
22
  import { createStore, defaultStorage, storageKey } from './storage.js';
23
23
  import { RecapiError, createTransport, defaultSleep, withRetry } from './transport.js';
24
24
 
@@ -207,6 +207,12 @@ export function createClient(options) {
207
207
 
208
208
  /** @type {HistoryState} */
209
209
  let history = emptyHistory();
210
+ // The product page a visitor without an id came from (AP-1066): the only
211
+ // step that ties two of their pages, as nothing on the device may. A
212
+ // visitor with an id has a history that says it, and an id the API would
213
+ // refuse (it often comes from an address) would cost the event itself.
214
+ const pageBefore = (itemId, before) =>
215
+ userId === null && anonId === null && typeof before === 'string' && before !== itemId && isId(before) ? before : undefined;
210
216
  let userId = null;
211
217
  let anonId = null;
212
218
  /**
@@ -657,7 +663,7 @@ export function createClient(options) {
657
663
  by(entry).placeRow(slot, { ...options, contextItemId: id || undefined });
658
664
  return;
659
665
  }
660
- if (id) by(entry).track(id, entry.level, entry.options);
666
+ if (id) by(entry).track(id, entry.level, Object.hasOwn(entry.options, 'contextItemId') ? entry.options : { ...entry.options, contextItemId: idBefore });
661
667
  if (entry.level !== LEVEL_NAMES.view) onPage.delete(entry);
662
668
  };
663
669
  const repeat = (entry) => {
@@ -691,6 +697,7 @@ export function createClient(options) {
691
697
  }
692
698
  unfollow = followProduct((id) => {
693
699
  const again = pageId !== null;
700
+ idBefore = again ? pageId : beforeId(cameFrom(here()));
694
701
  pageId = id;
695
702
  pageAt = here();
696
703
  for (const each of [...onPage]) apply(each, id, again);
@@ -711,6 +718,7 @@ export function createClient(options) {
711
718
  // their own. Under the key, the first follower, as older copies call it;
712
719
  // its `peers` the others.
713
720
  let following = null;
721
+ let idBefore = '';
714
722
  const self = { track: (...args) => client.track(...args), placeRow, live: () => !destroyed };
715
723
  // An older copy's entry names no client; a destroyed one sends nothing.
716
724
  const by = (entry) => (entry.by?.live() ? entry.by : self);
@@ -759,7 +767,9 @@ export function createClient(options) {
759
767
  * An `itemId` the API would refuse (a page often takes it from a
760
768
  * visitor's URL) drops the event and goes to `onError`, without throwing.
761
769
  * @param {{ recommendationId?: string | null, value?: number,
762
- * currency?: string, send?: boolean }} [options] `recommendationId` overrides the
770
+ * currency?: string, send?: boolean, contextItemId?: string }} [options]
771
+ * `contextItemId` is the product page the visitor came from on the
772
+ * shop, sent only while the visitor has no id (no consent). `recommendationId` overrides the
763
773
  * automatic attribution; `null` (a fallback list's id) is no override.
764
774
  * `value` is what the buyer paid for a purchase's line (0 for a free
765
775
  * line), `currency` its ISO 4217 code (three letters, any case); a
@@ -833,7 +843,8 @@ export function createClient(options) {
833
843
  currency,
834
844
  timestamp: new Date(t).toISOString(),
835
845
  event_id: uuid(),
836
- own: own()
846
+ own: own(),
847
+ context_item_id: pageBefore(itemId, options.contextItemId)
837
848
  }));
838
849
  if (level === LEVEL_NAMES.view && describing) describePage(itemId);
839
850
  },
package/src/magento.js CHANGED
@@ -22,7 +22,7 @@ import { storageKey } from './storage.js';
22
22
  // Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
23
23
  import './client.js';
24
24
  import './history.js';
25
- import './page.js';
25
+ import { beforeId, cameFrom } from './page.js';
26
26
  import './transport.js';
27
27
 
28
28
  /**
@@ -93,7 +93,8 @@ export async function magentoPage(page) {
93
93
  // The product id is the item id. A card's link carries its list's id in
94
94
  // the fragment, which no page cache sees: an unknown ?rec= gave every click
95
95
  // from the row its own entry in the full-page cache.
96
- if (page.product) landing(recapi, page.product);
96
+ // As on WooCommerce: the page before by its address (AP-1066).
97
+ if (page.product) landing(recapi, page.product, beforeId(cameFrom(location.href)));
97
98
  // The order's own page: the server sent the purchases.
98
99
  bought(recapi, page.bought);
99
100
 
package/src/page.js CHANGED
@@ -120,20 +120,7 @@ export function addressId(raw) {
120
120
  return '';
121
121
  }
122
122
  if (u.protocol !== 'https:' && u.protocol !== 'http:') return '';
123
- const query = u.search.slice(1).split('&').filter((pair) => {
124
- if (pair === '') return false;
125
- const [name, ...rest] = pair.split('=');
126
- // A card's own `?rec=rec_…` credits the click, then leaves the address
127
- // (client.js landed()): kept, the product would have a second id for the
128
- // view that carries the credit. The site's own `?rec=1` stays.
129
- if (name === 'rec' && REC_ID.test(rest.join('='))) return false;
130
- let key = name;
131
- try {
132
- key = decodeURIComponent(key.replace(/\+/g, ' '));
133
- } catch {}
134
- key = key.toLowerCase();
135
- return !CLICK_IDS.has(key) && !SWITCHES.has(key) && !key.startsWith('utm_');
136
- }).join('&');
123
+ const query = u.search.slice(1).split('&').filter((pair) => siteKey(pair) !== null).join('&');
137
124
  const path = u.pathname.length > 1 && u.pathname.endsWith('/') ? u.pathname.slice(0, -1) : u.pathname;
138
125
  let id = query ? `${path}?${query}` : path;
139
126
  try {
@@ -145,6 +132,68 @@ export function addressId(raw) {
145
132
  return fit(id);
146
133
  }
147
134
 
135
+ // The lower-cased name of a query pair the site itself put in its address,
136
+ // or null for an empty pair, a click or campaign id, a visitor's switch.
137
+ function siteKey(pair) {
138
+ if (pair === '') return null;
139
+ const [name, ...rest] = pair.split('=');
140
+ // A card's own `?rec=rec_…` credits the click, then leaves the address
141
+ // (client.js landed()): kept, the product would have a second id for the
142
+ // view that carries the credit. The site's own `?rec=1` stays.
143
+ if (name === 'rec' && REC_ID.test(rest.join('='))) return null;
144
+ let key = name;
145
+ try {
146
+ key = decodeURIComponent(key.replace(/\+/g, ' '));
147
+ } catch {}
148
+ key = key.toLowerCase();
149
+ return CLICK_IDS.has(key) || SWITCHES.has(key) || key.startsWith('utm_') ? null : key;
150
+ }
151
+
152
+ // The query names a product addresses carry (WooCommerce's plain
153
+ // `?product=`, osCommerce's `products_id`, PrestaShop's `id_product`): any
154
+ // other one may be a search, a token or an order, never sent for a visitor
155
+ // without consent.
156
+ const PRODUCT_KEYS = new Set(['p', 'id', 'pid', 'product', 'product_id', 'productid', 'products_id', 'id_product', 'item', 'item_id', 'itemid', 'sku', 'variant']);
157
+
158
+ // Path segments of pages that are no product's, and may name what a visitor
159
+ // searched, bought or is: search, cart, checkout and order, account and
160
+ // sign-in pages, and the shops' own category and tag lists.
161
+ const NOT_PRODUCT = new Set(['search', 'catalogsearch', 'cart', 'basket', 'checkout', 'order', 'orders', 'order-received', 'order-pay', 'track-order', 'order-tracking',
162
+ 'thank-you', 'thankyou', 'payment', 'invoice', 'account', 'my-account', 'customer', 'login', 'logout', 'signin', 'sign-in', 'register', 'password',
163
+ 'lost-password', 'reset-password', 'wishlist', 'wp-admin', 'wp-login.php', 'wp-json', 'admin', 'product-category', 'product-tag']);
164
+
165
+ /**
166
+ * The page before's id for an event without consent (AP-1066), by
167
+ * `addressId`, or '' when the address cannot be a product page: the home
168
+ * page, a path through a search, cart, checkout, order or account page, or a
169
+ * query with any name but a product's. Its address may hold what a visitor
170
+ * searched or an order's key, which no event may carry for them.
171
+ *
172
+ * @param {string} raw
173
+ * @returns {string}
174
+ */
175
+ export function beforeId(raw) {
176
+ let u;
177
+ try {
178
+ u = new URL(raw);
179
+ } catch {
180
+ return '';
181
+ }
182
+ const segments = u.pathname.split('/').filter((s) => s !== '').map((s) => {
183
+ try {
184
+ return decodeURIComponent(s).toLowerCase();
185
+ } catch {
186
+ return s.toLowerCase();
187
+ }
188
+ });
189
+ if (segments.some((s) => NOT_PRODUCT.has(s))) return '';
190
+ const keys = u.search.slice(1).split('&').map(siteKey).filter((key) => key !== null);
191
+ if (keys.some((key) => !PRODUCT_KEYS.has(key))) return '';
192
+ // The home page, also by its script's name, unless a product's query follows.
193
+ if (keys.length === 0 && (segments.length === 0 || (segments.length === 1 && /^index\.(php|html?)$/.test(segments[0])))) return '';
194
+ return addressId(raw);
195
+ }
196
+
148
197
  // Over the cap: the longest prefix cut on a character that leaves room for
149
198
  // '~' and the FNV-1a 64 hash of the whole id's UTF-8, in 16 hex digits.
150
199
  function fit(id) {
@@ -275,6 +324,9 @@ export function bare(at) {
275
324
  }
276
325
  }
277
326
 
327
+ // The page before on this host, from the browser alone (AP-1066), else ''.
328
+ export const cameFrom = (at) => onHost(String(globalThis.document?.referrer ?? ''), at);
329
+
278
330
  // An http(s) address on the page's host, resolved against it, else ''.
279
331
  function onHost(s, at) {
280
332
  if (s.trim() === '') return '';
package/src/shopify.js CHANGED
@@ -18,7 +18,7 @@ import { fillRows, followReturns, landing } from './shops.js';
18
18
  // Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
19
19
  import { ownBrowser } from './client.js';
20
20
  import './history.js';
21
- import './page.js';
21
+ import { cameFrom } from './page.js';
22
22
  import './storage.js';
23
23
  import './transport.js';
24
24
 
@@ -174,7 +174,7 @@ export async function shopifyTheme(options) {
174
174
  await seen(JSON.stringify({ page, products }), false).catch(() => null);
175
175
  };
176
176
  if (product && !editor) describe();
177
- if (handle && !editor) landing(recapi, handle);
177
+ if (handle && !editor) landing(recapi, handle, handleOf(cameFrom(location.href)));
178
178
 
179
179
  // Fills <div id="recapi-recommendations">&nbsp;</div> wherever the theme has one.
180
180
  const slot = document.getElementById('recapi-recommendations');
package/src/shops.js CHANGED
@@ -18,12 +18,13 @@ export { onReturn };
18
18
  * fragment, or ?rec=: old links, cards that can't use a fragment), which
19
19
  * then leaves the address: a shared link must not credit strangers' visits.
20
20
  * A prerendered page (a link under the pointer) may never be opened.
21
+ * `before` is the product page the visitor came from, if known.
21
22
  */
22
- export function landing(recapi, item) {
23
+ export function landing(recapi, item, before) {
23
24
  const viewed = () => {
24
25
  const fragment = REC_ID.test(location.hash.slice(1)) ? location.hash.slice(1) : null;
25
26
  const linked = fragment ?? new URLSearchParams(location.search).get('rec');
26
- recapi.track(item, 'view', { recommendationId: linked });
27
+ recapi.track(item, 'view', { recommendationId: linked, contextItemId: before || undefined });
27
28
  if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
28
29
  else if (linked !== null) {
29
30
  // The other parameters (a variant) keep their exact text.
@@ -19,7 +19,7 @@ import { bought, fillRows, followReturns, landing, orderStorage } from './shops.
19
19
  // Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
20
20
  import './client.js';
21
21
  import './history.js';
22
- import './page.js';
22
+ import { beforeId, cameFrom } from './page.js';
23
23
  import './storage.js';
24
24
  import './transport.js';
25
25
 
@@ -103,7 +103,9 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
103
103
  // The product id is the item id: the widget loads products by it. A
104
104
  // card's link carries its list's id in the fragment, which no page cache
105
105
  // sees: an unknown ?rec= made every click from the row miss it.
106
- if (page.product) landing(recapi, page.product);
106
+ // Products go by number here: the page before goes by its address, which
107
+ // recapi matches to the product whose link it is (AP-1066).
108
+ if (page.product) landing(recapi, page.product, beforeId(cameFrom(location.href)));
107
109
 
108
110
  // The checkout is the shop's own page, so the purchases find the visitor
109
111
  // and the recommendations they clicked where the product pages left them.