@findlane/browser 0.24.0 → 0.26.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 +2 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +78 -9
- package/dist/react/client.d.ts +4 -3
- package/dist/react/client.js +12 -4
- package/package.json +1 -1
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
|
@@ -153,6 +153,12 @@ export type SearchResponse<T> = {
|
|
|
153
153
|
};
|
|
154
154
|
/** With `subindexes`: each subindex's results by name, or its error (0.22.0). */
|
|
155
155
|
subindexes?: Record<string, SearchResponse<Record<string, unknown>> | SubindexError>;
|
|
156
|
+
/** While the index runs an A/B test of its settings (0.26.0): the test and the shopper's group, which this
|
|
157
|
+
* client's events carry so the dashboard can compare the groups. Nothing to do with it. */
|
|
158
|
+
abTest?: {
|
|
159
|
+
id: string;
|
|
160
|
+
variant: "a" | "b";
|
|
161
|
+
};
|
|
156
162
|
};
|
|
157
163
|
/** One search of a multi-index search (multiSearch): its index's public ID, the client's own when left out. */
|
|
158
164
|
export type MultiSearchQuery = SearchRequest & {
|
|
@@ -386,18 +392,30 @@ export type BrowserClientOptions = {
|
|
|
386
392
|
* banner covers analytics, or your shoppers don't need one; with `events: "afterConsent"` the IDs
|
|
387
393
|
* wait for consent as events do. */
|
|
388
394
|
visitorIds?: boolean;
|
|
395
|
+
/** A signed key (0.25.0) from your server (the server SDK's `signSearchKey`), for a person who's logged in:
|
|
396
|
+
* searches and did-you-mean suggestions send it, and its restrictions replace the index's public policy and
|
|
397
|
+
* allowed sites. Or a function that fetches one: called for the first search, again shortly before the key
|
|
398
|
+
* expires, and once more if the API says it has. Make a new client when the person changes. */
|
|
399
|
+
signedKey?: string | (() => string | Promise<string>);
|
|
389
400
|
};
|
|
390
401
|
export declare class SearchBrowserClient {
|
|
391
402
|
private readonly url;
|
|
392
403
|
private readonly origin;
|
|
393
404
|
private readonly publicId;
|
|
394
405
|
private readonly fetcher;
|
|
406
|
+
private readonly signer?;
|
|
407
|
+
/** The signed key a function gave, and when it expires. */
|
|
408
|
+
private signed;
|
|
395
409
|
/** Views, clicks, add-to-carts and orders, for the index's Events page and Bought together. */
|
|
396
410
|
readonly events: BrowserEvents;
|
|
397
411
|
/** The shopper's recent searches, kept in this browser only. */
|
|
398
412
|
readonly recentSearches: RecentSearches;
|
|
399
413
|
private popular;
|
|
414
|
+
private test;
|
|
400
415
|
constructor(options: BrowserClientOptions);
|
|
416
|
+
/** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
|
|
417
|
+
* expires, or at once when `fresh`. */
|
|
418
|
+
private signedKey;
|
|
401
419
|
private post;
|
|
402
420
|
private get;
|
|
403
421
|
/** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
|
package/dist/index.js
CHANGED
|
@@ -94,6 +94,16 @@ const landed = (value) => !!value && typeof value == "object" && typeof value.q
|
|
|
94
94
|
/** The hosted Findlane API, used unless `baseUrl` says otherwise. */
|
|
95
95
|
export const defaultBaseUrl = "https://api.findlane.dev";
|
|
96
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
|
+
}
|
|
97
107
|
/** The visitor and visit IDs of a public ID, kept on the device: the visitor's in localStorage, made
|
|
98
108
|
* anew 13 months after it was made (use doesn't extend it); the visit's in sessionStorage, made anew
|
|
99
109
|
* after 30 minutes without events, with how the visit's search was opened from outside the site, if it was.
|
|
@@ -152,7 +162,34 @@ function deviceIds(publicId) {
|
|
|
152
162
|
},
|
|
153
163
|
};
|
|
154
164
|
}
|
|
155
|
-
|
|
165
|
+
/** The shopper's A/B test label (`abt_…:a`), from the last search answer that had one, kept for the visit so events
|
|
166
|
+
* on later pages carry it too. */
|
|
167
|
+
function testLabel(publicId) {
|
|
168
|
+
const key = `findlane:abtest:${publicId}`;
|
|
169
|
+
let current = null;
|
|
170
|
+
try {
|
|
171
|
+
current = sessionStorage.getItem(key);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
// No storage: kept in memory only.
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
get: () => current,
|
|
178
|
+
set(test) {
|
|
179
|
+
const label = `${test.id}:${test.variant}`;
|
|
180
|
+
if (label === current)
|
|
181
|
+
return;
|
|
182
|
+
current = label;
|
|
183
|
+
try {
|
|
184
|
+
sessionStorage.setItem(key, label);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// No storage: kept in memory only.
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function eventSender(url, fetcher, mode, ids, test) {
|
|
156
193
|
let queue = [];
|
|
157
194
|
let allowed = mode === "afterConsent" ? undefined : mode;
|
|
158
195
|
let timer;
|
|
@@ -177,8 +214,10 @@ function eventSender(url, fetcher, mode, ids) {
|
|
|
177
214
|
const flush = () => {
|
|
178
215
|
clearTimeout(timer);
|
|
179
216
|
timer = undefined;
|
|
180
|
-
while (allowed && queue.length)
|
|
181
|
-
|
|
217
|
+
while (allowed && queue.length) {
|
|
218
|
+
const label = test?.get();
|
|
219
|
+
send(JSON.stringify({ ...ids?.use(Date.now(), page), ...(label ? { abTest: label } : {}), events: queue.splice(0, 100) }));
|
|
220
|
+
}
|
|
182
221
|
};
|
|
183
222
|
const add = (event) => {
|
|
184
223
|
if (allowed === false)
|
|
@@ -237,11 +276,15 @@ export class SearchBrowserClient {
|
|
|
237
276
|
origin;
|
|
238
277
|
publicId;
|
|
239
278
|
fetcher;
|
|
279
|
+
signer;
|
|
280
|
+
/** The signed key a function gave, and when it expires. */
|
|
281
|
+
signed = null;
|
|
240
282
|
/** Views, clicks, add-to-carts and orders, for the index's Events page and Bought together. */
|
|
241
283
|
events;
|
|
242
284
|
/** The shopper's recent searches, kept in this browser only. */
|
|
243
285
|
recentSearches;
|
|
244
286
|
popular = new Map();
|
|
287
|
+
test;
|
|
245
288
|
constructor(options) {
|
|
246
289
|
if (!/^pub_[a-f0-9]{32}$/.test(options.publicId))
|
|
247
290
|
throw new Error("A valid public index ID (pub_…) is required");
|
|
@@ -249,21 +292,44 @@ export class SearchBrowserClient {
|
|
|
249
292
|
this.url = `${(options.baseUrl ?? defaultBaseUrl).replace(/\/$/, "")}/api/public/indexes/${options.publicId}`;
|
|
250
293
|
this.origin = new URL(this.url).origin;
|
|
251
294
|
this.fetcher = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
252
|
-
this.
|
|
295
|
+
this.signer = options.signedKey;
|
|
296
|
+
this.test = testLabel(options.publicId);
|
|
297
|
+
this.events = eventSender(options.eventsUrl ?? `${this.url}/events`, options.fetch, options.events ?? true, options.visitorIds ? deviceIds(options.publicId) : null, this.test);
|
|
253
298
|
this.recentSearches = new RecentSearches(options.publicId);
|
|
254
299
|
}
|
|
255
|
-
|
|
300
|
+
/** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
|
|
301
|
+
* expires, or at once when `fresh`. */
|
|
302
|
+
signedKey(fresh) {
|
|
303
|
+
const signer = this.signer;
|
|
304
|
+
if (signer === undefined)
|
|
305
|
+
return undefined;
|
|
306
|
+
if (typeof signer == "string")
|
|
307
|
+
return Promise.resolve(signer);
|
|
308
|
+
if (fresh || !this.signed || Date.now() / 1000 > this.signed.until - 30) {
|
|
309
|
+
const entry = { key: Promise.resolve().then(signer), until: Infinity };
|
|
310
|
+
entry.key.then((key) => { entry.until = signedKeyExpiry(key); }, () => { if (this.signed === entry)
|
|
311
|
+
this.signed = null; });
|
|
312
|
+
this.signed = entry;
|
|
313
|
+
}
|
|
314
|
+
return this.signed.key;
|
|
315
|
+
}
|
|
316
|
+
async post(operation, request, signal, renewed = false) {
|
|
317
|
+
// A signed key goes in the body, so the request needs no preflight.
|
|
318
|
+
const signing = operation === "search" || operation === "suggest" ? this.signedKey(renewed) : undefined;
|
|
256
319
|
const response = await this.fetcher(`${this.url}/${operation}`, {
|
|
257
320
|
method: "POST",
|
|
258
321
|
// JSON as text/plain: browsers send it without asking the API first (a CORS preflight), which
|
|
259
322
|
// saves a round trip.
|
|
260
323
|
headers: { "content-type": "text/plain" },
|
|
261
|
-
body: JSON.stringify(request),
|
|
324
|
+
body: JSON.stringify(signing ? { ...request, signedKey: await signing } : request),
|
|
262
325
|
signal,
|
|
263
326
|
});
|
|
264
327
|
const data = await response.json();
|
|
265
|
-
if (!response.ok)
|
|
328
|
+
if (!response.ok) {
|
|
329
|
+
if (signing && !renewed && response.status === 401 && data.expired && typeof this.signer == "function")
|
|
330
|
+
return this.post(operation, request, signal, true);
|
|
266
331
|
throw new FindlaneError(response.status, data.error ?? `HTTP ${response.status}`);
|
|
332
|
+
}
|
|
267
333
|
return data;
|
|
268
334
|
}
|
|
269
335
|
// Lists are read with GET, which browsers send without a preflight and may keep for 30 seconds.
|
|
@@ -288,8 +354,11 @@ export class SearchBrowserClient {
|
|
|
288
354
|
link.crossOrigin = "anonymous";
|
|
289
355
|
document.head.append(link);
|
|
290
356
|
}
|
|
291
|
-
search(request, options = {}) {
|
|
292
|
-
|
|
357
|
+
async search(request, options = {}) {
|
|
358
|
+
const response = await this.post("search", request, options.signal);
|
|
359
|
+
if (response.abTest)
|
|
360
|
+
this.test.set(response.abTest);
|
|
361
|
+
return response;
|
|
293
362
|
}
|
|
294
363
|
/** Several indexes searched in one request, such as products and a blog (0.22.0): up to 10 searches, each
|
|
295
364
|
* naming its index's public ID (this client's when left out), whose allowed sites must include the page's.
|
package/dist/react/client.d.ts
CHANGED
|
@@ -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
|
-
|
|
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;
|
package/dist/react/client.js
CHANGED
|
@@ -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
|
-
|
|
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)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@findlane/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.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",
|