system HF Staff commited on
Commit
f4e34cf
ยท
verified ยท
1 Parent(s): d86560b

Sync from felladrin/MiniSearch@a3854eb (part 2)

Browse files
searxng-settings.yml CHANGED
@@ -4,6 +4,7 @@
4
  # file only declares what MiniSearch overrides:
5
  # - a placeholder secret_key
6
  # - JSON output format (consumed by server/webSearchService.ts)
 
7
  #
8
  # Docs: https://docs.searxng.org/admin/settings/settings_use_default_settings.html
9
  use_default_settings: true
@@ -15,3 +16,12 @@ server:
15
  search:
16
  formats:
17
  - json
 
 
 
 
 
 
 
 
 
 
4
  # file only declares what MiniSearch overrides:
5
  # - a placeholder secret_key
6
  # - JSON output format (consumed by server/webSearchService.ts)
7
+ # - Mojeek switched on for text search
8
  #
9
  # Docs: https://docs.searxng.org/admin/settings/settings_use_default_settings.html
10
  use_default_settings: true
 
16
  search:
17
  formats:
18
  - json
19
+
20
+ engines:
21
+ # Upstream ships Mojeek `inactive: true`, which only `inactive: false` undoes
22
+ # (`disabled: false` leaves it unloaded). It runs its own index, so its
23
+ # results are mostly ones the other engines do not return, and it keeps
24
+ # answering where DuckDuckGo shows a CAPTCHA. See docs/configuration.md,
25
+ # "Tuning the Search Engines".
26
+ - name: mojeek
27
+ inactive: false
server/fallbackSearchService.test.ts CHANGED
@@ -880,6 +880,27 @@ describe("mapping a result", () => {
880
  expect(LONG_EXCERPT[kept.length]).toBe(" ");
881
  });
882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883
  it("leaves a snippet that fits untouched", async () => {
884
  expect(EXCERPT.length).toBeLessThanOrEqual(400);
885
 
 
880
  expect(LONG_EXCERPT[kept.length]).toBe(" ");
881
  });
882
 
