@findlane/browser 0.23.0 → 0.24.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/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?: {
package/dist/index.js CHANGED
@@ -52,12 +52,52 @@ 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;
58
97
  /** The visitor and visit IDs of a public ID, kept on the device: the visitor's in localStorage, made
59
98
  * 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. */
99
+ * after 30 minutes without events, with how the visit's search was opened from outside the site, if it was.
100
+ * Storage that can't be used (a sandboxed frame's) means no IDs. */
61
101
  function deviceIds(publicId) {
62
102
  const keys = { visitor: `findlane:visitor:${publicId}`, visit: `findlane:visit:${publicId}` };
63
103
  // 16 random bytes in base64url: letters, digits, - and _, as the API takes IDs.
@@ -65,24 +105,39 @@ function deviceIds(publicId) {
65
105
  .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
66
106
  const read = (storage, key) => {
67
107
  const value = JSON.parse(storage.getItem(key) ?? "null");
68
- return typeof value?.id == "string" && typeof value.at == "number" ? value : null;
108
+ return typeof value?.id == "string" && typeof value.at == "number"
109
+ ? { id: value.id, at: value.at, ...(landed(value.landing) ? { landing: value.landing } : {}) } : null;
110
+ };
111
+ const live = (now) => {
112
+ const visit = read(sessionStorage, keys.visit);
113
+ return visit && now - visit.at <= 30 * 60_000 ? visit : null;
69
114
  };
70
115
  return {
71
- /** The IDs for a request now, made when there are none or they're old. */
72
- use(now = Date.now()) {
116
+ /** The IDs for a request now, made when there are none or they're old; the visit keeps `landing`, or its own. */
117
+ use(now = Date.now(), landing) {
73
118
  try {
74
119
  let visitor = read(localStorage, keys.visitor);
75
120
  if (!visitor || now - visitor.at > 395 * day)
76
121
  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 }));
122
+ const visit = live(now);
123
+ const visitId = visit?.id ?? random();
124
+ const kept = landing ?? visit?.landing;
125
+ sessionStorage.setItem(keys.visit, JSON.stringify({ id: visitId, at: now, ...(kept ? { landing: kept } : {}) }));
80
126
  return { visitorId: visitor.id, visitId };
81
127
  }
82
128
  catch {
83
129
  return null;
84
130
  }
85
131
  },
132
+ /** How the live visit's search was opened from outside the site, if it was. */
133
+ landing(now = Date.now()) {
134
+ try {
135
+ return live(now)?.landing ?? null;
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ },
86
141
  /** Deletes them from the device, and returns those there were. */
87
142
  clear() {
88
143
  try {
@@ -103,6 +158,16 @@ function eventSender(url, fetcher, mode, ids) {
103
158
  let timer;
104
159
  let listening = false;
105
160
  let lastView = { objectID: "", at: 0 };
161
+ // The page's search when the page was opened from outside the site (landed).
162
+ let page = null;
163
+ const landingFor = (query) => {
164
+ if (!query)
165
+ return null;
166
+ if (page && sameQuery(page.q, query))
167
+ return page;
168
+ const visit = ids?.landing();
169
+ return visit && sameQuery(visit.q, query) ? visit : null;
170
+ };
106
171
  const send = (body) => {
107
172
  // A beacon outlives the page; text/plain needs no CORS preflight.
108
173
  if (fetcher || !(typeof navigator == "object" && navigator.sendBeacon?.(url, new Blob([body], { type: "text/plain" }))))
@@ -113,7 +178,7 @@ function eventSender(url, fetcher, mode, ids) {
113
178
  clearTimeout(timer);
114
179
  timer = undefined;
115
180
  while (allowed && queue.length)
116
- send(JSON.stringify({ ...ids?.use(), events: queue.splice(0, 100) }));
181
+ send(JSON.stringify({ ...ids?.use(Date.now(), page), events: queue.splice(0, 100) }));
117
182
  };
118
183
  const add = (event) => {
119
184
  if (allowed === false)
@@ -135,7 +200,15 @@ function eventSender(url, fetcher, mode, ids) {
135
200
  lastView = { objectID, at: now };
136
201
  add({ type: "view", objectID });
137
202
  },
138
- click: (objectID, details) => add({ type: "click", objectID, ...details }),
203
+ click(objectID, details) {
204
+ const landing = details?.list || details?.landing ? null : landingFor(details?.query);
205
+ add({ type: "click", objectID, ...details, ...(landing ? { landing: landing.kind, ...(landing.network ? { network: landing.network } : {}) } : {}) });
206
+ },
207
+ landed(q) {
208
+ const landing = q.trim() && typeof location == "object" && typeof document == "object"
209
+ ? landingOf(location.search, document.referrer, location.hostname) : null;
210
+ page = landing ? { ...landing, q: q.trim() } : null;
211
+ },
139
212
  suggestion: (query, details) => add({ type: "suggestion", query, ...details }),
140
213
  bannerClick: (rule, details) => add({ type: "bannerClick", rule, ...details }),
141
214
  addToCart: (items, options) => add({ type: "addToCart", items, ...options }),
@@ -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.24.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",