@findlane/browser 0.27.1 → 0.28.1

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/images.d.ts CHANGED
@@ -8,6 +8,30 @@ export declare function imageWidth(width: number): 48 | 64 | 96 | 128 | 160 | 19
8
8
  export declare const imageHostsHeader = "x-findlane-images";
9
9
  /** The hosts an `x-findlane-images` header names; empty without one. */
10
10
  export declare function imageHostsOf(header: string | null | undefined): Set<string>;
11
+ /** The header naming where the index's optimized images load from (0.28.0), such as https://images.findlane.dev.
12
+ * Without it they load from the API's own origin. */
13
+ export declare const imageOriginHeader = "x-findlane-image-origin";
14
+ /** The origin an `x-findlane-image-origin` header names, or null for none or one that isn't an http(s) origin. */
15
+ export declare function imageOriginOf(header: string | null | undefined): string | null;
16
+ /** Where an index's images loaded from on an earlier page, kept in this browser (localStorage), so the next page
17
+ * can open that connection before its first answer says; null when unknown or without storage. */
18
+ export declare function rememberedImageOrigin(id: string): string | null;
19
+ /** What an index's last answer in this browser said about its images (0.28.1): the hosts that may be resized and
20
+ * where from, so a page showing results it kept (a reload, Back) resizes them before its first search; null when
21
+ * unknown, off, or without storage. */
22
+ export declare function rememberedImages(id: string): {
23
+ hosts: Set<string>;
24
+ origin: string | null;
25
+ } | null;
26
+ /** Keeps what an answer said about an index's images for later pages (0.28.1), or forgets it once it has none. The
27
+ * 0.28.0 key with the origin alone is kept in step, for the widget. */
28
+ export declare function rememberImages(id: string, hosts: Set<string>, origin: string | null): void;
29
+ /** Keeps where an index's images load from for later pages, or forgets it (null) once the index has none. */
30
+ export declare function rememberImageOrigin(id: string, origin: string | null): void;
31
+ /** Opens a connection to `origin` before a request needs it, as a preconnect hint in the page would: once per page,
32
+ * nothing outside a browser. Without credentials, as searches and optimized images are sent, so they use it. */
33
+ export declare function preconnect(origin: string): void;
11
34
  /** An image's optimized address: `src` resized to `width` (rounded up to a made width) by the image Worker
12
- * at `apiOrigin`, or null when `src` isn't an http(s) address on one of `hosts`. */
13
- export declare function optimizedImageUrl(apiOrigin: string, publicId: string, hosts: Set<string>, src: unknown, width: number): string | null;
35
+ * at `origin` (the one the API names, else the API's own), or null when `src` isn't an http(s) address on one of
36
+ * `hosts`. */
37
+ export declare function optimizedImageUrl(origin: string, publicId: string, hosts: Set<string>, src: unknown, width: number): string | null;
package/dist/images.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Optimized images (0.27.0): an index's record images, resized and re-encoded at the edge
2
2
  // (workers/images), from the hosts its owner allows. Shared by the client, the React Image component,
3
- // the search widget and the image Worker, so all of them ask for the same few widths.
3
+ // the search widget and the image Worker, so all of them ask for the same few widths. Since 0.28.0 they load
4
+ // from the address the API names (images.findlane.dev), whose connection is opened ahead of need.
4
5
  /** The widths the image Worker makes, in pixels. Any other width is rounded up to one of these, so a
5
6
  * page's images share cached copies, and asking for odd widths can't make endless new ones. */
6
7
  export const imageWidths = [48, 64, 96, 128, 160, 192, 256, 320, 384, 480, 640, 768, 960, 1280, 1600];
@@ -15,9 +16,90 @@ export const imageHostsHeader = "x-findlane-images";
15
16
  export function imageHostsOf(header) {
16
17
  return new Set((header ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(Boolean));
17
18
  }
19
+ /** The header naming where the index's optimized images load from (0.28.0), such as https://images.findlane.dev.
20
+ * Without it they load from the API's own origin. */
21
+ export const imageOriginHeader = "x-findlane-image-origin";
22
+ /** The origin an `x-findlane-image-origin` header names, or null for none or one that isn't an http(s) origin. */
23
+ export function imageOriginOf(header) {
24
+ if (!header)
25
+ return null;
26
+ try {
27
+ const url = new URL(header.trim());
28
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ const originKey = (id) => `findlane:image-origin:${id}`;
35
+ const imagesKey = (id) => `findlane:images:${id}`;
36
+ /** Where an index's images loaded from on an earlier page, kept in this browser (localStorage), so the next page
37
+ * can open that connection before its first answer says; null when unknown or without storage. */
38
+ export function rememberedImageOrigin(id) {
39
+ try {
40
+ return imageOriginOf(localStorage.getItem(originKey(id)));
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ /** What an index's last answer in this browser said about its images (0.28.1): the hosts that may be resized and
47
+ * where from, so a page showing results it kept (a reload, Back) resizes them before its first search; null when
48
+ * unknown, off, or without storage. */
49
+ export function rememberedImages(id) {
50
+ try {
51
+ const kept = JSON.parse(localStorage.getItem(imagesKey(id)) ?? "null");
52
+ const hosts = Array.isArray(kept?.hosts) ? imageHostsOf(kept.hosts.filter((host) => typeof host === "string").join(",")) : new Set();
53
+ return hosts.size ? { hosts, origin: imageOriginOf(typeof kept?.origin === "string" ? kept.origin : null) } : null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ /** Keeps what an answer said about an index's images for later pages (0.28.1), or forgets it once it has none. The
60
+ * 0.28.0 key with the origin alone is kept in step, for the widget. */
61
+ export function rememberImages(id, hosts, origin) {
62
+ try {
63
+ if (hosts.size)
64
+ localStorage.setItem(imagesKey(id), JSON.stringify({ hosts: [...hosts], origin }));
65
+ else
66
+ localStorage.removeItem(imagesKey(id));
67
+ }
68
+ catch {
69
+ // Storage that can't be used: later pages learn them from their first answer.
70
+ }
71
+ rememberImageOrigin(id, hosts.size ? origin : null);
72
+ }
73
+ /** Keeps where an index's images load from for later pages, or forgets it (null) once the index has none. */
74
+ export function rememberImageOrigin(id, origin) {
75
+ try {
76
+ if (origin)
77
+ localStorage.setItem(originKey(id), origin);
78
+ else
79
+ localStorage.removeItem(originKey(id));
80
+ }
81
+ catch {
82
+ // Storage that can't be used (a private window, a sandboxed frame): the next page opens it when it learns it.
83
+ }
84
+ }
85
+ /** Origins this page has opened a connection to ahead of need. */
86
+ const opened = new Set();
87
+ /** Opens a connection to `origin` before a request needs it, as a preconnect hint in the page would: once per page,
88
+ * nothing outside a browser. Without credentials, as searches and optimized images are sent, so they use it. */
89
+ export function preconnect(origin) {
90
+ if (typeof document === "undefined" || opened.has(origin))
91
+ return;
92
+ opened.add(origin);
93
+ const link = document.createElement("link");
94
+ link.rel = "preconnect";
95
+ link.href = origin;
96
+ link.crossOrigin = "anonymous";
97
+ document.head.append(link);
98
+ }
18
99
  /** An image's optimized address: `src` resized to `width` (rounded up to a made width) by the image Worker
19
- * at `apiOrigin`, or null when `src` isn't an http(s) address on one of `hosts`. */
20
- export function optimizedImageUrl(apiOrigin, publicId, hosts, src, width) {
100
+ * at `origin` (the one the API names, else the API's own), or null when `src` isn't an http(s) address on one of
101
+ * `hosts`. */
102
+ export function optimizedImageUrl(origin, publicId, hosts, src, width) {
21
103
  if (typeof src !== "string" || !hosts.size)
22
104
  return null;
23
105
  let url;
@@ -29,5 +111,5 @@ export function optimizedImageUrl(apiOrigin, publicId, hosts, src, width) {
29
111
  }
30
112
  if ((url.protocol !== "https:" && url.protocol !== "http:") || !hosts.has(url.hostname.toLowerCase()))
31
113
  return null;
32
- return `${apiOrigin}/img/${publicId}?url=${encodeURIComponent(src)}&w=${imageWidth(width)}`;
114
+ return `${origin}/img/${publicId}?url=${encodeURIComponent(src)}&w=${imageWidth(width)}`;
33
115
  }
package/dist/index.d.ts CHANGED
@@ -422,22 +422,36 @@ export declare class SearchBrowserClient {
422
422
  private test;
423
423
  /** The hosts the index's images may be loaded from resized, from the API's last answer (x-findlane-images). */
424
424
  private imageHosts;
425
+ /** Where they load from (x-findlane-image-origin, 0.28.0); the API's own origin without one. */
426
+ private imageOrigin;
427
+ /** What an earlier page's answers said about them in this browser (0.28.1), read once, used until this page's first
428
+ * answer; undefined until read. */
429
+ private knownImages;
430
+ /** Whether an answer has said, so what was remembered is no longer used. */
431
+ private answered;
425
432
  constructor(options: BrowserClientOptions);
426
433
  /** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
427
434
  * expires, or at once when `fresh`. */
428
435
  private signedKey;
429
436
  private post;
430
437
  private get;
431
- /** Each answer says which hosts the index's images may be loaded from resized; refusals say nothing. */
438
+ /** Each answer says which hosts the index's images may be loaded from resized, and where from (0.28.0); refusals
439
+ * say nothing. Both are kept for later pages (0.28.1), and the connection opened now, before the results' images ask. */
432
440
  private noteImages;
441
+ private remembered;
442
+ /** Opens the connection to where the index's images loaded from on an earlier page, with the first request or
443
+ * when a search box gets focus, so the results' first image doesn't wait for it. Nothing for an index without. */
444
+ private warmImages;
433
445
  /** Optimized images (0.27.0): a record image's address, resized to `width` pixels (rounded up to one of
434
- * `imageWidths`) and sent as WebP from the API's own address, when the index has optimized images on and the
435
- * image is on a host it allows; otherwise `src` as it is. Known from the first answer on, so build image
436
- * addresses from results, not before the first search. Load them with `crossorigin="anonymous"`, which
437
- * shares the connection searches use. React's `Image` does all of this. */
446
+ * `imageWidths`) and sent as WebP from the address the API names (images.findlane.dev since 0.28.0; the API's own
447
+ * before), when the index has optimized images on and the image is on a host it allows; otherwise `src` as it is.
448
+ * Known from the first answer on; since 0.28.1, before it too from what an earlier page's answers said in this
449
+ * browser, so results a page kept (a reload, Back) are resized. Load them with `crossorigin="anonymous"`, which uses
450
+ * the connection opened for them ahead of need. React's `Image` does all of this. */
438
451
  imageUrl(src: string, width: number): string;
439
452
  /** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
440
- * would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. */
453
+ * would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. Since 0.28.0 it
454
+ * also opens the one to where the index's images loaded from on an earlier page. */
441
455
  warm(): void;
442
456
  search<T = Record<string, unknown>>(request: SearchRequest, options?: {
443
457
  signal?: AbortSignal;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { imageHostsHeader, imageHostsOf, optimizedImageUrl } from "./images.js";
1
+ import { imageHostsHeader, imageHostsOf, imageOriginHeader, imageOriginOf, optimizedImageUrl, preconnect, rememberedImages, rememberImages } from "./images.js";
2
2
  export { imageWidth, imageWidths } from "./images.js";
3
3
  export { placeholderCss, placeholderUrl, revealCss } from "./placeholder.js";
4
4
  /** A query suggestion's text in parts: what was typed (`typed: true`) and the rest. */
@@ -272,8 +272,6 @@ function eventSender(url, fetcher, mode, ids, test) {
272
272
  flush,
273
273
  };
274
274
  }
275
- /** Origins this page has opened a connection to ahead of a search (warm). */
276
- const warmed = new Set();
277
275
  export class SearchBrowserClient {
278
276
  url;
279
277
  origin;
@@ -290,6 +288,13 @@ export class SearchBrowserClient {
290
288
  test;
291
289
  /** The hosts the index's images may be loaded from resized, from the API's last answer (x-findlane-images). */
292
290
  imageHosts = new Set();
291
+ /** Where they load from (x-findlane-image-origin, 0.28.0); the API's own origin without one. */
292
+ imageOrigin = null;
293
+ /** What an earlier page's answers said about them in this browser (0.28.1), read once, used until this page's first
294
+ * answer; undefined until read. */
295
+ knownImages;
296
+ /** Whether an answer has said, so what was remembered is no longer used. */
297
+ answered = false;
293
298
  constructor(options) {
294
299
  if (!/^pub_[a-f0-9]{32}$/.test(options.publicId))
295
300
  throw new Error("A valid public index ID (pub_…) is required");
@@ -321,6 +326,7 @@ export class SearchBrowserClient {
321
326
  async post(operation, request, signal, renewed = false) {
322
327
  // A signed key goes in the body, so the request needs no preflight.
323
328
  const signing = operation === "search" || operation === "suggest" ? this.signedKey(renewed) : undefined;
329
+ this.warmImages();
324
330
  const response = await this.fetcher(`${this.url}/${operation}`, {
325
331
  method: "POST",
326
332
  // JSON as text/plain: browsers send it without asking the API first (a CORS preflight), which
@@ -341,6 +347,7 @@ export class SearchBrowserClient {
341
347
  // Lists are read with GET, which browsers send without a preflight and may keep for 30 seconds.
342
348
  async get(path, params, signal) {
343
349
  const query = new URLSearchParams(params).toString();
350
+ this.warmImages();
344
351
  const response = await this.fetcher(`${this.url}/${path}${query ? `?${query}` : ""}`, { method: "GET", signal });
345
352
  this.noteImages(response);
346
353
  const data = await response.json();
@@ -348,31 +355,52 @@ export class SearchBrowserClient {
348
355
  throw new FindlaneError(response.status, data.error ?? `HTTP ${response.status}`);
349
356
  return data;
350
357
  }
351
- /** Each answer says which hosts the index's images may be loaded from resized; refusals say nothing. */
358
+ /** Each answer says which hosts the index's images may be loaded from resized, and where from (0.28.0); refusals
359
+ * say nothing. Both are kept for later pages (0.28.1), and the connection opened now, before the results' images ask. */
352
360
  noteImages(response) {
353
- if (response.ok)
354
- this.imageHosts = imageHostsOf(response.headers?.get(imageHostsHeader));
361
+ if (!response.ok)
362
+ return;
363
+ this.answered = true;
364
+ this.imageHosts = imageHostsOf(response.headers?.get(imageHostsHeader));
365
+ this.imageOrigin = this.imageHosts.size ? imageOriginOf(response.headers?.get(imageOriginHeader)) : null;
366
+ if (this.imageOrigin)
367
+ preconnect(this.imageOrigin);
368
+ const known = this.remembered();
369
+ const same = known ? known.origin === this.imageOrigin && known.hosts.size === this.imageHosts.size &&
370
+ [...this.imageHosts].every((host) => known.hosts.has(host)) : !this.imageHosts.size;
371
+ if (!same) {
372
+ rememberImages(this.publicId, this.imageHosts, this.imageOrigin);
373
+ this.knownImages = this.imageHosts.size ? { hosts: new Set(this.imageHosts), origin: this.imageOrigin } : null;
374
+ }
375
+ }
376
+ remembered() {
377
+ if (this.knownImages === undefined)
378
+ this.knownImages = rememberedImages(this.publicId);
379
+ return this.knownImages;
380
+ }
381
+ /** Opens the connection to where the index's images loaded from on an earlier page, with the first request or
382
+ * when a search box gets focus, so the results' first image doesn't wait for it. Nothing for an index without. */
383
+ warmImages() {
384
+ const origin = this.remembered()?.origin;
385
+ if (origin)
386
+ preconnect(origin);
355
387
  }
356
388
  /** Optimized images (0.27.0): a record image's address, resized to `width` pixels (rounded up to one of
357
- * `imageWidths`) and sent as WebP from the API's own address, when the index has optimized images on and the
358
- * image is on a host it allows; otherwise `src` as it is. Known from the first answer on, so build image
359
- * addresses from results, not before the first search. Load them with `crossorigin="anonymous"`, which
360
- * shares the connection searches use. React's `Image` does all of this. */
389
+ * `imageWidths`) and sent as WebP from the address the API names (images.findlane.dev since 0.28.0; the API's own
390
+ * before), when the index has optimized images on and the image is on a host it allows; otherwise `src` as it is.
391
+ * Known from the first answer on; since 0.28.1, before it too from what an earlier page's answers said in this
392
+ * browser, so results a page kept (a reload, Back) are resized. Load them with `crossorigin="anonymous"`, which uses
393
+ * the connection opened for them ahead of need. React's `Image` does all of this. */
361
394
  imageUrl(src, width) {
362
- return optimizedImageUrl(this.origin, this.publicId, this.imageHosts, src, width) ?? src;
395
+ const known = this.answered ? null : this.remembered();
396
+ return optimizedImageUrl((known ? known.origin : this.imageOrigin) ?? this.origin, this.publicId, known?.hosts ?? this.imageHosts, src, width) ?? src;
363
397
  }
364
398
  /** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
365
- * would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. */
399
+ * would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. Since 0.28.0 it
400
+ * also opens the one to where the index's images loaded from on an earlier page. */
366
401
  warm() {
367
- if (typeof document === "undefined" || warmed.has(this.origin))
368
- return;
369
- warmed.add(this.origin);
370
- const link = document.createElement("link");
371
- link.rel = "preconnect";
372
- link.href = this.origin;
373
- // Searches are sent without credentials, so they use the connection a crossorigin hint opens.
374
- link.crossOrigin = "anonymous";
375
- document.head.append(link);
402
+ preconnect(this.origin);
403
+ this.warmImages();
376
404
  }
377
405
  async search(request, options = {}) {
378
406
  const response = await this.post("search", request, options.signal);
@@ -38,7 +38,7 @@ export function Image({ src, width, client: given, placeholder, alt = "", loadin
38
38
  const waiting = preview !== null && loaded !== one;
39
39
  const ours = waiting ? placeholderStyle(preview) : revealing ? revealStyle : undefined;
40
40
  return (_jsx("img", { ...rest, src: one, srcSet: two !== one ? `${one} 1x, ${two} 2x` : undefined, width: width, alt: alt, loading: loading, decoding: decoding, style: ours ? { ...ours, ...style } : style,
41
- // Searches are sent without credentials, so an image sent without them comes over the same connection.
41
+ // Without credentials, as the client opened the image host's connection ahead of need, so the image uses it.
42
42
  crossOrigin: optimized ? "anonymous" : undefined,
43
43
  // An image the browser had already shows at once, without its placeholder.
44
44
  ref: waiting ? (node) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@findlane/browser",
3
- "version": "0.27.1",
3
+ "version": "0.28.1",
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",