import { describe, expect, it, vi } from "vitest"; import type { IndexHandle, IndexSearchOptions, SearchClient, SearchDocument, SearchHits, } from "./client.js"; import { bulkIndex, searchInIndex, searchWithFallback } from "./query.js"; import { kbArticlesIndex } from "./schemas/index.js"; const ORIGINAL_PRIMARY_KEY_FIELD = "__hivegridOriginalPrimaryKey"; /** * Minimal SearchClient fake that records the (query, options) handed to * the underlying index handle and returns a caller-supplied result. Lets * the tests assert the exact filter / attribute strings query.ts builds * without depending on the in-memory fake's filter interpretation. */ function capturingClient(result?: SearchHits): { client: SearchClient; calls: Array<{ query: string; options: IndexSearchOptions }>; } { const calls: Array<{ query: string; options: IndexSearchOptions }> = []; const searchResult: SearchHits = result ?? { hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }; const client = { index(): IndexHandle { return { async ensure() {}, async search(query: string, options: IndexSearchOptions) { calls.push({ query, options }); return searchResult as SearchHits; }, async upsert() {}, async delete() {}, async deleteByFilter() {}, }; }, async health() { return { status: "available" as const }; }, } satisfies SearchClient; return { client, calls }; } function throwingClient(error: unknown): SearchClient { return { index(): IndexHandle { return { async ensure() {}, async search(): Promise> { throw error; }, async upsert() {}, async delete() {}, async deleteByFilter() {}, }; }, async health() { return { status: "available" as const }; }, }; } describe("searchInIndex — filter construction", () => { it("escapes quotes and backslashes in the tenantId so the filter cannot be broken out of", async () => { const { client, calls } = capturingClient(); await searchInIndex({ client, schema: kbArticlesIndex, tenantId: 'a"b\\c', query: "x" }); // Backslash -> \\ then quote -> \" → the value stays inside one quoted token. expect(calls[0]?.options.filter).toBe('tenantId = "a\\"b\\\\c"'); }); it("AND-merges an array of extra filters and drops blank entries", async () => { const { client, calls } = capturingClient(); await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x", options: { extraFilters: ["isPublished = true", " ", 'language = "de"'] }, }); expect(calls[0]?.options.filter).toBe( 'tenantId = "t1" AND (isPublished = true) AND (language = "de")' ); }); it("falls back to the bare tenant filter when every array entry is blank", async () => { const { client, calls } = capturingClient(); await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x", options: { extraFilters: [" ", ""] }, }); expect(calls[0]?.options.filter).toBe('tenantId = "t1"'); }); it("falls back to the bare tenant filter for a blank single extra filter", async () => { const { client, calls } = capturingClient(); await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x", options: { extraFilters: " " }, }); expect(calls[0]?.options.filter).toBe('tenantId = "t1"'); }); it("defaults a missing query to an empty string", async () => { const { client, calls } = capturingClient(); await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: undefined as unknown as string, }); expect(calls[0]?.query).toBe(""); }); }); describe("searchInIndex — attributesToRetrieve handling", () => { it("augments attributesToRetrieve with the primary key and internal field, deduped", async () => { const { client, calls } = capturingClient(); await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x", // "id" duplicates the primaryKey to exercise the de-dup path. options: { attributesToRetrieve: ["title", "id"] }, }); expect(calls[0]?.options.attributesToRetrieve).toEqual([ "title", "id", ORIGINAL_PRIMARY_KEY_FIELD, ]); }); it("leaves attributesToRetrieve untouched when the wildcard is requested", async () => { const { client, calls } = capturingClient(); await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x", options: { attributesToRetrieve: ["*"] }, }); expect(calls[0]?.options.attributesToRetrieve).toEqual(["*"]); }); it("strips the internal extraFilters key before handing options to the client", async () => { const { client, calls } = capturingClient(); await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x", options: { extraFilters: "isPublished = true", limit: 3 }, }); expect(calls[0]?.options).not.toHaveProperty("extraFilters"); expect(calls[0]?.options.limit).toBe(3); }); }); describe("searchInIndex — primary-key restoration", () => { it("returns the document unchanged when it carries no internal primary-key field", async () => { const { client } = capturingClient({ hits: [{ document: { id: "raw-id", tenantId: "t1", title: "X" } }], estimatedTotalHits: 1, processingTimeMs: 0, }); const res = await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x" }); expect(res.hits[0]?.document).toEqual({ id: "raw-id", tenantId: "t1", title: "X" }); }); it("restores the original domain id from the internal field", async () => { const { client } = capturingClient({ hits: [{ document: { id: "t1:raw", tenantId: "t1", [ORIGINAL_PRIMARY_KEY_FIELD]: "raw" } }], estimatedTotalHits: 1, processingTimeMs: 0, }); const res = await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x" }); expect(res.hits[0]?.document).toEqual({ id: "raw", tenantId: "t1" }); expect(ORIGINAL_PRIMARY_KEY_FIELD in (res.hits[0]?.document ?? {})).toBe(false); }); it("drops the internal field but keeps the scoped id when the original is not a primitive", async () => { const { client } = capturingClient({ hits: [ { document: { id: "t1:raw", tenantId: "t1", title: "X", [ORIGINAL_PRIMARY_KEY_FIELD]: { nested: true }, }, }, ], estimatedTotalHits: 1, processingTimeMs: 0, }); const res = await searchInIndex({ client, schema: kbArticlesIndex, tenantId: "t1", query: "x" }); expect(res.hits[0]?.document).toEqual({ id: "t1:raw", tenantId: "t1", title: "X" }); expect(ORIGINAL_PRIMARY_KEY_FIELD in (res.hits[0]?.document ?? {})).toBe(false); }); }); describe("bulkIndex — input validation", () => { it("surfaces a clear error when a document is missing its primary key", async () => { const { client } = capturingClient(); await expect( bulkIndex({ client, schema: kbArticlesIndex, tenantId: "t1", documents: [ { tenantId: "t1", title: "no id" } as unknown as SearchDocument, ], }) ).rejects.toThrow(/missing primary key/); }); }); describe("searchWithFallback — connectivity detection", () => { const fallbackResult: SearchHits = { hits: [{ document: { id: "fb", tenantId: "t1" } }], estimatedTotalHits: 1, processingTimeMs: 0, }; const fallback = () => Promise.resolve(fallbackResult); it("falls back when the error matches only by its name", async () => { const error = Object.assign(new Error("boom"), { name: "MeiliSearchCommunicationError" }); const res = await searchWithFallback({ client: throwingClient(error), schema: kbArticlesIndex, tenantId: "t1", query: "x", fallback, }); expect(res.hits[0]?.document.id).toBe("fb"); }); it("falls back when the error matches only by its message", async () => { const error = { message: "fetch failed" }; const res = await searchWithFallback({ client: throwingClient(error), schema: kbArticlesIndex, tenantId: "t1", query: "x", fallback, }); expect(res.hits[0]?.document.id).toBe("fb"); }); it("rethrows a non-connectivity error and never invokes the fallback", async () => { const onFallback = vi.fn(); const spied = vi.fn(fallback); await expect( searchWithFallback({ client: throwingClient(new Error("validation failed: bad filter syntax")), schema: kbArticlesIndex, tenantId: "t1", query: "x", fallback: spied, onFallback, }) ).rejects.toThrow(/validation failed/); expect(spied).not.toHaveBeenCalled(); expect(onFallback).not.toHaveBeenCalled(); }); it("rethrows when the thrown value is not an object", async () => { const spied = vi.fn(fallback); await expect( searchWithFallback({ client: throwingClient("string error"), schema: kbArticlesIndex, tenantId: "t1", query: "x", fallback: spied, }) ).rejects.toBe("string error"); expect(spied).not.toHaveBeenCalled(); }); });