Spaces:
Running
Running
Sync from felladrin/MiniSearch@ebacf26 (part 2)
Browse filesFiles changed (8)
158 unmodified lines159160161162163164165158 unmodified lines4. Return structured JSON response```Reranking is applied to both text and image search results. For image results, titles and URLs are reformatted into the same text-tuple shape used for text search before being sent through the reranker, then the original image data (including thumbnails) is re-matched to the reranked order by URL. Text search passes `preserveTopResults: true` to keep the original top SearXNG result pinned, while image search does not.## Model Details158 unmodified lines159160161162163164165158 unmodified lines4. Return structured JSON response```Reranking is applied to both text and image search results. For image results, titles and URLs are reformatted into the same text-tuple shape used for text search before being sent through the reranker, then the original image data (including thumbnails) is re-matched to the reranked order. The reranker still gets the page URL, because the authority boost reads its host, so each ranked row takes an image from that page that has not been placed yet, preferring one with the same title; several images from one page all keep their own place. Text search passes `preserveTopResults: true` to keep the original top SearXNG result pinned, while image search does not.## Model Details
79 unmodified lines80818283848579 unmodified lines| `imageSearchResultsPubSub` | `ImageSearchResults` | Image search results | ImageResultsSection || `textSearchStatePubSub` | `SearchState` | Text search state: `"idle" \| "running" \| "failed" \| "completed"` | SearchResultsSection, LoadingIndicators || `textSearchStalePubSub` | `boolean` | Whether the text results on screen came from the cache because the live search failed | TextSearchResults || `imageSearchStatePubSub` | `SearchState` | Image search state: `"idle" \| "running" \| "failed" \| "completed"` | ImageResultsSection || `textGenerationStatePubSub` | `TextGenerationState` | AI generation state | AiResponseSection, StatusIndicators || `modelLoadingProgressPubSub` | `number` | Model download progress (0-100) | AiResponseSection |79 unmodified lines8081828384858679 unmodified lines| `imageSearchResultsPubSub` | `ImageSearchResults` | Image search results | ImageResultsSection || `textSearchStatePubSub` | `SearchState` | Text search state: `"idle" \| "running" \| "failed" \| "completed"` | SearchResultsSection, LoadingIndicators || `textSearchStalePubSub` | `boolean` | Whether the text results on screen came from the cache because the live search failed | TextSearchResults || `textSearchTimeFilterPubSub` | `boolean` | Whether the text results on screen carry no time filter although one was asked for, because a fallback provider answered; a follow-up can set it but never clear it | TextSearchResults || `imageSearchStatePubSub` | `SearchState` | Image search state: `"idle" \| "running" \| "failed" \| "completed"` | ImageResultsSection || `textGenerationStatePubSub` | `TextGenerationState` | AI generation state | AiResponseSection, StatusIndicators || `modelLoadingProgressPubSub` | `number` | Model download progress (0-100) | AiResponseSection |
2078 unmodified lines2079208020812082208320842085208620871 unmodified line2089209020912092209320942095209620972098209921002078 unmodified lines"license": "MIT"},"node_modules/@tabler/icons": {"version": "3.52.0","resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.52.0.tgz","integrity": "sha512-dldKlJNfO/gZnGLcIY0X2EFFKIMGwL/rEvTqglvBgAPFiwj9pZOCN5V3Sf0Gyjq6foX4VQmLdOmsS4w5FdWKAw==","license": "MIT","funding": {"type": "github",1 unmodified line}},"node_modules/@tabler/icons-react": {"version": "3.52.0","resolved": "https://registry.npmjs.org/@tabler/icons-react/-/icons-react-3.52.0.tgz","integrity": "sha512-tN22mz4KLVpR+psqu9bAsT4b1IdhKcPGA1fDhyQerIv+8azyowdWzf8e0hWxQSsIxDTfkipGfiL0/uHNmpbvgw==","license": "MIT","dependencies": {"@tabler/icons": "3.52.0"},"funding": {"type": "github",2078 unmodified lines2079208020812082208320842085208620871 unmodified line2089209020912092209320942095209620972098209921002078 unmodified lines"license": "MIT"},"node_modules/@tabler/icons": {"version": "3.53.0","resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.53.0.tgz","integrity": "sha512-7V77PESErZob7+Ie4ibDs9tjRoMmZyjr3RpxRK3KLJejwggzxrkhVunbQ7xGYewjwdUyPc6dHpMvvft0prkkzQ==","license": "MIT","funding": {"type": "github",1 unmodified line}},"node_modules/@tabler/icons-react": {"version": "3.53.0","resolved": "https://registry.npmjs.org/@tabler/icons-react/-/icons-react-3.53.0.tgz","integrity": "sha512-uaj3Pne8ULNIOhYYHCX1kK6q1AVzxB2qCoyRnb67Q36YTA+1ctSmrrzZS/VptG/OQWOsXYz4prA7lQMTG2llcw==","license": "MIT","dependencies": {"@tabler/icons": "3.53.0"},"funding": {"type": "github",
212 unmodified lines21321421521621721873 unmodified lines29229329429529629721 unmodified lines31932032132232332432532632713 unmodified lines341342343344345346112 unmodified lines459460461462463464141 unmodified lines606607608609610611259 unmodified lines8718728738748758769 unmodified lines886887888889890891212 unmodified lines30,undefined,expect.any(AbortSignal),);});73 unmodified lines30,undefined,expect.any(AbortSignal),);expect(incrementTextualSearchesSinceLastRestart).toHaveBeenCalled();expect(response.setHeader).toHaveBeenCalledWith(21 unmodified lines30,undefined,expect.any(AbortSignal),);});it("reranks results when the reranker is healthy and returns its reordered output", async () => {vi.mocked(fetchSearXNG).mockResolvedValue([["A", "snippet a", "https://a.com"],13 unmodified lines5,undefined,expect.any(AbortSignal),);expect(rankSearchResults).toHaveBeenCalledWith("test",112 unmodified linesexpect(endBody(response)).toEqual([imageResult]);});it("drops an image the reranker returns under an unknown URL", async () => {vi.mocked(fetchSearXNG).mockResolvedValue([imageResult]);vi.mocked(getRerankerStatus).mockResolvedValue(true);141 unmodified lines);});it("answers 200 with an empty list when the fallback returns nothing usable", async () => {vi.mocked(isSearchFallbackEnabled).mockReturnValue(true);failSearxng();259 unmodified linesexpect(response.end).toHaveBeenCalledWith(JSON.stringify(searxngResults));});it("asks a supplementary search for the named site and merges it behind the first result", async () => {vi.mocked(fetchSearXNG).mockResolvedValue(searxngResults);vi.mocked(fetchSupplementarySearXNG).mockResolvedValue(laneResults);9 unmodified lines"site:disney.com disney showtimes",30,expect.any(AbortSignal),);expect(response.end).toHaveBeenCalledWith(JSON.stringify([searxngResults[0], laneResults[0], searxngResults[1]]),212 unmodified lines21321421521621721821973 unmodified lines29329429529629729829921 unmodified lines32132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440513 unmodified lines419420421422423424425112 unmodified lines538539540541542543544545546547548549550551552553554555556557558559560561562563564565566141 unmodified lines708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762259 unmodified lines10221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510469 unmodified lines1056105710581059106010611062212 unmodified lines30,undefined,expect.any(AbortSignal),undefined,);});73 unmodified lines30,undefined,expect.any(AbortSignal),undefined,);expect(incrementTextualSearchesSinceLastRestart).toHaveBeenCalled();expect(response.setHeader).toHaveBeenCalledWith(21 unmodified lines30,undefined,expect.any(AbortSignal),undefined,);});describe("time_range parameter", () => {it.each(["day", "week", "month", "year"] as const)("passes %s through to SearXNG",async (timeRange) => {vi.mocked(fetchSearXNG).mockResolvedValue([]);await sendSearch(`/search/text?q=cats&token=abc&time_range=${timeRange}`,);expect(fetchSearXNG).toHaveBeenCalledWith("cats","text",30,undefined,expect.any(AbortSignal),timeRange,);},);it("passes it on an image search as well", async () => {vi.mocked(fetchSearXNG).mockResolvedValue([]);await sendSearch("/search/images?q=cats&token=abc&time_range=month");expect(fetchSearXNG).toHaveBeenCalledWith("cats","images",30,undefined,expect.any(AbortSignal),"month",);});it("passes nothing when the request carries no time range", async () => {vi.mocked(fetchSearXNG).mockResolvedValue([]);await sendSearch("/search/text?q=cats&token=abc");expect(fetchSearXNG).toHaveBeenCalledWith("cats","text",30,undefined,expect.any(AbortSignal),undefined,);});it("answers 400 to a period SearXNG does not know", async () => {const response = await sendSearch("/search/text?q=cats&token=abc&time_range=fortnight",);// Refused rather than answered unfiltered: results from any time would// look like the recent ones the caller asked for.expect(response.statusCode).toBe(400);expect(response.end).toHaveBeenCalledWith(JSON.stringify({ error: "Invalid time_range parameter" }),);expect(fetchSearXNG).not.toHaveBeenCalled();});it("answers 400 to an empty time range", async () => {const response = await sendSearch("/search/text?q=cats&token=abc&time_range=",);expect(response.statusCode).toBe(400);expect(fetchSearXNG).not.toHaveBeenCalled();});});it("reranks results when the reranker is healthy and returns its reordered output", async () => {vi.mocked(fetchSearXNG).mockResolvedValue([["A", "snippet a", "https://a.com"],13 unmodified lines5,undefined,expect.any(AbortSignal),undefined,);expect(rankSearchResults).toHaveBeenCalledWith("test",112 unmodified linesexpect(endBody(response)).toEqual([imageResult]);});it("keeps every reranked image from the same page", async () => {const galleryImages = ["first", "second"].map((name) =>[`Gallery ${name}`,"https://example.com/gallery",`https://example.com/${name}-thumb.gif`,`https://example.com/${name}.gif`,] as [string, string, string, string],);vi.mocked(fetchSearXNG).mockResolvedValue(galleryImages);vi.mocked(getRerankerStatus).mockResolvedValue(true);vi.mocked(rankSearchResults).mockResolvedValue([["Gallery second", "", "https://example.com/gallery", 0.9],["Gallery first", "", "https://example.com/gallery", 0.5],]);const response = await sendSearch("/search/images?q=cats&token=abc");expect(response.statusCode).toBe(200);expect(endBody(response)).toEqual([galleryImages[1], galleryImages[0]]);});it("drops an image the reranker returns under an unknown URL", async () => {vi.mocked(fetchSearXNG).mockResolvedValue([imageResult]);vi.mocked(getRerankerStatus).mockResolvedValue(true);141 unmodified lines);});it("says the time filter was not applied when the fallback answers a filtered search", async () => {vi.mocked(isSearchFallbackEnabled).mockReturnValue(true);failSearxng();vi.mocked(fetchFallbackTextResults).mockResolvedValue(fallbackResults);const response = await sendSearch("/search/text?q=cats&token=abc&time_range=week",);expect(response.statusCode).toBe(200);expect(response.setHeader).toHaveBeenCalledWith("X-Search-Time-Range-Applied","false",);// The body keeps its shape: the note is the header's job alone.expect(response.end).toHaveBeenCalledWith(JSON.stringify(fallbackResults),);});it("says nothing when the fallback answers a search with no time range", async () => {vi.mocked(isSearchFallbackEnabled).mockReturnValue(true);failSearxng();vi.mocked(fetchFallbackTextResults).mockResolvedValue(fallbackResults);const response = await sendSearch("/search/text?q=cats&token=abc");expect(response.statusCode).toBe(200);expect(response.setHeader).not.toHaveBeenCalledWith("X-Search-Time-Range-Applied","false",);});it("says nothing when SearXNG answers a filtered search itself", async () => {vi.mocked(isSearchFallbackEnabled).mockReturnValue(true);vi.mocked(fetchSearXNG).mockResolvedValue(searxngResults);const response = await sendSearch("/search/text?q=cats&token=abc&time_range=week",);expect(response.statusCode).toBe(200);expect(response.setHeader).not.toHaveBeenCalledWith("X-Search-Time-Range-Applied","false",);});it("answers 200 with an empty list when the fallback returns nothing usable", async () => {vi.mocked(isSearchFallbackEnabled).mockReturnValue(true);failSearxng();259 unmodified linesexpect(response.end).toHaveBeenCalledWith(JSON.stringify(searxngResults));});it("gives the supplementary search the same time range", async () => {vi.mocked(fetchSearXNG).mockResolvedValue(searxngResults);vi.mocked(fetchSupplementarySearXNG).mockResolvedValue([]);const handler = getRegisteredHandler();await handler(createRequest(`${query}&time_range=day`),createResponse(),vi.fn(),);expect(fetchSupplementarySearXNG).toHaveBeenCalledWith("site:disney.com disney showtimes",30,expect.any(AbortSignal),"day",);});it("asks a supplementary search for the named site and merges it behind the first result", async () => {vi.mocked(fetchSearXNG).mockResolvedValue(searxngResults);vi.mocked(fetchSupplementarySearXNG).mockResolvedValue(laneResults);9 unmodified lines"site:disney.com disney showtimes",30,expect.any(AbortSignal),undefined,);expect(response.end).toHaveBeenCalledWith(JSON.stringify([searxngResults[0], laneResults[0], searxngResults[1]]),
1234576 unmodified lines82838485868747 unmodified lines13513613713813914013 unmodified lines15415515615715815962 unmodified lines2222232242252262271 unmodified line22923023123223323423512 unmodified lines24824925025125225324 unmodified lines27827928028128228334 unmodified lines31831932032132232319 unmodified lines343344345346347348349350351352353354355356import type { PreviewServer, ViteDevServer } from "vite";import { z } from "zod";import {assertSearchFallbackConfiguration,fetchFallbackTextResults,76 unmodified lines.positive().catch(DEFAULT_SEARCH_LIMIT).transform((limit) => Math.min(limit, MAX_SEARCH_LIMIT)),});type TextResult = [title: string, content: string, url: string];47 unmodified linesresults: TextResult[],limit: number,remainingMs: number,): Promise<TextResult[]> {const budgetMs = Math.min(MAX_OFFICIAL_LANE_TIMEOUT_MS,13 unmodified lineslane.query,limit,AbortSignal.timeout(budgetMs),);const merged = mergeOfficialLaneResults(results, laneResults, lane.domain);62 unmodified linesconst parsedParams = searchParamsSchema.safeParse({query: url.searchParams.get("q") ?? undefined,limit: url.searchParams.get("limit") ?? DEFAULT_SEARCH_LIMIT,});if (!parsedParams.success) {1 unmodified linereturn;}const { query, limit } = parsedParams.data;try {const isTextSearch = searchType === "text";12 unmodified lineslimit,undefined,AbortSignal.timeout(searxngTimeoutMs),);servedBySearXNG = true;recordSearchDuration(searchType, performance.now() - searchStartedAt);24 unmodified linesremainingMs,);incrementSearchesServedByFallback();} catch (fallbackError) {incrementSearchesFailedOnFallback();// Fixed text plus the error's message, which by construction34 unmodified linesresults,limit,remainingMs,);}19 unmodified linesresultsText,);const processedResults = rankedResults.map(([title, , rankedResultUrl]) => {const result = results.find(([, resultUrl]) => resultUrl === rankedResultUrl,);if (!result) return null;const [, url, thumbnailSource, sourceUrl] = result;return [title, url, thumbnailSource, sourceUrl] as ImageResult;}).filter((result): result is ImageResult => result !== null);1234567891076 unmodified lines878889909192939495969747 unmodified lines14514614714814915015113 unmodified lines16516616716816917017162 unmodified lines2342352362372382392401 unmodified line24224324424524624724812 unmodified lines26126226326426526626724 unmodified lines29229329429529629729829930030130230330430534 unmodified lines34034134234334434534619 unmodified lines366367368369370371372373374375376377378379380381382383384385386387388389390391392393394import type { PreviewServer, ViteDevServer } from "vite";import { z } from "zod";import {SEARCH_TIME_RANGE_APPLIED_HEADER,type SearxngTimeRange,searxngTimeRanges,} from "../shared/searchTimeRange.ts";import {assertSearchFallbackConfiguration,fetchFallbackTextResults,76 unmodified lines.positive().catch(DEFAULT_SEARCH_LIMIT).transform((limit) => Math.min(limit, MAX_SEARCH_LIMIT)),// No `.catch()`: an unknown period is the caller's mistake, and answering it// with unfiltered results would pass off a wider search as the one asked for.time_range: z.enum(searxngTimeRanges, { error: "Invalid time_range parameter" }).optional(),});type TextResult = [title: string, content: string, url: string];47 unmodified linesresults: TextResult[],limit: number,remainingMs: number,timeRange: SearxngTimeRange | undefined,): Promise<TextResult[]> {const budgetMs = Math.min(MAX_OFFICIAL_LANE_TIMEOUT_MS,13 unmodified lineslane.query,limit,AbortSignal.timeout(budgetMs),timeRange,);const merged = mergeOfficialLaneResults(results, laneResults, lane.domain);62 unmodified linesconst parsedParams = searchParamsSchema.safeParse({query: url.searchParams.get("q") ?? undefined,limit: url.searchParams.get("limit") ?? DEFAULT_SEARCH_LIMIT,time_range: url.searchParams.get("time_range") ?? undefined,});if (!parsedParams.success) {1 unmodified linereturn;}const { query, limit, time_range: timeRange } = parsedParams.data;try {const isTextSearch = searchType === "text";12 unmodified lineslimit,undefined,AbortSignal.timeout(searxngTimeoutMs),timeRange,);servedBySearXNG = true;recordSearchDuration(searchType, performance.now() - searchStartedAt);24 unmodified linesremainingMs,);incrementSearchesServedByFallback();// The fallback providers take a query and a count only, so the// period the search asked for cannot be honored here. Saying so// is the difference between a narrow search and a wide one that// looks narrow.if (timeRange) {response.setHeader(SEARCH_TIME_RANGE_APPLIED_HEADER, "false");}} catch (fallbackError) {incrementSearchesFailedOnFallback();// Fixed text plus the error's message, which by construction34 unmodified linesresults,limit,remainingMs,timeRange,);}19 unmodified linesresultsText,);// Several images can come from one page, so a ranked row is matched// back to an image it has not been matched to yet, preferring one with// the same title. The reranker keeps the page URL for its authority// boost.const unmatched = new Set(results);const processedResults = rankedResults.map(([rankedTitle, , rankedResultUrl]) => {const sameUrl = [...unmatched].filter(([, resultUrl]) => resultUrl === rankedResultUrl,);const result =sameUrl.find(([title]) => (title?.slice(0, 100) || "") === rankedTitle,) ?? sameUrl[0];if (!result) return null;unmatched.delete(result);const [, url, thumbnailSource, sourceUrl] = result;return [rankedTitle,url,thumbnailSource,sourceUrl,] as ImageResult;}).filter((result): result is ImageResult => result !== null);
578 unmodified lines579580581582583584634 unmodified lines121912201221122212231224150 unmodified lines137513761377578 unmodified lines]);});it("drops image results that carry no thumbnail URL", async () => {fetchMock.mockResolvedValue(createMockResponse(634 unmodified linesexpect(healthBookkeeping()).toEqual(before);});it("fails on the first error status, without retrying", async () => {fetchMock.mockResolvedValue(createMockResponse("", false, 500));const before = healthBookkeeping();150 unmodified linesexpect(answer.cancel).toHaveBeenCalledTimes(1);});});578 unmodified lines579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622634 unmodified lines1257125812591260126112621263126412651266126712681269127012711272127312741275127612771278150 unmodified lines142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482578 unmodified lines]);});it("keeps different images found on the same page", async () => {const galleryImage = (name: string) => ({title: name,url: "https://example.com/gallery",category: "images",img_src: `https://example.com/${name}.gif`,thumbnail_src: `https://example.com/${name}-thumb.gif`,});fetchMock.mockResolvedValue(createMockResponse(JSON.stringify({results: [galleryImage("first"),galleryImage("second"),// The same image reported by a second engine is still one result.galleryImage("first"),],}),),);const results = await fetchSearXNG("failure injection","images",5,new CircuitBreaker(breakerOptions),);expect(results).toEqual(["first", "second"].map((name) => [name,"https://example.com/gallery",`https://example.com/${name}-thumb.gif`,`https://example.com/${name}.gif`,]),);});it("drops image results that carry no thumbnail URL", async () => {fetchMock.mockResolvedValue(createMockResponse(634 unmodified linesexpect(healthBookkeeping()).toEqual(before);});it("sends the time range it is given", async () => {fetchMock.mockResolvedValue(createMockResponse(JSON.stringify({ results: [] })),);await fetchSupplementarySearXNG("site:example.com test",30,undefined,"week",);const url = new URL(String(fetchMock.mock.calls[0]?.[0]));expect(url.searchParams.get("time_range")).toBe("week");});it("fails on the first error status, without retrying", async () => {fetchMock.mockResolvedValue(createMockResponse("", false, 500));const before = healthBookkeeping();150 unmodified linesexpect(answer.cancel).toHaveBeenCalledTimes(1);});});describe("time_range parameter", () => {/** The query parameters of the SearXNG request the search just made. */function sentParams() {return new URL(fetchMock.mock.calls[0][0] as string).searchParams;}it("sends no time_range when the search asks for any time", async () => {fetchMock.mockResolvedValue(successResponse());await fetchSearXNG("test", "text", 30);expect(sentParams().has("time_range")).toBe(false);expect(sentParams().get("categories")).toBe("general");});it.each(["day", "week", "month", "year"] as const)("sends time_range=%s next to the categories it already sent",async (timeRange) => {fetchMock.mockResolvedValue(successResponse());await fetchSearXNG("test","text",30,new CircuitBreaker(),undefined,timeRange,);expect(sentParams().get("time_range")).toBe(timeRange);expect(sentParams().get("categories")).toBe("general");},);it("sends it on an image search too", async () => {fetchMock.mockResolvedValue(successResponse());await fetchSearXNG("test","images",30,new CircuitBreaker(),undefined,"week",);expect(sentParams().get("time_range")).toBe("week");expect(sentParams().get("categories")).toBe("images,videos");});});
1 unmodified line234567155 unmodified lines163164165166167168169170171172115 unmodified lines28828929029129229329429574 unmodified lines37037137237337437537637737837938038138244 unmodified lines4274284294304314321 unmodified line4344354364374384392 unmodified lines44244344444544644716 unmodified lines4644654664674684694704716 unmodified lines47847948048148248348459 unmodified lines5445455465475485495505515525535545555565575585595605615625631 unmodified lineimport debug from "debug";import { convert as convertHtmlToPlainText } from "html-to-text";import { strip as stripEmojis } from "node-emoji";import {type EngineFailure,getDegradedSearchTypes,155 unmodified linesreturn getDegradedSearchTypes().length > 0 ? "degraded" : "healthy";}function buildSearchUrl(query: string, searchType: SearchType) {const params = new URLSearchParams(defaultSearchParams);params.set("q", query);params.set("categories", searchType === "text" ? "general" : "images,videos");return `${SERVICE_BASE_URL}/search?${params.toString()}`;}115 unmodified linesquery: string,searchType: SearchType,signal?: AbortSignal,): Promise<SearxngSearchResult[]> {const searchUrl = buildSearchUrl(query, searchType);let retryReason = "";74 unmodified lineslimit: number,breaker: CircuitBreaker,signal?: AbortSignal,) {// An abort is thrown inside `execute`, so a stalled SearXNG counts as a// failure as soon as the deadline passes.const results = await breaker.execute(circuitKey(searchType), () =>performSearch(query, searchType, signal),);const openableResults = openableUniqueResults(results);if (searchType === "text") {const consideredResults = openableResults.slice(0, limit);44 unmodified lines* `signal` bounds the whole search, retries and backoff included: every fetch* gets it, and a backoff ends when it fires. Without one, a stalled SearXNG* holds the request for undici's 300 s default.*/export async function fetchSearXNG(query: string,1 unmodified linelimit = 30,breaker: CircuitBreaker = searxngCircuitBreaker,signal?: AbortSignal,) {try {return await processSearchResults(2 unmodified lineslimit,breaker,signal,);} catch (error) {// Upstream failure (bad status, network error, malformed body, open16 unmodified linesquery: string,limit: number,signal?: AbortSignal,) {const response = await fetch(buildSearchUrl(query, "text"), {headers: { Accept: "application/json" },signal,});6 unmodified linesconst data = (await response.json()) as SearxngSearchResponse;const results = Array.isArray(data.results) ? data.results : [];const textualResults = await Promise.all(openableUniqueResults(results).slice(0, limit).map(processTextualResult),);return filterNullResults(textualResults);}59 unmodified lines}}// Runs before the limit is applied, so a dropped link does not take the slot// of a result that would have made the cut.function openableUniqueResults(results: SearxngSearchResult[],): SearxngSearchResult[] {const urls = new Set<string>();const unopenableEngines: string[] = [];const kept = results.filter((result) => {if (!isOpenableUrl(result.url)) {unopenableEngines.push(result.engine ?? "unknown");return false;}if (urls.has(result.url)) return false;urls.add(result.url);return true;});// Engine names only: the url is downstream of the query, which never reaches1 unmodified line2345678155 unmodified lines164165166167168169170171172173174175176177178179180115 unmodified lines29629729829930030130230330474 unmodified lines37938038138238338438538638738838939039139239339439544 unmodified lines4404414424434444454464474481 unmodified line4504514524534544554562 unmodified lines45946046146246346446516 unmodified lines4824834844854864874884894904914926 unmodified lines49950050150250350450550650759 unmodified lines5675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996001 unmodified lineimport debug from "debug";import { convert as convertHtmlToPlainText } from "html-to-text";import { strip as stripEmojis } from "node-emoji";import type { SearxngTimeRange } from "../shared/searchTimeRange.ts";import {type EngineFailure,getDegradedSearchTypes,155 unmodified linesreturn getDegradedSearchTypes().length > 0 ? "degraded" : "healthy";}function buildSearchUrl(query: string,searchType: SearchType,timeRange?: SearxngTimeRange,) {const params = new URLSearchParams(defaultSearchParams);params.set("q", query);params.set("categories", searchType === "text" ? "general" : "images,videos");// Left out rather than sent empty, so a search with no time range reaches// SearXNG exactly as it did before the filter existed.if (timeRange) params.set("time_range", timeRange);return `${SERVICE_BASE_URL}/search?${params.toString()}`;}115 unmodified linesquery: string,searchType: SearchType,signal?: AbortSignal,timeRange?: SearxngTimeRange,): Promise<SearxngSearchResult[]> {const searchUrl = buildSearchUrl(query, searchType, timeRange);let retryReason = "";74 unmodified lineslimit: number,breaker: CircuitBreaker,signal?: AbortSignal,timeRange?: SearxngTimeRange,) {// An abort is thrown inside `execute`, so a stalled SearXNG counts as a// failure as soon as the deadline passes.const results = await breaker.execute(circuitKey(searchType), () =>performSearch(query, searchType, signal, timeRange),);const openableResults = openableUniqueResults(results,searchType === "text" ? (result) => result.url : graphicalResultKey,);if (searchType === "text") {const consideredResults = openableResults.slice(0, limit);44 unmodified lines* `signal` bounds the whole search, retries and backoff included: every fetch* gets it, and a backoff ends when it fires. Without one, a stalled SearXNG* holds the request for undici's 300 s default.** `timeRange` is SearXNG's own `time_range`, and is left out for a search that* accepts any time.*/export async function fetchSearXNG(query: string,1 unmodified linelimit = 30,breaker: CircuitBreaker = searxngCircuitBreaker,signal?: AbortSignal,timeRange?: SearxngTimeRange,) {try {return await processSearchResults(2 unmodified lineslimit,breaker,signal,timeRange,);} catch (error) {// Upstream failure (bad status, network error, malformed body, open16 unmodified linesquery: string,limit: number,signal?: AbortSignal,timeRange?: SearxngTimeRange,) {// The lane's results are merged into the main ones, so they have to honor// the same time range, or a filtered search shows unfiltered pages.const response = await fetch(buildSearchUrl(query, "text", timeRange), {headers: { Accept: "application/json" },signal,});6 unmodified linesconst data = (await response.json()) as SearxngSearchResponse;const results = Array.isArray(data.results) ? data.results : [];const textualResults = await Promise.all(openableUniqueResults(results, (result) => result.url).slice(0, limit).map(processTextualResult),);return filterNullResults(textualResults);}59 unmodified lines}}/*** What makes an image or video result distinct: the full-size source, then the* thumbnail. A gallery page returns many different images under one page URL,* so keying on the page would keep only the first of them.*/function graphicalResultKey(result: SearxngSearchResult): string {if (result.category === "videos") {return result.iframe_src || result.url;}return result.img_src || result.thumbnail_src || result.url;}// Runs before the limit is applied, so a dropped link does not take the slot// of a result that would have made the cut.function openableUniqueResults(results: SearxngSearchResult[],keyOf: (result: SearxngSearchResult) => string,): SearxngSearchResult[] {const keys = new Set<string>();const unopenableEngines: string[] = [];const kept = results.filter((result) => {if (!isOpenableUrl(result.url)) {unopenableEngines.push(result.engine ?? "unknown");return false;}const key = keyOf(result);if (keys.has(key)) return false;keys.add(key);return true;});// Engine names only: the url is downstream of the query, which never reaches
123456789101112131415161718192021222324252627/** * The time-range choices the client offers, in the order the selects list them. * `any` is MiniSearch's own value and means no filter: it is never sent to * SearXNG, which only knows the four periods after it. */export const searchTimeRangeOptions = [ { value: "any", label: "Anytime" }, { value: "day", label: "Past day" }, { value: "week", label: "Past week" }, { value: "month", label: "Past month" }, { value: "year", label: "Past year" },] as const;
export type SearchTimeRange = (typeof searchTimeRangeOptions)[number]["value"];
/** The values SearXNG accepts for its `time_range` parameter. */export const searxngTimeRanges = ["day", "week", "month", "year"] as const;
export type SearxngTimeRange = (typeof searxngTimeRanges)[number];
/** * Set to `false` on a search response whose requested time range could not be * applied, which happens when a fallback provider answers a text search: those * take only a query and a count. The header is absent when the filter was * applied, so an unfiltered search carries nothing new. */export const SEARCH_TIME_RANGE_APPLIED_HEADER = "X-Search-Time-Range-Applied";docs/reranking.md+1-1
docs/ui-components.md+1
package-lock.json+7-7
server/searchEndpointServerHook.test.ts+171
server/searchEndpointServerHook.ts+42-4
server/webSearchService.test.ts+105
server/webSearchService.ts+46-9
shared/searchTimeRange.tsAdded+27