@recapi/client 0.13.0 → 0.15.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.13.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.15.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).
@@ -732,7 +732,7 @@ for (const item of items) {
732
732
 
733
733
  ### Client methods
734
734
 
735
- - **`track(itemId, level, { recommendationId? })`**: `level` is any integer
735
+ - **`track(itemId, level, { recommendationId?, value?, currency? })`**: `level` is any integer
736
736
  0–10 of the [recommended scale](https://recapi.io/docs/api#interaction-levels) (3
737
737
  opened, 5 strong interest, 10 the action that matters most), or one of its
738
738
  shop names `'view'`, `'cart'` and `'purchase'` (3, 5 and 10). `'reject'`
@@ -744,7 +744,10 @@ for (const item of items) {
744
744
  timestamp and a fresh `event_id` (the idempotency
745
745
  key, reused on retries). Level 0 means an impression: it is sent but does
746
746
  not change the history. Throws `RecapiError('invalid_request')` on a bad
747
- level. An item id follows the API's rules, 1–256 bytes of UTF-8
747
+ level. A purchase may carry `{ value, currency }` (what the buyer paid for
748
+ the line, and its ISO 4217 code such as `'EUR'`), kept for the sales figure
749
+ of a lift test; a negative value, or a currency without a value or not of
750
+ three letters, throws the same error. An item id follows the API's rules, 1–256 bytes of UTF-8
748
751
  (128 characters of Cyrillic or accented Latin, 85 of CJK) without
749
752
  control characters; any other drops the event and reports it instead of
750
753
  throwing, as a visitor's URL can carry one (see [Fallback](#fallback)). A stored history entry whose id breaks the rule,
@@ -1102,6 +1105,12 @@ minifier, to keep zero dev dependencies.
1102
1105
 
1103
1106
  ## Changes
1104
1107
 
1108
+ - 2026-11-22: version 0.15.0. `track()` takes a purchase's `value` and
1109
+ `currency`, sent with the event for the sales figure of a lift test.
1110
+ - 2026-11-21: version 0.14.0. Shopify: a row in a full-width section
1111
+ (Dawn's Custom Liquid) keeps to the theme's page width, four cards across
1112
+ (two on a phone); the theme editor's preview shows the row and sends or
1113
+ stores nothing. Pieces already pasted get both with nothing to paste again.
1105
1114
  - 2026-11-20: version 0.13.0. `magento.js`, served beside `index.js` with
1106
1115
  its day of cache: the Magento module's storefront code (the rows, consent,
1107
1116
  the view and the add-to-cart events). The module now prints only the page's
package/index.d.ts CHANGED
@@ -168,7 +168,11 @@ export interface PopularResult {
168
168
  export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
169
169
 
170
170
  export interface RecapiClient {
171
- track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null }): void;
171
+ /**
172
+ * `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
173
+ * (three letters, any case); a currency needs a value. An invalid pair throws `RecapiError('invalid_request')`, as a bad level does.
174
+ */
175
+ track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string }): void;
172
176
  /** 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. */
173
177
  recommend(params?: RecommendParams): Promise<RecommendResult>;
174
178
  /** 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.13.0",
3
+ "version": "0.15.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
@@ -545,10 +545,14 @@ export function createClient(options) {
545
545
  * Does nothing under Do Not Track (see `respectDoNotTrack`).
546
546
  * An `itemId` the API would refuse (a page often takes it from a
547
547
  * visitor's URL) drops the event and goes to `onError`, without throwing.
548
- * @param {{ recommendationId?: string | null }} [options] Overrides the
549
- * automatic attribution. `null` (a fallback list's id) is no override.
548
+ * @param {{ recommendationId?: string | null, value?: number,
549
+ * currency?: string }} [options] `recommendationId` overrides the
550
+ * automatic attribution; `null` (a fallback list's id) is no override.
551
+ * `value` is what the buyer paid for a purchase's line (0 for a free
552
+ * line), `currency` its ISO 4217 code (three letters, any case); a
553
+ * currency needs a value. An invalid pair throws, as a bad level does.
550
554
  */
551
- track(itemId, level, { recommendationId: explicit } = {}) {
555
+ track(itemId, level, { recommendationId: explicit, value, currency } = {}) {
552
556
  start();
553
557
  // A fallback list has a null id, and a page passing it on must not
554
558
  // send `null` or lose the item's earlier, real attribution.
@@ -560,6 +564,7 @@ export function createClient(options) {
560
564
  "level must be an integer between -10 and 10, or 'view', 'cart', 'purchase' or 'reject'"
561
565
  );
562
566
  }
567
+ checkAmount(value, currency);
563
568
  // A page often takes this id from a visitor's URL, so a crafted link
564
569
  // must not fail it. Nothing is kept: in the history it would make the
565
570
  // API refuse every later list. The line never quotes the visitor's id.
@@ -584,6 +589,8 @@ export function createClient(options) {
584
589
  user_id: userId ?? undefined,
585
590
  anon_id: anonId ?? undefined,
586
591
  recommendation_id: attributed,
592
+ value,
593
+ currency,
587
594
  timestamp: new Date(t).toISOString(),
588
595
  event_id: uuid()
589
596
  }));
@@ -880,6 +887,22 @@ function withRejected(exclude, rejected) {
880
887
  return [...out];
881
888
  }
882
889
 
