@recapi/client 0.6.5 → 0.6.6

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
@@ -31,11 +31,11 @@ visit, private browsing) are not part of it.
31
31
 
32
32
  On a site without a build step (a theme, plain HTML), load the SDK from
33
33
  your recapi API with one tag. The API serves the files of `src/` as they
34
- are, gzipped, and browsers cache them for a year:
34
+ 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.6.5/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.6.6/index.js';
39
39
 
40
40
  const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com' });
41
41
  recapi.track('item-42', 'view'); // and the calls of the quick start below
@@ -47,8 +47,20 @@ dashboard's quick start shows this tag with your API's address. A site
47
47
  with a Content-Security-Policy allows that address in `script-src` and
48
48
  `connect-src`. Each version's files never change: a later version gets a
49
49
  new path, and an older path redirects to it, so a pasted tag keeps
50
- working. New visitors then get the new version; a browser that cached the
51
- older files may keep running them for up to a year.
50
+ working. You have no version to manage: new visitors get the new version at
51
+ once, and returning visitors move to it about a day after it ships. A browser
52
+ holding a copy over a day old may run that copy once more while it fetches
53
+ the new one.
54
+
55
+ Browsers keep `index.js`, the file the tag loads, for a day, and the other
56
+ files for a year: `index.js` is all it takes to reach a new version. The price
57
+ is in a long recapi outage: a returning visitor's copy over a day old runs at
58
+ most once more, and after that the library doesn't load until the API is back,
59
+ as for a first-time visitor. Your page isn't affected: its content and other
60
+ scripts keep working. Only the code in the same `<script>` block as the
61
+ `import` doesn't run, so keep anything that must run without recapi in another
62
+ block. A browser that got `index.js` before this header (November 2026) keeps
63
+ that copy for up to a year.
52
64
 
53
65
  With a bundler (Vite, webpack…), install the package instead:
54
66
 
@@ -143,11 +155,19 @@ in two places, both shown with your address in the dashboard's quick start:
143
155
  where no consent is required Shopify reports it allowed) and fails closed
144
156
  if the API doesn't load within 2 s. Without consent it stores nothing and
145
157
  sends events without `anon_id`, and each card links to its product with