883
+ // The page read for this result would go looking for the text the snippet
884
+ // cut, so the whole of it is kept for `/page-content`, under the query.
885
+ it("keeps the whole cleaned excerpt text for the page read", async () => {
886
+ const results = await run([
887
+ {
888
+ url: "https://example.com/long",
889
+ title: "Long",
890
+ excerpts: ["Skip to main content", `## ${LONG_EXCERPT}`, EXCERPT],
891
+ },
892
+ ]);
893
+ const { recallSearchExcerpts } = await import("./searchExcerptStore");
894
+
895
+ expect(results[0][1].length).toBeLessThanOrEqual(400);
896
+ expect(recallSearchExcerpts(QUERY, "https://example.com/long")).toBe(
897
+ `${LONG_EXCERPT}\n\n${EXCERPT}`,
898
+ );
899
+ expect(
900
+ recallSearchExcerpts("another query", "https://example.com/long"),
901
+ ).toBeUndefined();
902
+ });
903
+
904
  it("leaves a snippet that fits untouched", async () => {
905
  expect(EXCERPT.length).toBeLessThanOrEqual(400);
906
 
server/fallbackSearchService.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { randomUUID } from "node:crypto";
2
  import { basename } from "node:path";
3
  import debug from "debug";
 
4
  import { isOpenableUrl } from "./utils/openableUrl.ts";
5
 
6
  const fileName = basename(import.meta.url);
@@ -68,6 +69,8 @@ type ProviderName = "parallel" | "youcom";
68
  interface MappedResults {
69
  results: TextualResult[];
70
  received: number;
 
 
71
  }
72
 
73
  interface FallbackProvider {
@@ -307,7 +310,7 @@ export async function fetchFallbackTextResults(
307
  const attemptMs = Math.ceil(remainingMs / eligibleCount);
308
 
309
  try {
310
- const results = await searchWithProvider(
311
  provider,
312
  query,
313
  limit,
@@ -317,6 +320,9 @@ export async function fetchFallbackTextResults(
317
  if (results.length > 0) {
318
  countFor(provider.name).served++;
319
  printMessage(`Fallback search served by ${provider.name}.`);
 
 
 
320
  return results;
321
  }
322
  countFor(provider.name).empty++;
@@ -414,7 +420,7 @@ async function searchWithProvider(
414
  query: string,
415
  limit: number,
416
  signal: AbortSignal,
417
- ): Promise<TextualResult[]> {
418
  const apiKey = (process.env[provider.apiKeyVariable] ?? "").trim();
419
  const endpointUrl = provider.endpointUrl(apiKey);
420
 
@@ -499,11 +505,11 @@ async function searchWithProvider(
499
  }
500
 
501
  const document = await readSearchDocument<object>(callResponse, 2);
502
- const { results, received } = provider.mapResults(document, limit);
503
  printMessage(
504
- `Fallback search usable text results from ${provider.name}: ${results.length} of ${received}.`,
505
  );
506
- return results;
507
  }
508
 
509
  /**
@@ -618,12 +624,16 @@ function mapParallelResults(
618
  );
619
  }
620
 
621
- return {
622
- results: mapEntries(document.results, limit, (result) =>
623
- buildSnippet(result.excerpts),
624
- ),
625
- received: document.results.length,
626
- };
 
 
 
 
627
  }
628
 
629
  function mapYoucomResults(
@@ -697,18 +707,26 @@ function buildYoucomSnippet(result: YoucomWebResult): string {
697
  }
698
 
699
  function buildSnippet(excerpts: string[] | undefined): string {
 
 
 
 
 
 
 
 
700
  if (!Array.isArray(excerpts) || excerpts.length === 0) return "";
701
 
702
- const snippet = excerpts
703
  .join("\n")
704
  .split("\n")
705
  .map(stripMarkdown)
706
  .filter((line) => line.length >= MIN_SNIPPET_LINE_LENGTH)
707
- .join(" ")
708
- .replace(/\s+/g, " ")
709
- .trim();
710
 
711
- return truncateSnippet(snippet);
 
712
  }
713
 
714
  /**
 
1
  import { randomUUID } from "node:crypto";
2
  import { basename } from "node:path";
3
  import debug from "debug";
4
+ import { rememberSearchExcerpts } from "./searchExcerptStore.ts";
5
  import { isOpenableUrl } from "./utils/openableUrl.ts";
6
 
7
  const fileName = basename(import.meta.url);
 
69
  interface MappedResults {
70
  results: TextualResult[];
71
  received: number;
72
+ /** The provider's longer text per result URL, kept for `/page-content`. */
73
+ pageTexts?: Map<string, string>;
74
  }
75
 
76
  interface FallbackProvider {
 
310
  const attemptMs = Math.ceil(remainingMs / eligibleCount);
311
 
312
  try {
313
+ const { results, pageTexts } = await searchWithProvider(
314
  provider,
315
  query,
316
  limit,
 
320
  if (results.length > 0) {
321
  countFor(provider.name).served++;
322
  printMessage(`Fallback search served by ${provider.name}.`);
323
+ for (const [url, text] of pageTexts ?? []) {
324
+ rememberSearchExcerpts(query, url, text);
325
+ }
326
  return results;
327
  }
328
  countFor(provider.name).empty++;
 
420
  query: string,
421
  limit: number,
422
  signal: AbortSignal,
423
+ ): Promise<MappedResults> {
424
  const apiKey = (process.env[provider.apiKeyVariable] ?? "").trim();
425
  const endpointUrl = provider.endpointUrl(apiKey);
426
 
 
505
  }
506
 
507
  const document = await readSearchDocument<object>(callResponse, 2);
508
+ const mapped = provider.mapResults(document, limit);
509
  printMessage(
510
+ `Fallback search usable text results from ${provider.name}: ${mapped.results.length} of ${mapped.received}.`,
511
  );
512
+ return mapped;
513
  }
514
 
515
  /**
 
624
  );
625
  }
626
 
627
+ // The snippet keeps 400 characters of the excerpts; the rest is what the
628
+ // page read would have gone looking for, so it is kept for `/page-content`.
629
+ const pageTexts = new Map<string, string>();
630
+ const results = mapEntries(document.results, limit, (result) => {
631
+ const text = cleanExcerpts(result.excerpts);
632
+ if (text && typeof result.url === "string") pageTexts.set(result.url, text);
633
+ return toSnippet(text);
634
+ });
635
+
636
+ return { results, received: document.results.length, pageTexts };
637
  }
638
 
639
  function mapYoucomResults(
 
707
  }
708
 
709
  function buildSnippet(excerpts: string[] | undefined): string {
710
+ return toSnippet(cleanExcerpts(excerpts));
711
+ }
712
+
713
+ /**
714
+ * One kept line per paragraph, separated by blank lines, which is where
715
+ * `splitIntoPassages` cuts when the text is read as page content.
716
+ */
717
+ function cleanExcerpts(excerpts: string[] | undefined): string {
718
  if (!Array.isArray(excerpts) || excerpts.length === 0) return "";
719
 
720
+ return excerpts
721
  .join("\n")
722
  .split("\n")
723
  .map(stripMarkdown)
724
  .filter((line) => line.length >= MIN_SNIPPET_LINE_LENGTH)
725
+ .join("\n\n");
726
+ }
 
727
 
728
+ function toSnippet(text: string): string {
729
+ return truncateSnippet(text.replace(/\s+/g, " ").trim());
730
  }
731
 
732
  /**
server/pageContentService.test.ts CHANGED
@@ -32,6 +32,7 @@ import {
32
  PageReadHostBreaker,
33
  } from "./pageReadHostBreaker";
34
  import { getPageReadStats } from "./pageReadsSinceLastRestart";
 
35
 
36
  const fetchMock = vi.fn();
37
  vi.stubGlobal("fetch", fetchMock);
@@ -1093,6 +1094,55 @@ describe("host circuit breaker", () => {
1093
  });
1094
  });
1095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1096
  describe("fetchPageContents", () => {
1097
  it("identifies itself with the name, version and repository in package.json", async () => {
1098
  respondWithHtml(articlePage);
 
32
  PageReadHostBreaker,
33
  } from "./pageReadHostBreaker";
34
  import { getPageReadStats } from "./pageReadsSinceLastRestart";
35
+ import { rememberSearchExcerpts } from "./searchExcerptStore";
36
 
37
  const fetchMock = vi.fn();
38
  vi.stubGlobal("fetch", fetchMock);
 
1094
  });
1095
  });
1096
 
1097
+ describe("pages the fallback search already sent", () => {
1098
+ // The store outlives each test, so each one uses its own URL.
1099
+ let url: string;
1100
+ let nextPage = 0;
1101
+ beforeEach(() => {
1102
+ url = `https://example.com/heat-pumps-${nextPage++}`;
1103
+ });
1104
+ const excerpts = [
1105
+ "A heat pump moves heat from the outside air into the house instead of generating it, which is why it uses less electricity than a resistive heater for the same warmth.",
1106
+ "In cooling mode the same refrigerant cycle runs in reverse and carries the heat from the house back to the outside unit, the way an air conditioner does.",
1107
+ ].join("\n\n");
1108
+
1109
+ it("grounds on the excerpts without reading the page", async () => {
1110
+ rememberSearchExcerpts("how does a heat pump work", url, excerpts);
1111
+ const before = getPageReadStats();
1112
+
1113
+ const contents = await fetchPageContents("how does a heat pump work", [
1114
+ url,
1115
+ ]);
1116
+
1117
+ expect(fetchMock).not.toHaveBeenCalled();
1118
+ expect(contents).toHaveLength(1);
1119
+ expect(contents[0].content).toContain("refrigerant cycle");
1120
+ const after = getPageReadStats();
1121
+ expect(after.servedFromSearchExcerpts).toBe(
1122
+ before.servedFromSearchExcerpts + 1,
1123
+ );
1124
+ expect(after.requested).toBe(before.requested);
1125
+ });
1126
+
1127
+ it("reads the page when the excerpts were sent for another query", async () => {
1128
+ rememberSearchExcerpts("heat pump prices", url, excerpts);
1129
+ respondWithHtml(articlePage);
1130
+
1131
+ await fetchPageContents("how does a heat pump work", [url]);
1132
+
1133
+ expect(fetchMock).toHaveBeenCalledTimes(1);
1134
+ });
1135
+
1136
+ it("reads the page when the excerpts are too short to ground on", async () => {
1137
+ rememberSearchExcerpts("short excerpts", url, "Too short to ground on.");
1138
+ respondWithHtml(articlePage);
1139
+
1140
+ await fetchPageContents("short excerpts", [url]);
1141
+
1142
+ expect(fetchMock).toHaveBeenCalledTimes(1);
1143
+ });
1144
+ });
1145
+
1146
  describe("fetchPageContents", () => {
1147
  it("identifies itself with the name, version and repository in package.json", async () => {
1148
  respondWithHtml(articlePage);
server/pageContentService.ts CHANGED
@@ -9,7 +9,9 @@ import {
9
  import {
10
  type PageReadOutcome,
11
  recordPageRead,
 
12
  } from "./pageReadsSinceLastRestart.ts";
 
13
  import { resolvePublicUrl } from "./utils/publicUrl.ts";
14
  import { readCappedBytes } from "./utils/streamUtils.ts";
15
 
@@ -421,6 +423,8 @@ interface FetchedPage {
421
  contextTerms: string[];
422
  durationMs: number;
423
  bodyTruncated: boolean;
 
 
424
  }
425
 
426
  function isRedirect(status: number): boolean {
@@ -1193,6 +1197,30 @@ async function fetchPageContent(
1193
  }
1194
  }
1195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1196
  /**
1197
  * Reads the given pages and returns the passages most relevant to the query.
1198
  * Pages that fail, time out, or carry no readable text are left out instead of
@@ -1203,7 +1231,9 @@ async function fetchPageContent(
1203
  * appear on several pages reach the prompt once.
1204
  *
1205
  * A host that refused enough recent reads is skipped without a request, under
1206
- * `breaker`, and that skip is counted like any other outcome.
 
 
1207
  *
1208
  * Nothing here is logged. Every read is counted instead, by outcome, in
1209
  * `pageReadsSinceLastRestart`, since a line naming the query or the URL would
@@ -1219,7 +1249,10 @@ export async function fetchPageContents(
1219
  breaker: PageReadHostBreaker = pageReadHostBreaker,
1220
  ): Promise<PageContent[]> {
1221
  const results = await Promise.all(
1222
- urls.map((url) => fetchPageContent(url, breaker)),
 
 
 
1223
  );
1224
 
1225
  const pages = results.filter((r): r is FetchedPage => r !== null);
@@ -1243,6 +1276,10 @@ export async function fetchPageContents(
1243
  );
1244
 
1245
  for (const page of pages) {
 
 
 
 
1246
  const selected = selectedByUrl.get(page.url) ?? [];
1247
  recordPageRead({
1248
  outcome: "read",
 
9
  import {
10
  type PageReadOutcome,
11
  recordPageRead,
12
+ recordPageServedFromSearchExcerpts,
13
  } from "./pageReadsSinceLastRestart.ts";
14
+ import { recallSearchExcerpts } from "./searchExcerptStore.ts";
15
  import { resolvePublicUrl } from "./utils/publicUrl.ts";
16
  import { readCappedBytes } from "./utils/streamUtils.ts";
17
 
 
423
  contextTerms: string[];
424
  durationMs: number;
425
  bodyTruncated: boolean;
426
+ /** Text the search provider already sent, so no request was made. */
427
+ fromSearchExcerpts?: boolean;
428
  }
429
 
430
  function isRedirect(status: number): boolean {
 
1197
  }
1198
  }
1199
 
1200
+ /**
1201
+ * The excerpts the fallback search received for this query and URL, as a page,
1202
+ * when they hold enough text to ground on. Otherwise the page is read.
1203
+ */
1204
+ function pageFromSearchExcerpts(
1205
+ query: string,
1206
+ url: string,
1207
+ ): FetchedPage | null {
1208
+ const text = recallSearchExcerpts(query, url);
1209
+ if (text === undefined) return null;
1210
+
1211
+ const passages = splitIntoPassages(text);
1212
+ if (passages.join("\n").length < MIN_USEFUL_CHARS) return null;
1213
+
1214
+ return {
1215
+ url,
1216
+ passages,
1217
+ contextTerms: [],
1218
+ durationMs: 0,
1219
+ bodyTruncated: false,
1220
+ fromSearchExcerpts: true,
1221
+ };
1222
+ }
1223
+
1224
  /**
1225
  * Reads the given pages and returns the passages most relevant to the query.
1226
  * Pages that fail, time out, or carry no readable text are left out instead of
 
1231
  * appear on several pages reach the prompt once.
1232
  *
1233
  * A host that refused enough recent reads is skipped without a request, under
1234
+ * `breaker`, and that skip is counted like any other outcome. A page the
1235
+ * fallback search already sent excerpts of for this query is not requested
1236
+ * either: those excerpts stand in for its text.
1237
  *
1238
  * Nothing here is logged. Every read is counted instead, by outcome, in
1239
  * `pageReadsSinceLastRestart`, since a line naming the query or the URL would
 
1249
  breaker: PageReadHostBreaker = pageReadHostBreaker,
1250
  ): Promise<PageContent[]> {
1251
  const results = await Promise.all(
1252
+ urls.map(
1253
+ (url) =>
1254
+ pageFromSearchExcerpts(query, url) ?? fetchPageContent(url, breaker),
1255
+ ),
1256
  );
1257
 
1258
  const pages = results.filter((r): r is FetchedPage => r !== null);
 
1276
  );
1277
 
1278
  for (const page of pages) {
1279
+ if (page.fromSearchExcerpts) {
1280
+ recordPageServedFromSearchExcerpts();
1281
+ continue;
1282
+ }
1283
  const selected = selectedByUrl.get(page.url) ?? [];
1284
  recordPageRead({
1285
  outcome: "read",
server/pageReadsSinceLastRestart.ts CHANGED
@@ -50,6 +50,10 @@ const outcomes: Record<PageReadOutcome, number> = {
50
  let groundingRequests = 0;
51
  let groundingRequestsWithContent = 0;
52
 
 
 
 
 
53
  let totalReadMs = 0;
54
  let bodiesTruncated = 0;
55
  let totalPassagesKept = 0;
@@ -79,6 +83,10 @@ export function recordPageRead({
79
  totalPassagesAvailable += passagesAvailable;
80
  }
81
 
 
 
 
 
82
  /** One `/page-content` request, and whether any of its pages yielded text. */
83
  export function recordGroundingOutcome(hadContent: boolean): void {
84
  groundingRequests++;
@@ -100,6 +108,7 @@ export function getPageReadStats() {
100
  requested,
101
  read,
102
  readRate: Number(((read / requested) * 100 || 0).toFixed(1)),
 
103
  averageReadMs: Math.round(totalReadMs / requested || 0),
104
  bodiesTruncated,
105
  // A ratio rather than a count of pages that overflowed: an article almost
 
50
  let groundingRequests = 0;
51
  let groundingRequestsWithContent = 0;
52
 
53
+ // Pages whose text came with the search results, so no read was made. Kept out
54
+ // of `requested`, so `readRate` keeps measuring the reads that went out.
55
+ let servedFromSearchExcerpts = 0;
56
+
57
  let totalReadMs = 0;
58
  let bodiesTruncated = 0;
59
  let totalPassagesKept = 0;
 
83
  totalPassagesAvailable += passagesAvailable;
84
  }
85
 
86
+ export function recordPageServedFromSearchExcerpts(): void {
87
+ servedFromSearchExcerpts++;
88
+ }
89
+
90
  /** One `/page-content` request, and whether any of its pages yielded text. */
91
  export function recordGroundingOutcome(hadContent: boolean): void {
92
  groundingRequests++;
 
108
  requested,
109
  read,
110
  readRate: Number(((read / requested) * 100 || 0).toFixed(1)),
111
+ servedFromSearchExcerpts,
112
  averageReadMs: Math.round(totalReadMs / requested || 0),
113
  bodiesTruncated,
114
  // A ratio rather than a count of pages that overflowed: an article almost
server/searchExcerptStore.test.ts ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ type StoreModule = typeof import("./searchExcerptStore");
4
+ let rememberSearchExcerpts: StoreModule["rememberSearchExcerpts"];
5
+ let recallSearchExcerpts: StoreModule["recallSearchExcerpts"];
6
+
7
+ beforeEach(async () => {
8
+ // A fresh store per test, since the entries are module state.
9
+ vi.resetModules();
10
+ ({ rememberSearchExcerpts, recallSearchExcerpts } = await import(
11
+ "./searchExcerptStore"
12
+ ));
13
+ });
14
+
15
+ afterEach(() => {
16
+ vi.useRealTimers();
17
+ });
18
+
19
+ describe("searchExcerptStore", () => {
20
+ it("returns the text only for the query and URL it was stored under", () => {
21
+ rememberSearchExcerpts("heat pumps", "https://example.com/a", "Text A");
22
+
23
+ expect(recallSearchExcerpts("heat pumps", "https://example.com/a")).toBe(
24
+ "Text A",
25
+ );
26
+ expect(recallSearchExcerpts(" heat pumps ", "https://example.com/a")).toBe(
27
+ "Text A",
28
+ );
29
+ expect(
30
+ recallSearchExcerpts("heat pump", "https://example.com/a"),
31
+ ).toBeUndefined();
32
+ expect(
33
+ recallSearchExcerpts("heat pumps", "https://example.com/b"),
34
+ ).toBeUndefined();
35
+ });
36
+
37
+ it("forgets an entry after five minutes", () => {
38
+ vi.useFakeTimers();
39
+ rememberSearchExcerpts("q", "https://example.com/a", "Text");
40
+
41
+ vi.advanceTimersByTime(5 * 60_000 - 1);
42
+ expect(recallSearchExcerpts("q", "https://example.com/a")).toBe("Text");
43
+
44
+ vi.advanceTimersByTime(1);
45
+ expect(recallSearchExcerpts("q", "https://example.com/a")).toBeUndefined();
46
+ });
47
+
48
+ it("drops the oldest entries beyond 500", () => {
49
+ for (let index = 0; index <= 500; index++) {
50
+ rememberSearchExcerpts("q", `https://example.com/${index}`, `${index}`);
51
+ }
52
+
53
+ expect(recallSearchExcerpts("q", "https://example.com/0")).toBeUndefined();
54
+ expect(recallSearchExcerpts("q", "https://example.com/1")).toBe("1");
55
+ expect(recallSearchExcerpts("q", "https://example.com/500")).toBe("500");
56
+ });
57
+ });
server/searchExcerptStore.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createHash } from "node:crypto";
2
+
3
+ /**
4
+ * Page text a search provider already sent with its results, held so that
5
+ * `/page-content` can ground the answer on it instead of downloading the page.
6
+ * Only the fallback search fills it: Parallel answers each result with excerpts
7
+ * picked for the query, a median of about 2,500 characters, of which the
8
+ * result's snippet keeps 400.
9
+ *
10
+ * Keyed on a hash of the query and the URL. Excerpts picked for one query are
11
+ * no grounding for another, an entry only reaches a caller that already sent
12
+ * the same query, and the store holds no query in clear text.
13
+ */
14
+ const TTL_MS = 5 * 60_000;
15
+ const MAX_ENTRIES = 500;
16
+
17
+ const entries = new Map<string, { text: string; expiresAt: number }>();
18
+
19
+ function keyOf(query: string, url: string): string {
20
+ return createHash("sha256")
21
+ .update(JSON.stringify([query.trim(), url]))
22
+ .digest("hex");
23
+ }
24
+
25
+ export function rememberSearchExcerpts(
26
+ query: string,
27
+ url: string,
28
+ text: string,
29
+ ): void {
30
+ const now = Date.now();
31
+ const key = keyOf(query, url);
32
+ entries.delete(key);
33
+ entries.set(key, { text, expiresAt: now + TTL_MS });
34
+
35
+ // Insertion order is expiry order, since every entry lives for the same
36
+ // time, so the oldest entries are both the expired and the evictable ones.
37
+ for (const [oldestKey, oldest] of entries) {
38
+ if (entries.size <= MAX_ENTRIES && oldest.expiresAt > now) break;
39
+ entries.delete(oldestKey);
40
+ }
41
+ }
42
+
43
+ export function recallSearchExcerpts(
44
+ query: string,
45
+ url: string,
46
+ ): string | undefined {
47
+ const key = keyOf(query, url);
48
+ const entry = entries.get(key);
49
+ if (!entry) return undefined;
50
+ if (entry.expiresAt <= Date.now()) {
51
+ entries.delete(key);
52
+ return undefined;
53
+ }
54
+ return entry.text;
55
+ }