@findlane/browser 0.23.0 → 0.25.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
@@ -79,6 +79,8 @@ A response has `hits` (each with its `record` and any `highlights`), `total`, `f
79
79
 
80
80
  The public ID grants search access only to its index, and it is visible in browser source. By default the API returns every uploaded record field. `attributesToRetrieve` requests fewer fields for speed, but it does not make the others private. Origin checks constrain browsers; they do not authenticate other callers. Keep public catalog fields safe to expose. The dashboard can remove origins, add server-enforced restrictions, or rotate the ID.
81
81
 
82
+ For logged-in people, pass `signedKey`: a short-lived key your server signs with the server SDK's `signSearchKey`, or a function that fetches one. Its restrictions replace the index's public settings. See [Logged-in visitors](https://findlane.dev/docs/security#logged-in-visitors).
83
+
82
84
  ## Errors
83
85
 
84
86
  Failed requests throw a `FindlaneError` with the HTTP `status` and the API's message:
package/dist/index.d.ts CHANGED
@@ -298,14 +298,31 @@ export type EventItem = {
298
298
  quantity?: number;
299
299
  price?: number;
300
300
  };
301
- /** Where a clicked product was: its place in the results (from 1), and the search's query or the
302
- * recommendation list (and the product whose list it was). */
301
+ /** Where a clicked product was: its place in the results (from 1), and the search's query and filters, or the
302
+ * recommendation list (and the product whose list it was). A click on a search the page noted with `landed` is
303
+ * marked with how the page was opened from outside the site; `landing` and `network` say so yourself. */
303
304
  export type ClickDetails = {
304
305
  position?: number;
305
306
  query?: string;
306
307
  list?: "goesWith" | "similar" | "together" | "related";
307
308
  from?: string;
309
+ /** The search's filters, as it took them: sales by filter value count them. */
310
+ filters?: Record<string, unknown>;
311
+ landing?: Landing["kind"];
312
+ network?: string;
313
+ };
314
+ /** How a page was opened from outside the site: an ad (with its network, when its click ID or tags name one), an
315
+ * email, or another site's link. Revenue from search leaves such searches' clicks out. */
316
+ export type Landing = {
317
+ kind: "ad" | "email" | "link";
318
+ network?: string;
308
319
  };
320
+ /** How a page with this address (`search`) and referrer was opened from outside the site on `host`: an ad click
321
+ * ID, or `utm_medium` saying paid, is an ad; `utm_medium` email or newsletter an email; other `utm_*` tags,
322
+ * `fbclid` alone (Facebook and Instagram add it to every link out) or another site's referrer, a link. Null
323
+ * otherwise, an empty referrer without tags too: some sites send none from their own pages. The search box
324
+ * widget decides the same way. */
325
+ export declare function landingOf(search: string, referrer: string, host: string): Landing | null;
309
326
  /** Events from the page, sent in the background: a batch a second, and what's left when the page is
310
327
  * hidden or closed. They carry no cookie, and no ID unless `visitorIds` is on. */
311
328
  export type BrowserEvents = {
@@ -313,6 +330,11 @@ export type BrowserEvents = {
313
330
  * (React's double mount in development, a re-render), so it isn't sent. */
314
331
  view(objectID: string): void;
315
332
  click(objectID: string, details?: ClickDetails): void;
333
+ /** The page shows search `q` from its address, such as a results page a link opened. When the page was opened
334
+ * from outside the site (an ad, an email, another site: `landingOf`), clicks on that search are marked so, and
335
+ * with `visitorIds` for the rest of the visit, so revenue from search leaves them out. `SearchProvider` with
336
+ * `routing` calls it. */
337
+ landed(q: string): void;
316
338
  /** A query suggestion was picked: the search, its place in its list (from 1), and whether it was
317
339
  * suggested for what was typed, or was a popular or recent search in an empty box. */
318
340
  suggestion(query: string, details?: {
@@ -364,18 +386,29 @@ export type BrowserClientOptions = {
364
386
  * banner covers analytics, or your shoppers don't need one; with `events: "afterConsent"` the IDs
365
387
  * wait for consent as events do. */
366
388
  visitorIds?: boolean;
389
+ /** A signed key (0.25.0) from your server (the server SDK's `signSearchKey`), for a person who's logged in:
390
+ * searches and did-you-mean suggestions send it, and its restrictions replace the index's public policy and
391
+ * allowed sites. Or a function that fetches one: called for the first search, again shortly before the key
392
+ * expires, and once more if the API says it has. Make a new client when the person changes. */
393
+ signedKey?: string | (() => string | Promise<string>);
367
394
  };
368
395
  export declare class SearchBrowserClient {
369
396
  private readonly url;
370
397
  private readonly origin;
371
398
  private readonly publicId;
372
399
  private readonly fetcher;
400
+ private readonly signer?;
401
+ /** The signed key a function gave, and when it expires. */
402
+ private signed;
373
403
  /** Views, clicks, add-to-carts and orders, for the index's Events page and Bought together. */
374
404
  readonly events: BrowserEvents;
375
405
  /** The shopper's recent searches, kept in this browser only. */
376
406
  readonly recentSearches: RecentSearches;
377
407
  private popular;
378
408
  constructor(options: BrowserClientOptions);
409
+ /** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
410
+ * expires, or at once when `fresh`. */
411
+ private signedKey;
379
412
  private post;
380
413
  private get;
381
414
  /** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
package/dist/index.js CHANGED
@@ -52,12 +52,62 @@ export class FindlaneError extends Error {
52
52
  this.name = "FindlaneError";
53
53
  }
54
54
  }
55
+ // Ad click IDs and their networks. The ID itself is never kept.
56
+ const clickIds = { gclid: "google", gbraid: "google", wbraid: "google", dclid: "google", msclkid: "microsoft",
57
+ ttclid: "tiktok", twclid: "x", li_fat_id: "linkedin", epik: "pinterest", sccid: "snapchat" };
58
+ const paidMedium = /^(cpc|ppc|cpm|cpv|paid|paid[-_ ]?(search|social|media)|display|banner|retargeting|remarketing|ads?)$/;
59
+ const sourceNetworks = [[/google|youtube/, "google"], [/bing|microsoft/, "microsoft"],
60
+ [/facebook|instagram|^fb$|^ig$|meta/, "meta"], [/tiktok/, "tiktok"], [/twitter|^x$/, "x"], [/linkedin/, "linkedin"],
61
+ [/pinterest/, "pinterest"], [/snapchat/, "snapchat"]];
62
+ /** How a page with this address (`search`) and referrer was opened from outside the site on `host`: an ad click
63
+ * ID, or `utm_medium` saying paid, is an ad; `utm_medium` email or newsletter an email; other `utm_*` tags,
64
+ * `fbclid` alone (Facebook and Instagram add it to every link out) or another site's referrer, a link. Null
65
+ * otherwise, an empty referrer without tags too: some sites send none from their own pages. The search box
66
+ * widget decides the same way. */
67
+ export function landingOf(search, referrer, host) {
68
+ const params = new URLSearchParams(search);
69
+ const named = new Map([...params.keys()].map((key) => [key.toLowerCase(), params.get(key)?.trim() ?? ""]));
70
+ for (const [id, network] of Object.entries(clickIds))
71
+ if (named.get(id))
72
+ return { kind: "ad", network };
73
+ const medium = (named.get("utm_medium") ?? "").toLowerCase();
74
+ if (paidMedium.test(medium)) {
75
+ const source = (named.get("utm_source") ?? "").toLowerCase();
76
+ const network = sourceNetworks.find(([pattern]) => pattern.test(source))?.[1];
77
+ return network ? { kind: "ad", network } : { kind: "ad" };
78
+ }
79
+ if (/^(e-?mail|newsletter)$/.test(medium))
80
+ return { kind: "email" };
81
+ if (named.get("fbclid") || [...named].some(([key, value]) => key.startsWith("utm_") && value))
82
+ return { kind: "link" };
83
+ const bare = (name) => name.toLowerCase().replace(/^www\./, "");
84
+ try {
85
+ if (referrer && bare(new URL(referrer).hostname) !== bare(host))
86
+ return { kind: "link" };
87
+ }
88
+ catch { }
89
+ return null;
90
+ }
91
+ const sameQuery = (a, b) => a.trim().toLowerCase().replace(/\s+/g, " ") === b.trim().toLowerCase().replace(/\s+/g, " ");
92
+ const landed = (value) => !!value && typeof value == "object" && typeof value.q == "string" &&
93
+ ["ad", "email", "link"].includes(value.kind) && ["string", "undefined"].includes(typeof value.network);
55
94
  /** The hosted Findlane API, used unless `baseUrl` says otherwise. */
56
95
  export const defaultBaseUrl = "https://api.findlane.dev";
57
96
  const day = 86_400_000;
97
+ /** When a signed key expires, in Unix seconds, from its restrictions; Infinity when it can't be read. */
98
+ function signedKeyExpiry(signedKey) {
99
+ try {
100
+ const until = atob(signedKey).slice(64).match(/(?:^|&)validUntil=(\d+)/)?.[1];
101
+ return until ? Number(until) : Infinity;
102
+ }
103
+ catch {
104
+ return Infinity;
105
+ }
106
+ }
58
107
  /** The visitor and visit IDs of a public ID, kept on the device: the visitor's in localStorage, made
59
108
  * anew 13 months after it was made (use doesn't extend it); the visit's in sessionStorage, made anew
60
- * after 30 minutes without events. Storage that can't be used (a sandboxed frame's) means no IDs. */
109
+ * after 30 minutes without events, with how the visit's search was opened from outside the site, if it was.
110
+ * Storage that can't be used (a sandboxed frame's) means no IDs. */
61
111
  function deviceIds(publicId) {
62
112
  const keys = { visitor: `findlane:visitor:${publicId}`, visit: `findlane:visit:${publicId}` };
63
113
  // 16 random bytes in base64url: letters, digits, - and _, as the API takes IDs.
@@ -65,24 +115,39 @@ function deviceIds(publicId) {
65
115
  .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
66
116
  const read = (storage, key) => {
67
117
  const value = JSON.parse(storage.getItem(key) ?? "null");
68
- return typeof value?.id == "string" && typeof value.at == "number" ? value : null;
118
+ return typeof value?.id == "string" && typeof value.at == "number"
119
+ ? { id: value.id, at: value.at, ...(landed(value.landing) ? { landing: value.landing } : {}) } : null;
120
+ };
121
+ const live = (now) => {
122
+ const visit = read(sessionStorage, keys.visit);
123
+ return visit && now - visit.at <= 30 * 60_000 ? visit : null;
69
124
  };
70
125
  return {
71
- /** The IDs for a request now, made when there are none or they're old. */
72
- use(now = Date.now()) {
126
+ /** The IDs for a request now, made when there are none or they're old; the visit keeps `landing`, or its own. */
127
+ use(now = Date.now(), landing) {
73
128
  try {
74
129
  let visitor = read(localStorage, keys.visitor);
75
130
  if (!visitor || now - visitor.at > 395 * day)
76
131
  localStorage.setItem(keys.visitor, JSON.stringify(visitor = { id: random(), at: now }));
77
- const visit = read(sessionStorage, keys.visit);
78
- const visitId = visit && now - visit.at <= 30 * 60_000 ? visit.id : random();
79
- sessionStorage.setItem(keys.visit, JSON.stringify({ id: visitId, at: now }));
132
+ const visit = live(now);
133
+ const visitId = visit?.id ?? random();
134
+ const kept = landing ?? visit?.landing;
135
+ sessionStorage.setItem(keys.visit, JSON.stringify({ id: visitId, at: now, ...(kept ? { landing: kept } : {}) }));
80
136
  return { visitorId: visitor.id, visitId };
81
137
  }
82
138
  catch {
83
139
  return null;
84
140
  }
85
141
  },
142
+ /** How the live visit's search was opened from outside the site, if it was. */
143
+ landing(now = Date.now()) {
144
+ try {
145
+ return live(now)?.landing ?? null;
146
+ }
147
+ catch {
148
+ return null;
149
+ }
150
+ },
86
151
  /** Deletes them from the device, and returns those there were. */
87
152
  clear() {
88
153
  try {
@@ -103,6 +168,16 @@ function eventSender(url, fetcher, mode, ids) {
103
168
  let timer;
104
169
  let listening = false;
105
170
  let lastView = { objectID: "", at: 0 };
171
+ // The page's search when the page was opened from outside the site (landed).
172
+ let page = null;
173
+ const landingFor = (query) => {
174
+ if (!query)
175
+ return null;
176
+ if (page && sameQuery(page.q, query))
177
+ return page;
178
+ const visit = ids?.landing();
179
+ return visit && sameQuery(visit.q, query) ? visit : null;
180
+ };
106
181
  const send = (body) => {
107
182
  // A beacon outlives the page; text/plain needs no CORS preflight.
108
183
  if (fetcher || !(typeof navigator == "object" && navigator.sendBeacon?.(url, new Blob([body], { type: "text/plain" }))))
@@ -113,7 +188,7 @@ function eventSender(url, fetcher, mode, ids) {
113
188
  clearTimeout(timer);
114
189
  timer = undefined;
115
190
  while (allowed && queue.length)
116
- send(JSON.stringify({ ...ids?.use(), events: queue.splice(0, 100) }));
191
+ send(JSON.stringify({ ...ids?.use(Date.now(), page), events: queue.splice(0, 100) }));
117
192
  };
118
193
  const add = (event) => {
119
194
  if (allowed === false)
@@ -135,7 +210,15 @@ function eventSender(url, fetcher, mode, ids) {
135
210
  lastView = { objectID, at: now };
136
211
  add({ type: "view", objectID });
137
212
  },
138
- click: (objectID, details) => add({ type: "click", objectID, ...details }),
213
+ click(objectID, details) {
214
+ const landing = details?.list || details?.landing ? null : landingFor(details?.query);
215
+ add({ type: "click", objectID, ...details, ...(landing ? { landing: landing.kind, ...(landing.network ? { network: landing.network } : {}) } : {}) });
216
+ },
217
+ landed(q) {
218
+ const landing = q.trim() && typeof location == "object" && typeof document == "object"
219
+ ? landingOf(location.search, document.referrer, location.hostname) : null;
220
+ page = landing ? { ...landing, q: q.trim() } : null;
221
+ },
139
222
  suggestion: (query, details) => add({ type: "suggestion", query, ...details }),
140
223
  bannerClick: (rule, details) => add({ type: "bannerClick", rule, ...details }),
141
224
  addToCart: (items, options) => add({ type: "addToCart", items, ...options }),
@@ -164,6 +247,9 @@ export class SearchBrowserClient {
164
247
  origin;
165
248
  publicId;
166
249
  fetcher;
250
+ signer;
251
+ /** The signed key a function gave, and when it expires. */
252
+ signed = null;
167
253
  /** Views, clicks, add-to-carts and orders, for the index's Events page and Bought together. */
168
254
  events;
169
255
  /** The shopper's recent searches, kept in this browser only. */
@@ -176,21 +262,43 @@ export class SearchBrowserClient {
176
262
  this.url = `${(options.baseUrl ?? defaultBaseUrl).replace(/\/$/, "")}/api/public/indexes/${options.publicId}`;
177
263
  this.origin = new URL(this.url).origin;
178
264
  this.fetcher = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
265
+ this.signer = options.signedKey;
179
266
  this.events = eventSender(options.eventsUrl ?? `${this.url}/events`, options.fetch, options.events ?? true, options.visitorIds ? deviceIds(options.publicId) : null);
180
267
  this.recentSearches = new RecentSearches(options.publicId);
181
268
  }
182
- async post(operation, request, signal) {
269
+ /** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
270
+ * expires, or at once when `fresh`. */
271
+ signedKey(fresh) {
272
+ const signer = this.signer;
273
+ if (signer === undefined)
274
+ return undefined;
275
+ if (typeof signer == "string")
276
+ return Promise.resolve(signer);
277
+ if (fresh || !this.signed || Date.now() / 1000 > this.signed.until - 30) {
278
+ const entry = { key: Promise.resolve().then(signer), until: Infinity };
279
+ entry.key.then((key) => { entry.until = signedKeyExpiry(key); }, () => { if (this.signed === entry)
280
+ this.signed = null; });
281
+ this.signed = entry;
282
+ }
283
+ return this.signed.key;
284
+ }
285
+ async post(operation, request, signal, renewed = false) {
286
+ // A signed key goes in the body, so the request needs no preflight.
287
+ const signing = operation === "search" || operation === "suggest" ? this.signedKey(renewed) : undefined;
183
288
  const response = await this.fetcher(`${this.url}/${operation}`, {
184
289
  method: "POST",
185
290
  // JSON as text/plain: browsers send it without asking the API first (a CORS preflight), which
186
291
  // saves a round trip.
187
292
  headers: { "content-type": "text/plain" },
188
- body: JSON.stringify(request),
293
+ body: JSON.stringify(signing ? { ...request, signedKey: await signing } : request),
189
294
  signal,
190
295
  });
191
296
  const data = await response.json();
192
- if (!response.ok)
297
+ if (!response.ok) {
298
+ if (signing && !renewed && response.status === 401 && data.expired && typeof this.signer == "function")
299
+ return this.post(operation, request, signal, true);
193
300
  throw new FindlaneError(response.status, data.error ?? `HTTP ${response.status}`);
301
+ }
194
302
  return data;
195
303
  }
196
304
  // Lists are read with GET, which browsers send without a preflight and may keep for 30 seconds.
@@ -1,5 +1,5 @@
1
1
  import { type ReactNode } from "react";
2
- import { SearchBrowserClient } from "../index.js";
2
+ import { SearchBrowserClient, type BrowserClientOptions } from "../index.js";
3
3
  /** Where to search: a public ID (with an optional `baseUrl`), or a client you made. Leave both out
4
4
  * inside a FindlaneProvider. */
5
5
  export type ClientOptions = {
@@ -7,8 +7,9 @@ export type ClientOptions = {
7
7
  baseUrl?: string;
8
8
  client?: SearchBrowserClient;
9
9
  };
10
- /** Sets the index once for the hooks and components inside it. */
11
- export declare function FindlaneProvider({ children, ...options }: ClientOptions & {
10
+ /** Sets the index once for the hooks and components inside it. With `signedKey` (0.25.0), a signed key from your
11
+ * server, or a function that fetches one, the searches inside it are a logged-in person's (SearchBrowserClient). */
12
+ export declare function FindlaneProvider({ children, ...options }: ClientOptions & Pick<BrowserClientOptions, "signedKey"> & {
12
13
  children: ReactNode;
13
14
  }): import("react").JSX.Element;
14
15
  export declare function useClient(options?: ClientOptions): SearchBrowserClient;
@@ -1,12 +1,20 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- import { createContext, useContext, useMemo } from "react";
3
+ import { createContext, useContext, useMemo, useRef } from "react";
4
4
  import { SearchBrowserClient } from "../index.js";
5
5
  const ClientContext = createContext(null);
6
- function useOwnClient({ publicId, baseUrl, client }) {
7
- return useMemo(() => client ?? (publicId ? new SearchBrowserClient({ publicId, baseUrl }) : null), [client, publicId, baseUrl]);
6
+ function useOwnClient({ publicId, baseUrl, client, signedKey }) {
7
+ // A function is read when the client needs a key, so a new one each render keeps the client (and its
8
+ // cached results); a new key string makes a new client, for the person it's for.
9
+ const signer = useRef(signedKey);
10
+ signer.current = signedKey;
11
+ const kind = typeof signedKey == "function" ? "function" : signedKey;
12
+ return useMemo(() => client ?? (publicId ? new SearchBrowserClient({ publicId, baseUrl,
13
+ ...(typeof signer.current == "function" ? { signedKey: () => signer.current() }
14
+ : signer.current ? { signedKey: signer.current } : {}) }) : null), [client, publicId, baseUrl, kind]);
8
15
  }
9
- /** Sets the index once for the hooks and components inside it. */
16
+ /** Sets the index once for the hooks and components inside it. With `signedKey` (0.25.0), a signed key from your
17
+ * server, or a function that fetches one, the searches inside it are a logged-in person's (SearchBrowserClient). */
10
18
  export function FindlaneProvider({ children, ...options }) {
11
19
  const client = useOwnClient(options);
12
20
  if (!client)
@@ -27,7 +27,11 @@ export function SearchProvider(props) {
27
27
  };
28
28
  });
29
29
  useClientLayoutEffect(() => {
30
- store.start(routing && !state ? stateFromUrl(window.location.search, config) : undefined);
30
+ const fromUrl = routing && !state ? stateFromUrl(window.location.search, config) : undefined;
31
+ // A search the address opened, perhaps from an ad, an email or another site, whose clicks are marked so.
32
+ if (fromUrl?.q)
33
+ client.events.landed(fromUrl.q);
34
+ store.start(fromUrl);
31
35
  return () => store.stop();
32
36
  // eslint-disable-next-line react-hooks/exhaustive-deps
33
37
  }, [store]);
@@ -62,7 +62,7 @@ export declare class SearchStore<T = unknown> {
62
62
  get settings(): SearchConfig;
63
63
  /** Opens the connection to the API before the first search needs it (the client's warm). */
64
64
  warm(): void;
65
- /** Sends a click on a result: its place in the results, from 1, and the query they're for. A related
65
+ /** Sends a click on a result: its place in the results, from 1, and the query and filters they're for. A related
66
66
  * result's click says so (list "related"), with its place among them. */
67
67
  click(objectID: string): void;
68
68
  /** Sends a click on a rule's banner, with the query it showed for. */
@@ -67,15 +67,17 @@ export class SearchStore {
67
67
  get settings() { return this.config; }
68
68
  /** Opens the connection to the API before the first search needs it (the client's warm). */
69
69
  warm() { this.client.warm(); }
70
- /** Sends a click on a result: its place in the results, from 1, and the query they're for. A related
70
+ /** Sends a click on a result: its place in the results, from 1, and the query and filters they're for. A related
71
71
  * result's click says so (list "related"), with its place among them. */
72
72
  click(objectID) {
73
73
  const results = this.snapshot.results;
74
74
  const index = results ? results.hits.findIndex((hit) => hit.id === objectID) : -1;
75
75
  const related = index < 0 && results ? (results.response.related?.hits ?? []).findIndex((hit) => hit.id === objectID) : -1;
76
+ const filters = related < 0 ? results?.request.filters : undefined;
76
77
  this.client.events.click(objectID, { query: results?.request.q ?? "",
77
78
  ...(index >= 0 ? { position: (results.request.offset ?? 0) + index + 1 } : {}),
78
- ...(related >= 0 ? { position: related + 1, list: "related" } : {}) });
79
+ ...(related >= 0 ? { position: related + 1, list: "related" } : {}),
80
+ ...(filters && Object.keys(filters).length ? { filters } : {}) });
79
81
  }
80
82
  /** Sends a click on a rule's banner, with the query it showed for. */
81
83
  bannerClick(banner) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@findlane/browser",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "Findlane browser SDK: fast, typo-tolerant public search from the browser with an index's public ID, plus React hooks and components.",
5
5
  "keywords": ["findlane", "search", "full-text search", "typo tolerance", "instant search", "ecommerce search", "browser", "react", "autocomplete"],
6
6
  "license": "MIT",