890
+ /**
891
+ * Refuses what the API would refuse in an event: a value that is not a
892
+ * finite number of at least 0, a currency that is not three ASCII letters or
893
+ * comes without a value. `undefined` is no value, no currency.
894
+ */
895
+ function checkAmount(value, currency) {
896
+ if (value !== undefined && !(typeof value === 'number' && value >= 0 && value !== Infinity)) {
897
+ throw new RecapiError('invalid_request', 'value must be a number of at least 0');
898
+ }
899
+ if (currency === undefined) return;
900
+ if (value === undefined) throw new RecapiError('invalid_request', 'currency needs a value');
901
+ if (typeof currency !== 'string' || !/^[A-Za-z]{3}$/.test(currency)) {
902
+ throw new RecapiError('invalid_request', 'currency must be three letters (ISO 4217)');
903
+ }
904
+ }
905
+
883
906
  function compact(object) {
884
907
  return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
885
908
  }
package/src/shopify.js CHANGED
@@ -40,7 +40,11 @@ export async function shopifyTheme(options) {
40
40
  window.Shopify.loadFeatures([{ name: 'consent-tracking-api', version: '0.2' }],
41
41
  (error) => done(error ? null : window.Shopify.customerPrivacy));
42
42
  });
43
- const consent = privacy?.analyticsProcessingAllowed?.() === true;
43
+ // The theme editor's preview is the shop's own staff placing the row: it
44
+ // shows, but nothing is stored or sent about them (no view, cart or click).
45
+ // Its lists still count as shown: the API has no way to ask without counting.
46
+ const editor = window.Shopify?.designMode === true;
47
+ const consent = !editor && privacy?.analyticsProcessingAllowed?.() === true;
44
48
 
45
49
  // Shopify doesn't promise that the checkout's pixel can read this page's
46
50
  // storage, so the cart, which Shopify carries into the checkout, holds the
@@ -82,7 +86,7 @@ export async function shopifyTheme(options) {
82
86
  // is: withdrawing consent forgets it too.
83
87
  const DESCRIBED = 'recapi:described';
84
88
  document.addEventListener('visitorConsentCollected', (event) => {
85
- recapi.setConsent(event.detail?.analyticsAllowed === true);
89
+ recapi.setConsent(!editor && event.detail?.analyticsAllowed === true);
86
90
  if (recapi.getAnonId() === null) local.removeItem(DESCRIBED);
87
91
  });
88
92
 
@@ -164,7 +168,7 @@ export async function shopifyTheme(options) {
164
168
  // The page's number tells recapi which page this is: an empty one ends the list.
165
169
  await seen(JSON.stringify({ page, products }), false).catch(() => null);
166
170
  };
167
- if (product) describe();
171
+ if (product && !editor) describe();
168
172
  // A card's link carries its recommendation: without consent nothing on the
169
173
  // device remembers which list showed the product. In the fragment, which no
170
174
  // server or crawler sees: each list's new ?rec= looks like another page.
@@ -187,20 +191,31 @@ export async function shopifyTheme(options) {
187
191
  // A browser may preload the link under the pointer, and a page it prerenders
188
192
  // runs this script though nobody may ever open it: a click nobody made must
189
193
  // not be credited.
190
- if (handle && document.prerendering) document.addEventListener('prerenderingchange', viewed);
191
- else if (handle) viewed();
194
+ if (handle && !editor && document.prerendering) document.addEventListener('prerenderingchange', viewed);
195
+ else if (handle && !editor) viewed();
192
196
 
193
197
  // Fills <div id="recapi-recommendations">&nbsp;</div> wherever the theme has one.
194
198
  const slot = document.getElementById('recapi-recommendations');
195
199
  // A product row in the theme's colours and fonts. :where() weighs
196
- // nothing, so any rule of the theme's restyles the cards.
200
+ // nothing, so any rule of the theme's restyles the cards. Four cards
201
+ // across, as the theme's product grids show them, two where four would be
202
+ // narrower than 150px (a phone). The page-width rule is for themes with
203
+ // no page-width class of their own (below).
197
204
  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}` +
205
+ `:where(#${id}){display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start;align-content:start}` +
206
+ ':where(#recapi-recommendations.page-width,.recapi-bought-together.page-width){box-sizing:border-box;max-width:var(--page-width,1200px);margin-inline:auto;padding-inline:1.5rem}' +
199
207
  `:where(#${id} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
200
208
  `:where(#${id} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
201
209
  `:where(#${id} .recapi-price){font-weight:600}` +
202
210
  '</style>';
203
211
  const style = styleOf('recapi-recommendations');
212
+ // Dawn's Custom Liquid section spans the whole screen (no page-width box),
213
+ // so a row there took 15 narrow columns from the left edge: it keeps to
214
+ // the page width through the theme's own page-width class (Dawn's max-width
215
+ // and side margins). Horizon's puts its content in the page's column
216
+ // (section--page-width) unless the shop chose full width.
217
+ const wide = slot && !slot.closest('.page-width, .section--page-width');
218
+ if (wide) slot.classList.add('page-width');
204
219
  // Dawn and the themes built on it hide every empty div (div:empty
205
220
  // { display: none }): a slot pasted empty, as the quick start once
206
221
  // printed it, has no box, never comes near the screen, and the row would
@@ -331,7 +346,7 @@ export async function shopifyTheme(options) {
331
346
  // styles its title.
332
347
  if (second.length && !lists[1].fallback) {
333
348
  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>`);
349
+ slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${second.join('')}</div></div>`);
335
350
  }
336
351
  };
337
352
  // recommendLists() rejects only on a bad request: a page still loses no more than its rows.