146
- `?rec=<recommendation id>`, which the product page's view passes on, so a
147
- click is still credited (see [Consent](#consent-and-eprivacy)). The page
148
- then removes `rec` from its address (`history.replaceState`, other
149
- parameters kept): recapi credits an explicit id to whoever sends it, so a
150
- copied or shared link would credit strangers' visits and purchases to it.
158
+ `#<recommendation id>`, which the product page's view passes on, so a
159
+ click is still credited (see [Consent](#consent-and-eprivacy)). A fragment
160
+ never reaches a server, so a page cache serves the click its stored page and
161
+ a crawler sees no new address per list. The page then removes the id from its
162
+ address (`history.replaceState`, everything else kept): recapi credits an
163
+ explicit id to whoever sends it, so a copied or shared link would credit
164
+ strangers' visits and purchases to it. The page accepts only `#rec_` and hex
165
+ digits, and leaves any other fragment alone. A card uses `?rec=<recommendation
166
+ id>` instead when its address has a fragment of its own, or is the page
167
+ already open (a fragment wouldn't load it); the page still reads `?rec=`, for
168
+ those and for links already out there. A page the browser prerenders sends
169
+ its view only once it is shown (`prerenderingchange`), so a preload nobody
170
+ opened credits no click.
151
171
  - [`shopify/pixel.js`](shopify/pixel.js), a custom pixel (Settings →
152
172
  Customer events): on `product_added_to_cart` it tracks the product as a
153
173
  `cart` (level 5, the default conversion level, so a pilot's conversion
@@ -208,8 +228,12 @@ version, your address and your project (`jssdk.Shopify`).
208
228
  plugin (or a snippet for Code Snippets or WPCode) that prints the SDK on
209
229
  every page from `wp_footer`. The product id is the item id. It tracks:
210
230
 
211
- - a `view` on product pages, with `?rec=<recommendation id>` from a card's
212
- link (then removed from the address, as on Shopify);
231
+ - a `view` on product pages, with `#<recommendation id>` from a card's link
232
+ (then removed from the address, and sent only once a prerendered page is
233
+ shown, as on Shopify). On a shop with a page cache a `?rec=` link missed the
234
+ cache on every click: on a test shop (Cache Enabler, WordPress Playground, so
235
+ only hit or miss carries over) 0 of 7 hits at about 1.8 s first byte, against
236
+ 7 of 7 at about 50 ms with the fragment;
213
237
  - a `cart` (level 5) once per add to cart: on the classic product page's
214
238
  form submit (the page reloads, so it counts at once), or on jQuery's
215
239
  `added_to_cart` (Ajax buttons) or the blocks' `wc-blocks_added_to_cart`
@@ -539,9 +563,8 @@ for (const item of items) {
539
563
  are added to `exclude`, after yours, up to the API's limit of 500. The SDK does not send `explain`, which needs
540
564
  a secret key: call the API from your backend for that.
541
565
  - **`popular({ tagsAny, tagsAll, count })`** resolves to `{ items: [{ itemId, score, why, metadata }] }`.
542
- A public key goes in `?key=`, so the response can be cached by a CDN and
543
- the request needs no CORS preflight. A secret key (Node) goes in the
544
- `Authorization` header, because the API refuses a secret key in a URL.
566
+ A public key goes in `?key=`, so the response can be cached by a CDN.
567
+ [How the key is sent](#how-the-key-is-sent) gives the reason for the rest.
545
568
  The [Fallback](#fallback) sends the key the same way, and says when the list
546
569
  is empty instead of rejecting.
547
570
  - **`identify(userId, { history? })`**: see [Login and logout](#login-and-logout).
@@ -666,6 +689,20 @@ the oldest are dropped first. An explicit `recommendationId` always wins;
666
689
  when it is the id of the recommendation that showed the item, it is the
667
690
  click on the item too.
668
691
 
692
+ ### How the key is sent
693
+
694
+ A public key (`rk_pub_…`) goes in the URL as `?key=` on every call, and the JSON
695
+ body is labelled `Content-Type: text/plain`. So a browser sends the call at once,
696
+ without first asking permission with an `OPTIONS` request (the CORS preflight),
697
+ which would cost a network trip before a visit's first list and events. A public
698
+ key is public by design, as it is in the page's source, so seeing it in access logs
699
+ exposes nothing new.
700
+
701
+ A secret key (Node) goes in the `Authorization` header with
702
+ `Content-Type: application/json`, because the API refuses a secret key in a URL.
703
+
704
+ There is no option for this: the key's prefix decides.
705
+
669
706
  ### Event delivery
670
707
 
671
708
  Events are sent in batches every `flushIntervalMs`, or as soon as
@@ -693,8 +730,7 @@ succeed and storage errors print nothing. With an `onError`, nothing is printed.
693
730
  When the page is hidden (`visibilitychange` → `hidden`, or `pagehide`),
694
731
  the SDK sends the queue at once using `fetch` with `keepalive: true`.
695
732
  It does not use `navigator.sendBeacon`, because a beacon cannot send the
696
- `Authorization` header and the API accepts `?key=` only on
697
- `GET /v1/popular`. A keepalive fetch also survives page unload, but the
733
+ `Authorization` header a secret key needs. A keepalive fetch also survives page unload, but the
698
734
  browser allows at most 64 KiB of keepalive bodies in flight per page, all
699
735
  requests together. The SDK marks a request keepalive only up to 60,000
700
736
  bytes (about 250 typical events). A default batch of 100 events is about
@@ -761,7 +797,9 @@ Without consent, the SDK never reads or writes storage and creates no
761
797
  anonymous id. The history and the attribution map live in memory for the
762
798
  current page only. A single-page app keeps attribution. On a multi-page
763
799
  site, a click that loads the item's page is not attributed unless you
764
- pass the id yourself, for example in the link:
800
+ pass the id yourself, for example in the link. A fragment (`#${recommendationId}`,
801
+ read from `location.hash`) avoids a page cache miss, as the shop rows above do;
802
+ a query also reaches pages that read the id on the server:
765
803
 
766
804
  ```js
767
805
  // On the listing page: link each item with its recommendation id
@@ -831,13 +869,18 @@ key on a format change makes old data invisible.
831
869
 
832
870
  Budget: **6 KB gzip** after minification. The sources ship unminified with
833
871
  full JSDoc: 58 KB raw in five files, 20 KB as the API serves them (gzip -9),
834
- and the browser caches them for a year. With comments stripped and no
872
+ and the browser caches them. With comments stripped and no
835
873
  minification they are 8.5 KB gzip. A bundler's minifier should bring
836
874
  that under the budget, but this has not been measured: the repo has no
837
875
  minifier, to keep zero dev dependencies.
838
876
 
839
877
  ## Changes
840
878
 
879
+ - 2026-11-07: version 0.6.6. With a public key, `recommend()` and the event
880
+ batches go out with `?key=` and `Content-Type: text/plain`, no `Authorization`,
881
+ so a browser skips the permission request before them: a visit's first list
882
+ arrives one network trip sooner ([How the key is sent](#how-the-key-is-sent)).
883
+ Nothing changes in your code, and a secret key keeps the header.
841
884
  - 2026-11-05: version 0.6.5. A visitor's URL can't make `recommend()` or
842
885
  `track()` throw: a `contextItemId` the API would refuse gets popular items
843
886
  with no recommendation request, and such an `itemId` drops only that event.
@@ -918,8 +961,8 @@ The same steps in real browsers (Chromium, Firefox, WebKit): see
918
961
  [Testing](../../docs/development.md#testing).
919
962
 
920
963
  The API embeds `src/*.js` (module `recapi/sdkjs`, `embed.go`) and serves
921
- them at `/sdk/<version>/`, where browsers cache them for a year. So a
922
- change to `src/` needs a new version: bump `version` in `package.json`,
964
+ them at `/sdk/<version>/`, where browsers cache every file but `index.js` for
965
+ a year. So a change to `src/` needs a new version: bump `version` in `package.json`,
923
966
  add the entry the failing Go test `TestSDKChangesNeedANewVersion` prints
924
967
  to `published.json` (the digest is `sha256sum src/*.js | sha256sum`, then
925
968
  each file's exports), and change the `/sdk/<version>/` paths in this
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.6.5",
3
+ "version": "0.6.6",
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
@@ -153,6 +153,9 @@ export function createClient(options) {
153
153
  }
154
154
  };
155
155
  const transport = createTransport({ baseUrl, apiKey, fetch: fetchImpl, timeoutMs });
156
+ // A public key goes in the URL (no CORS preflight; popular() is CDN-cacheable),
157
+ // any other key in the header (Node with a secret key).
158
+ const auth = apiKey.startsWith(PUBLIC_KEY_PREFIX) ? 'query' : 'header';
156
159
  const popularCache = serverCacheMode();
157
160
  // The default adapter probes localStorage with a write, so it is picked at
158
161
  // the first storage access: never before consent, nor under Do Not Track.
@@ -290,7 +293,7 @@ export function createClient(options) {
290
293
  * away still completes.
291
294
  */
292
295
  async function sendBatch(events, { retry }) {
293
- const send = () => transport.request({ method: 'POST', path: '/v1/events', body: { events }, keepalive: true });
296
+ const send = () => transport.request({ method: 'POST', path: '/v1/events', auth, body: { events }, keepalive: true });
294
297
  const response = retry ? await withRetry(send, { sleep }) : await send();
295
298
  if (response?.rejected?.length) {
296
299
  report(new RecapiError('event_rejected', `${response.rejected.length} event(s) rejected`, {
@@ -363,6 +366,7 @@ export function createClient(options) {
363
366
  const response = await transport.request({
364
367
  method: 'POST',
365
368
  path: '/v1/recommendations',
369
+ auth,
366
370
  timeoutMs: deadline,
367
371
  body: compact({
368
372
  user_id: userId ?? undefined,
@@ -443,14 +447,13 @@ export function createClient(options) {
443
447
 
444
448
  /**
445
449
  * `GET /v1/popular` for `popular()` and the fallback; `deadline` defaults
446
- * to `timeoutMs`. A public key goes in the query string (CDN-cacheable, no
447
- * CORS preflight); any other key in the header (Node with a secret key).
450
+ * to `timeoutMs`.
448
451
  */
449
452
  async function fetchPopular({ tagsAny, tagsAll, count }, deadline) {
450
453
  const response = await transport.request({
451
454
  method: 'GET',
452
455
  path: '/v1/popular',
453
- auth: apiKey.startsWith(PUBLIC_KEY_PREFIX) ? 'query' : 'header',
456
+ auth,
454
457
  cache: popularCache,
455
458
  timeoutMs: deadline,
456
459
  query: { tags_any: tagsAny?.join(','), tags_all: tagsAll?.join(','), count }
package/src/transport.js CHANGED
@@ -1,11 +1,17 @@
1
1
  /**
2
2
  * HTTP layer: fetch with timeout, JSON, error mapping and retry.
3
3
  *
4
+ * A public key travels as `?key=` and a body as `text/plain`, because a browser
5
+ * sends such a call to another origin at once. `Authorization` or
6
+ * `Content-Type: application/json` would make it ask permission first (the CORS
7
+ * preflight), one more network trip before a visit's first list and events.
8
+ * The body is still JSON: the API doesn't read the `Content-Type`.
9
+ *
4
10
  * Page-hide flushing uses `fetch(..., { keepalive: true })` rather than
5
- * `navigator.sendBeacon`: a beacon cannot carry the `Authorization` header and
6
- * the API only accepts `?key=` on `GET /v1/popular`. A keepalive fetch
7
- * survives page unload like a beacon does, as long as in-flight keepalive
8
- * bodies stay under the browser's 64 KiB budget.
11
+ * `navigator.sendBeacon`: a beacon cannot carry the `Authorization` header a
12
+ * secret key needs, and a keepalive fetch survives page unload like a beacon
13
+ * does, as long as in-flight keepalive bodies stay under the browser's 64 KiB
14
+ * budget.
9
15
  *
10
16
  * @module transport
11
17
  */
@@ -62,8 +68,9 @@ export class RecapiError extends Error {
62
68
  * @property {string} path
63
69
  * @property {Record<string, string | number | undefined>} [query]
64
70
  * @property {unknown} [body]
65
- * @property {'header' | 'query'} [auth] `query` sends `?key=` so GET
66
- * responses are CDN-cacheable and need no CORS preflight.
71
+ * @property {'header' | 'query'} [auth] `query` sends `?key=`, and a body as
72
+ * `text/plain`, so the call needs no CORS preflight and a GET's response is
73
+ * CDN-cacheable. Only for a public key: the API refuses a secret key in a URL.
67
74
  * @property {boolean} [keepalive] Let the request outlive the page.
68
75
  * @property {RequestCache} [cache] fetch's cache mode; the runtime's default when unset.
69
76
  * @property {number} [timeoutMs]
@@ -92,7 +99,7 @@ export function createTransport({ baseUrl, apiKey, fetch, timeoutMs: defaultTime
92
99
  const init = { method, headers };
93
100
  if (cache) init.cache = cache;
94
101
  if (body !== undefined) {
95
- headers['Content-Type'] = 'application/json';
102
+ headers['Content-Type'] = auth === 'query' ? 'text/plain' : 'application/json';
96
103
  init.body = JSON.stringify(body);
97
104
  if (keepalive && byteLength(init.body) <= KEEPALIVE_MAX_BYTES) init.keepalive = true;
98
105
  }