Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -15,8 +15,7 @@
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"meilisearch": "0.45.0",
"zod": "^3.23.8"
"meilisearch": "0.45.0"
},
"devDependencies": {
"@types/node": "^25.0.0",
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { createSearchClient, type MeiliFactory } from "./client.js";
import { toPhysicalSearchIndexUid } from "./index-name.js";
import { createInMemoryMeili } from "./testing.js";
describe("createSearchClient — guards", () => {
@@ -42,9 +43,7 @@ describe("IndexHandle.ensure — createIndex error handling", () => {
it("rethrows a non 'already exists' error from createIndex", async () => {
const { factory } = createInMemoryMeili({ throwOnIndex: true });
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
await expect(
client.index("x").ensure({ primaryKey: "id", settings: {} })
).rejects.toThrow(/meili offline/);
await expect(client.index("x").ensure({ primaryKey: "id", settings: {} })).rejects.toThrow(/meili offline/);
});
it("swallows an HTTP 409 conflict and still applies settings", async () => {
@@ -68,11 +67,132 @@ describe("IndexHandle.ensure — createIndex error handling", () => {
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
await expect(
client.index("x").ensure({ primaryKey: "id", settings: { searchableAttributes: ["t"] } })
).resolves.toBeUndefined();
await expect(client.index("x").ensure({ primaryKey: "id", settings: { searchableAttributes: ["t"] } })).resolves.toBeUndefined();
expect(updateSettings).toHaveBeenCalledOnce();
});
it("waits for create and settings tasks before reporting the index ready", async () => {
const waits: number[] = [];
const factory: MeiliFactory = () => ({
async createIndex() {
return { taskUid: 11 };
},
async waitForTask(taskUid) {
waits.push(taskUid);
return { status: "succeeded", error: null };
},
index() {
return {
async updateSettings() {
return { taskUid: 12 };
},
async search() {
return { hits: [] };
},
async addDocuments() {},
async deleteDocuments() {},
};
},
async health() {
return { status: "available" };
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
await client.index("x").ensure({ primaryKey: "id", settings: { filterableAttributes: ["tenantId"] } });
expect(waits).toEqual([11, 12]);
});
it("accepts an asynchronously reported duplicate index and still confirms settings", async () => {
const factory: MeiliFactory = () => ({
async createIndex() {
return { taskUid: 21 };
},
async waitForTask(taskUid) {
if (taskUid === 21) {
return { status: "failed", error: { code: "index_already_exists", message: "Index already exists." } };
}
return { status: "succeeded", error: null };
},
index() {
return {
async updateSettings() {
return { taskUid: 22 };
},
async search() {
return { hits: [] };
},
async addDocuments() {},
async deleteDocuments() {},
};
},
async health() {
return { status: "available" };
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
await expect(client.index("x").ensure({ primaryKey: "id", settings: { filterableAttributes: ["tenantId"] } })).resolves.toBeUndefined();
});
it("propagates a failed settings task", async () => {
const factory: MeiliFactory = () => ({
async createIndex() {
return { taskUid: 31 };
},
async waitForTask(taskUid) {
return taskUid === 31
? { status: "succeeded", error: null }
: { status: "failed", error: { code: "invalid_settings_filterable_attributes", message: "Invalid settings." } };
},
index() {
return {
async updateSettings() {
return { taskUid: 32 };
},
async search() {
return { hits: [] };
},
async addDocuments() {},
async deleteDocuments() {},
};
},
async health() {
return { status: "available" };
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
await expect(client.index("x").ensure({ primaryKey: "id", settings: { filterableAttributes: ["tenantId"] } })).rejects.toMatchObject({
code: "invalid_settings_filterable_attributes",
taskUid: 32,
});
});
it("rejects malformed asynchronous task responses", async () => {
const factory: MeiliFactory = () => ({
async createIndex() {
return { taskUid: "not-a-number" };
},
index() {
return {
async updateSettings() {},
async search() {
return { hits: [] };
},
async addDocuments() {},
async deleteDocuments() {},
};
},
async health() {
return { status: "available" };
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
await expect(client.index("x").ensure({ primaryKey: "id", settings: {} })).rejects.toThrow(/invalid taskUid/);
});
});
describe("IndexHandle.ensure — settings mapping", () => {
@@ -209,7 +329,7 @@ describe("IndexHandle.deleteByFilter", () => {
await handle.deleteByFilter('tenantId = "t1"');
const docs = state.indexes.get("kb")?.documents;
const docs = state.indexes.get(toPhysicalSearchIndexUid("kb"))?.documents;
expect(docs?.has("a")).toBe(false);
expect(docs?.has("b")).toBe(true);
});
@@ -262,9 +382,7 @@ describe("IndexHandle.deleteByFilter", () => {
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
await expect(client.index("kb").deleteByFilter('tenantId = "t1"')).rejects.toThrow(
/does not support deleteByFilter/
);
await expect(client.index("kb").deleteByFilter('tenantId = "t1"')).rejects.toThrow(/does not support deleteByFilter/);
});
it("rethrows an error from deleteDocuments that is not a 'filter unsupported' signal", async () => {
@@ -286,9 +404,7 @@ describe("IndexHandle.deleteByFilter", () => {
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
await expect(client.index("kb").deleteByFilter('tenantId = "t1"')).rejects.toThrow(
/backend exploded/
);
await expect(client.index("kb").deleteByFilter('tenantId = "t1"')).rejects.toThrow(/backend exploded/);
});
});
@@ -298,7 +414,8 @@ describe("in-memory fixture behaviour relied on by worker integration tests", ()
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
const res = await client.index("lazy").search("", { limit: 10 });
expect(res.hits).toEqual([]);
expect(state.indexes.has("lazy")).toBe(true);
expect(state.indexes.has(toPhysicalSearchIndexUid("lazy"))).toBe(true);
expect(state.indexes.has("lazy")).toBe(false);
});
it("matches documents by terms inside array-valued fields", async () => {
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { createSearchClient } from "./client.js";
import { toPhysicalSearchIndexUid } from "./index-name.js";
import { createInMemoryMeili } from "./testing.js";
describe("createSearchClient", () => {
@@ -25,11 +26,18 @@ describe("createSearchClient", () => {
expect(results.hits.map((hit) => hit.document.id)).toEqual(["a"]);
expect(results.estimatedTotalHits).toBe(1);
const faceted = await handle.search("", { filter: 'tenantId = "t1"', limit: 0, facets: ["tenantId"] });
expect(faceted).toMatchObject({
hits: [],
facetDistribution: { tenantId: { t1: 1 } },
});
await handle.delete(["a"]);
const after = await handle.search("Onboarding", { filter: 'tenantId = "t1"', limit: 10 });
expect(after.hits).toHaveLength(0);
expect(state.indexes.get("kb-articles")?.settings).toMatchObject({ searchableAttributes: ["title"] });
expect(state.indexes.get(toPhysicalSearchIndexUid("kb-articles"))?.settings).toMatchObject({ searchableAttributes: ["title"] });
expect(state.indexes.has("kb-articles")).toBe(false);
});
it("returns health = available from a healthy backend", async () => {
@@ -12,6 +12,8 @@
import { createRequire } from "node:module";
import { toPhysicalSearchIndexUid } from "./index-name.js";
const requireFromHere = createRequire(import.meta.url);
export type SearchDocument = Record<string, unknown> & { id: string | number };
@@ -25,6 +27,7 @@ export interface SearchHit<TDocument extends SearchDocument = SearchDocument> {
export interface SearchHits<TDocument extends SearchDocument = SearchDocument> {
readonly hits: readonly SearchHit<TDocument>[];
readonly estimatedTotalHits: number;
readonly facetDistribution?: Readonly<Record<string, Readonly<Record<string, number>>>>;
readonly processingTimeMs: number;
readonly limit?: number;
readonly offset?: number;
@@ -35,6 +38,7 @@ export interface IndexSearchOptions {
readonly sort?: readonly string[];
readonly limit?: number;
readonly offset?: number;
readonly facets?: readonly string[];
readonly attributesToHighlight?: readonly string[];
readonly attributesToRetrieve?: readonly string[];
}
@@ -62,7 +66,9 @@ export interface IndexHandle<TDocument extends SearchDocument = SearchDocument>
}
export interface SearchClient {
index<TDocument extends SearchDocument = SearchDocument>(name: string): IndexHandle<TDocument>;
/** Accepts a logical registry name. The adapter applies the estate-wide
* physical UID prefix before touching Meilisearch. */
index<TDocument extends SearchDocument = SearchDocument>(logicalName: string): IndexHandle<TDocument>;
health(): Promise<{ status: "available" | "unavailable" }>;
}
@@ -83,15 +89,23 @@ interface MeilisearchLike {
index(uid: string): MeilisearchIndexLike;
createIndex?(uid: string, options: { primaryKey: string }): Promise<unknown>;
getIndex?(uid: string): Promise<MeilisearchIndexLike>;
waitForTask?(
taskUid: number,
options?: { timeOutMs?: number; intervalMs?: number }
): Promise<{ status?: string; error?: { code?: string; message?: string } | null }>;
health(): Promise<{ status: string } | { status: "available" }>;
isHealthy?(): Promise<boolean>;
}
interface MeilisearchIndexLike {
updateSettings(input: Record<string, unknown>): Promise<unknown>;
search(query: string, options: Record<string, unknown>): Promise<{
search(
query: string,
options: Record<string, unknown>
): Promise<{
hits: readonly (Record<string, unknown> & { id: string | number })[];
estimatedTotalHits?: number;
facetDistribution?: Record<string, Record<string, number>>;
processingTimeMs?: number;
limit?: number;
offset?: number;
@@ -121,11 +135,8 @@ export function createSearchClient(options: CreateSearchClientOptions): SearchCl
const meili = factory({ host: options.url, apiKey: options.apiKey, timeout: options.timeout });
return {
index<TDocument extends SearchDocument = SearchDocument>(name: string): IndexHandle<TDocument> {
if (typeof name !== "string" || name.length === 0) {
throw new Error("Index name must be a non-empty string.");
}
return buildIndexHandle<TDocument>(meili, name);
index<TDocument extends SearchDocument = SearchDocument>(logicalName: string): IndexHandle<TDocument> {
return buildIndexHandle<TDocument>(meili, toPhysicalSearchIndexUid(logicalName));
},
async health() {
const result = await meili.health();
@@ -135,27 +146,30 @@ export function createSearchClient(options: CreateSearchClientOptions): SearchCl
};
}
function buildIndexHandle<TDocument extends SearchDocument>(meili: MeilisearchLike, name: string): IndexHandle<TDocument> {
function buildIndexHandle<TDocument extends SearchDocument>(meili: MeilisearchLike, physicalUid: string): IndexHandle<TDocument> {
return {
async ensure({ primaryKey, settings }) {
if (typeof meili.createIndex === "function") {
try {
await meili.createIndex(name, { primaryKey });
const task = await meili.createIndex(physicalUid, { primaryKey });
await waitForMeiliTask(meili, task, `create index ${physicalUid}`);
} catch (error) {
if (!isIndexAlreadyExistsError(error)) {
throw error;
}
}
}
const handle = meili.index(name);
await handle.updateSettings(settingsToMeiliInput(settings));
const handle = meili.index(physicalUid);
const task = await handle.updateSettings(settingsToMeiliInput(settings));
await waitForMeiliTask(meili, task, `update settings for ${physicalUid}`);
},
async search(query, options) {
const handle = meili.index(name);
const handle = meili.index(physicalUid);
const raw = await handle.search(query, toMeiliSearchOptions(options));
return {
hits: raw.hits.map((hit) => ({ document: hit as TDocument })),
estimatedTotalHits: raw.estimatedTotalHits ?? raw.hits.length,
...(raw.facetDistribution ? { facetDistribution: raw.facetDistribution } : {}),
processingTimeMs: raw.processingTimeMs ?? 0,
...(typeof raw.limit === "number" ? { limit: raw.limit } : {}),
...(typeof raw.offset === "number" ? { offset: raw.offset } : {}),
@@ -163,16 +177,18 @@ function buildIndexHandle<TDocument extends SearchDocument>(meili: MeilisearchLi
},
async upsert(documents) {
if (documents.length === 0) return;
const handle = meili.index(name);
await handle.addDocuments(documents as readonly Record<string, unknown>[]);
const handle = meili.index(physicalUid);
const task = await handle.addDocuments(documents as readonly Record<string, unknown>[]);
await waitForMeiliTask(meili, task, `upsert documents in ${physicalUid}`);
},
async delete(documentIds) {
if (documentIds.length === 0) return;
const handle = meili.index(name);
await handle.deleteDocuments(documentIds);
const handle = meili.index(physicalUid);
const task = await handle.deleteDocuments(documentIds);
await waitForMeiliTask(meili, task, `delete documents from ${physicalUid}`);
},
async deleteByFilter(filter) {
const handle = meili.index(name);
const handle = meili.index(physicalUid);
// Meilisearch 0.45 exposes `deleteDocuments({ filter })`; older
// builds used `deleteDocuments_filter`. Detect both.
const withFilter = handle as MeilisearchIndexLike & {
@@ -180,14 +196,16 @@ function buildIndexHandle<TDocument extends SearchDocument>(meili: MeilisearchLi
};
if (typeof withFilter.deleteDocuments === "function") {
try {
await withFilter.deleteDocuments({ filter });
const task = await withFilter.deleteDocuments({ filter });
await waitForMeiliTask(meili, task, `delete filtered documents from ${physicalUid}`);
return;
} catch (error) {
if (!isFilterDeleteUnsupportedError(error)) throw error;
}
}
if (typeof handle.deleteDocumentsFilter === "function") {
await handle.deleteDocumentsFilter({ filter });
const task = await handle.deleteDocumentsFilter({ filter });
await waitForMeiliTask(meili, task, `delete filtered documents from ${physicalUid}`);
return;
}
throw new Error("Search adapter does not support deleteByFilter.");
@@ -195,6 +213,32 @@ function buildIndexHandle<TDocument extends SearchDocument>(meili: MeilisearchLi
};
}
async function waitForMeiliTask(meili: MeilisearchLike, queued: unknown, operation: string): Promise<void> {
const taskUid = readTaskUid(queued);
if (taskUid === undefined) return;
if (typeof meili.waitForTask !== "function") {
throw new Error(`Meilisearch cannot confirm task ${taskUid} for ${operation}.`);
}
const task = await meili.waitForTask(taskUid, { timeOutMs: 60_000, intervalMs: 50 });
if (task.status === "succeeded") return;
const error = new Error(task.error?.message ?? `Meilisearch task ${taskUid} did not succeed for ${operation}.`) as Error & {
code?: string;
taskUid?: number;
};
error.code = task.error?.code ?? (task.status === "canceled" ? "task_canceled" : "task_failed");
error.taskUid = taskUid;
throw error;
}
function readTaskUid(task: unknown): number | undefined {
if (!task || typeof task !== "object" || !("taskUid" in task)) return undefined;
const taskUid = (task as { taskUid?: unknown }).taskUid;
if (typeof taskUid !== "number" || !Number.isInteger(taskUid) || taskUid < 0) {
throw new Error("Meilisearch returned an invalid taskUid.");
}
return taskUid;
}
function settingsToMeiliInput(settings: IndexSettingsInput): Record<string, unknown> {
const out: Record<string, unknown> = {};
if (settings.searchableAttributes) out.searchableAttributes = [...settings.searchableAttributes];
@@ -216,6 +260,7 @@ function toMeiliSearchOptions(options: IndexSearchOptions): Record<string, unkno
if (options.sort) out.sort = [...options.sort];
if (typeof options.limit === "number") out.limit = options.limit;
if (typeof options.offset === "number") out.offset = options.offset;
if (options.facets) out.facets = [...options.facets];
if (options.attributesToHighlight) out.attributesToHighlight = [...options.attributesToHighlight];
if (options.attributesToRetrieve) out.attributesToRetrieve = [...options.attributesToRetrieve];
return out;
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { createSearchClient } from "./client.js";
import { createSearchIndex } from "./index-helper.js";
import { toPhysicalSearchIndexUid } from "./index-name.js";
import type { SearchIndexSchema } from "./schemas/index.js";
import { createInMemoryMeili } from "./testing.js";
@@ -27,7 +28,7 @@ describe("createSearchIndex — schema settings merge", () => {
await createSearchIndex({ client, schema: schemaWithSynonyms });
const settings = state.indexes.get("syn-index")?.settings;
const settings = state.indexes.get(toPhysicalSearchIndexUid("syn-index"))?.settings;
expect(settings).toMatchObject({
searchableAttributes: ["title"],
stopWords: ["the", "a"],
@@ -53,7 +54,7 @@ describe("createSearchIndex — schema settings merge", () => {
},
});
expect(state.indexes.get("syn-index")?.settings).toMatchObject({
expect(state.indexes.get(toPhysicalSearchIndexUid("syn-index"))?.settings).toMatchObject({
searchableAttributes: ["body"],
filterableAttributes: ["tenantId", "status"],
sortableAttributes: ["updatedAt"],
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { createSearchClient } from "./client.js";
import { createSearchIndex, IndexSchemaValidationError, validateIndexSchema } from "./index-helper.js";
import { createSearchIndex, IndexSchemaValidationError, provisionSearchIndexes, validateIndexSchema } from "./index-helper.js";
import { toPhysicalSearchIndexUid } from "./index-name.js";
import type { SearchIndexSchema } from "./schemas/index.js";
import { kbArticlesIndex } from "./schemas/index.js";
import { createInMemoryMeili } from "./testing.js";
@@ -31,17 +32,11 @@ describe("validateIndexSchema", () => {
});
it("rejects schemas where tenantId is not filterable", () => {
expect(() =>
validateIndexSchema(baseSchema({ filterableAttributes: ["status"] }))
).toThrow(/tenantId/);
expect(() => validateIndexSchema(baseSchema({ filterableAttributes: ["status"] }))).toThrow(/tenantId/);
});
it("rejects schemas where tenantId is not in allowedDocumentFields", () => {
expect(() =>
validateIndexSchema(
baseSchema({ allowedDocumentFields: ["id", "title"] })
)
).toThrow(/allowedDocumentFields/);
expect(() => validateIndexSchema(baseSchema({ allowedDocumentFields: ["id", "title"] }))).toThrow(/allowedDocumentFields/);
});
});
@@ -51,7 +46,7 @@ describe("createSearchIndex", () => {
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
const handle = await createSearchIndex({ client, schema: kbArticlesIndex });
expect(handle).toBeDefined();
const idx = state.indexes.get(kbArticlesIndex.name);
const idx = state.indexes.get(toPhysicalSearchIndexUid(kbArticlesIndex.name));
expect(idx).toBeDefined();
expect(idx?.settings).toMatchObject({
searchableAttributes: kbArticlesIndex.searchableAttributes,
@@ -85,6 +80,21 @@ describe("createSearchIndex", () => {
schema: kbArticlesIndex,
settingsOverride: { stopWords: ["the", "a"] },
});
expect(state.indexes.get(kbArticlesIndex.name)?.settings).toMatchObject({ stopWords: ["the", "a"] });
expect(state.indexes.get(toPhysicalSearchIndexUid(kbArticlesIndex.name))?.settings).toMatchObject({ stopWords: ["the", "a"] });
});
});
describe("provisionSearchIndexes", () => {
it("creates and configures every supplied schema", async () => {
const { factory, state } = createInMemoryMeili();
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
const schemas = [baseSchema({ name: "first" }), baseSchema({ name: "second" })];
await provisionSearchIndexes({ client, schemas });
expect([...state.indexes.keys()]).toEqual([toPhysicalSearchIndexUid("first"), toPhysicalSearchIndexUid("second")]);
for (const index of state.indexes.values()) {
expect(index.settings).toMatchObject({ filterableAttributes: ["tenantId"] });
}
});
});
@@ -30,10 +30,7 @@ export function validateIndexSchema(schema: SearchIndexSchema): void {
throw new IndexSchemaValidationError("Search index schema requires a non-empty name.", "EMPTY_NAME");
}
if (typeof schema.primaryKey !== "string" || schema.primaryKey.length === 0) {
throw new IndexSchemaValidationError(
`Search index "${schema.name}" must declare a non-empty primaryKey.`,
"EMPTY_PRIMARY_KEY"
);
throw new IndexSchemaValidationError(`Search index "${schema.name}" must declare a non-empty primaryKey.`, "EMPTY_PRIMARY_KEY");
}
if (!Array.isArray(schema.filterableAttributes) || !schema.filterableAttributes.includes("tenantId")) {
throw new IndexSchemaValidationError(
@@ -56,9 +53,12 @@ export interface CreateSearchIndexInput {
readonly settingsOverride?: Partial<IndexSettingsInput>;
}
export async function createSearchIndex<TDocument extends SearchDocument = SearchDocument>(
input: CreateSearchIndexInput
): Promise<IndexHandle<TDocument>> {
export interface ProvisionSearchIndexesInput {
readonly client: SearchClient;
readonly schemas: readonly SearchIndexSchema[];
}
export async function createSearchIndex<TDocument extends SearchDocument = SearchDocument>(input: CreateSearchIndexInput): Promise<IndexHandle<TDocument>> {
validateIndexSchema(input.schema);
const settings = mergeSettings(input.schema, input.settingsOverride);
const handle = input.client.index<TDocument>(input.schema.name);
@@ -66,6 +66,17 @@ export async function createSearchIndex<TDocument extends SearchDocument = Searc
return handle;
}
/**
* Provision the complete registry before a worker accepts jobs. Waiting for
* every create/settings task keeps filtered tenant deletes from racing index
* creation or the mandatory `tenantId` filter setting.
*/
export async function provisionSearchIndexes(input: ProvisionSearchIndexesInput): Promise<void> {
for (const schema of input.schemas) {
await createSearchIndex({ client: input.client, schema });
}
}
function mergeSettings(schema: SearchIndexSchema, override: Partial<IndexSettingsInput> | undefined): IndexSettingsInput {
const base: IndexSettingsInput = {
searchableAttributes: schema.searchableAttributes,
@@ -0,0 +1,61 @@
import { describe, expect, it, vi } from "vitest";
import { createSearchClient, type MeiliFactory } from "./client.js";
import { SEARCH_INDEX_UID_PREFIX, toPhysicalSearchIndexUid } from "./index-name.js";
describe("physical search index UIDs", () => {
it("maps logical names into the HiveGrid estate namespace", () => {
expect(toPhysicalSearchIndexUid("projects")).toBe("hivegrid-projects");
expect(SEARCH_INDEX_UID_PREFIX).toBe("hivegrid-");
});
it("uses only the prefixed UID for every raw Meilisearch operation", async () => {
const createIndex = vi.fn(async () => undefined);
const updateSettings = vi.fn(async () => undefined);
const search = vi.fn(async () => ({ hits: [] }));
const addDocuments = vi.fn(async () => undefined);
const deleteDocuments = vi.fn(async () => undefined);
const rawIndex = vi.fn((_uid: string) => ({ updateSettings, search, addDocuments, deleteDocuments }));
const factory: MeiliFactory = () => ({
createIndex,
index: rawIndex,
async health() {
return { status: "available" };
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
const handle = client.index("projects");
await handle.ensure({ primaryKey: "id", settings: {} });
await handle.search("roof", {});
await handle.upsert([{ id: "project-1" }]);
await handle.delete(["project-1"]);
await handle.deleteByFilter('tenantId = "tenant-1"');
expect(createIndex).toHaveBeenCalledWith("hivegrid-projects", { primaryKey: "id" });
expect(rawIndex).toHaveBeenCalledTimes(5);
expect(rawIndex.mock.calls.every(([uid]) => uid === "hivegrid-projects")).toBe(true);
expect(rawIndex).not.toHaveBeenCalledWith("projects");
});
it("rejects physical UIDs at the logical client boundary before touching Meilisearch", () => {
const rawIndex = vi.fn((_uid: string) => ({
async updateSettings() {},
async search() {
return { hits: [] };
},
async addDocuments() {},
async deleteDocuments() {},
}));
const factory: MeiliFactory = () => ({
index: rawIndex,
async health() {
return { status: "available" };
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
expect(() => client.index("hivegrid-projects")).toThrow(/logical name without the "hivegrid-" physical prefix/);
expect(rawIndex).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,21 @@
/**
* Estate-wide namespace for physical Meilisearch index UIDs.
*
* Registry schemas and outbox payloads intentionally keep logical names
* such as `projects`. Only the adapter boundary turns them into physical
* UIDs such as `hivegrid-projects`.
*/
export const SEARCH_INDEX_UID_PREFIX = "hivegrid-" as const;
export function toPhysicalSearchIndexUid(logicalName: string): string {
if (typeof logicalName !== "string" || logicalName.length === 0) {
throw new Error("Index name must be a non-empty string.");
}
if (logicalName !== logicalName.trim()) {
throw new Error("Search index logical names must not contain leading or trailing whitespace.");
}
if (logicalName.startsWith(SEARCH_INDEX_UID_PREFIX)) {
throw new Error(`SearchClient.index expects a logical name without the "${SEARCH_INDEX_UID_PREFIX}" physical prefix.`);
}
return `${SEARCH_INDEX_UID_PREFIX}${logicalName}`;
}
@@ -26,19 +26,24 @@ export type {
SearchHits,
} from "./client.js";
export { createSearchIndex, IndexSchemaValidationError, validateIndexSchema } from "./index-helper.js";
export type { CreateSearchIndexInput } from "./index-helper.js";
export { SEARCH_INDEX_UID_PREFIX, toPhysicalSearchIndexUid } from "./index-name.js";
export { bulkIndex, deleteFromIndex, health, searchInIndex, searchWithFallback, TenantScopeError } from "./query.js";
export type { BulkIndexInput, DeleteFromIndexInput, SearchFallback, SearchInIndexInput, SearchWithFallbackInput } from "./query.js";
export { createSearchIndex, IndexSchemaValidationError, provisionSearchIndexes, validateIndexSchema } from "./index-helper.js";
export type { CreateSearchIndexInput, ProvisionSearchIndexesInput } from "./index-helper.js";
export { bulkIndex, deleteFromIndex, deleteTenantFromIndex, health, searchInIndex, searchWithFallback, TenantScopeError } from "./query.js";
export type { BulkIndexInput, DeleteFromIndexInput, DeleteTenantFromIndexInput, SearchFallback, SearchInIndexInput, SearchWithFallbackInput } from "./query.js";
export {
ALL_SEARCH_INDEXES,
BULK_REINDEX_SUPPORTED_INDEXES,
BULK_REINDEX_SUPPORTED_INDEX_NAMES,
chatMessagesIndex,
crmContactsIndex,
filesIndex,
getSearchIndexSchema,
hrDirectoryIndex,
hrLocationsIndex,
kbArticlesIndex,
projectsIndex,
tasksIndex,
@@ -46,13 +51,7 @@ export {
} from "./schemas/index.js";
export type { SearchIndexSchema } from "./schemas/index.js";
export {
getIndexedEntitiesForPermissions,
getIndexedEntity,
indexedEntities,
listIndexedEntities,
validateIndexedEntities,
} from "./indexed-entities.js";
export { getIndexedEntitiesForPermissions, getIndexedEntity, indexedEntities, listIndexedEntities, validateIndexedEntities } from "./indexed-entities.js";
export type { IndexedEntity, IndexedEntityConfig, IndexedEntityKey, IndexedEntityRegistry } from "./indexed-entities.js";
export { sanitizeDocument } from "./sanitize.js";
@@ -20,6 +20,12 @@ describe("indexedEntities registry", () => {
const keys = listIndexedEntities().map((entity) => entity.key);
expect(keys).toContain("file");
expect(getIndexedEntity("file")).toMatchObject({ key: "file", table: "File", index: "files", permission: "files.read_all" });
expect(getIndexedEntity("chatMessage")).toMatchObject({
key: "chatMessage",
table: "TeamChatMessage",
index: "chat-messages",
permission: "chat.read_all_channels",
});
// CRM contacts (R-P6): one entry covers both private persons and organisations.
expect(keys).toContain("contact");
expect(getIndexedEntity("contact")).toMatchObject({
@@ -28,6 +34,18 @@ describe("indexedEntities registry", () => {
index: "crm-contacts",
permission: "crm.read_all",
});
expect(getIndexedEntity("employee")).toMatchObject({
key: "employee",
table: "HrEmployeeProfile",
index: "hr-directory",
permission: "hr.read_all",
});
expect(getIndexedEntity("file")).toMatchObject({
key: "file",
table: "File",
index: "files",
permission: "files.read_all",
});
});
it("lists registered entities together with their key", () => {
@@ -38,10 +56,7 @@ describe("indexedEntities registry", () => {
it("permission-gates entities for the caller's granted permissions (M057)", () => {
expect(getIndexedEntitiesForPermissions(["crm.read"], fixture).map((entity) => entity.key)).toEqual(["contact"]);
expect(getIndexedEntitiesForPermissions(new Set(["crm.read", "sales.read"]), fixture).map((entity) => entity.key)).toEqual([
"contact",
"deal",
]);
expect(getIndexedEntitiesForPermissions(new Set(["crm.read", "sales.read"]), fixture).map((entity) => entity.key)).toEqual(["contact", "deal"]);
expect(getIndexedEntitiesForPermissions([], fixture)).toEqual([]);
});
@@ -41,6 +41,16 @@ export type IndexedEntity = IndexedEntityConfig & { key: string };
* grouping + deep-link routing). Empty until fachmodule register their entities.
*/
export const indexedEntities = {
// Team chat (AK-P15b). Normal member search is executed against PostgreSQL
// with active-channel membership in the same RLS transaction. The central
// index is intentionally gated to tenant-wide chat auditors so a coarse
// global permission can never expose messages from an unreadable channel.
chatMessage: {
table: "TeamChatMessage",
index: "chat-messages",
searchable: ["body"],
permission: "chat.read_all_channels",
},
// Files (AK-P4a). Tenant-scoped; only files the user may read_all surface in
// global search (owner/link-scoped read_own visibility is enforced at the
// route layer, not here).
@@ -97,6 +107,16 @@ export const indexedEntities = {
searchable: ["projectNumber", "name", "description", "type", "source"],
permission: "projects.read_all",
},
// Personnel directory (R-UX3). Only non-sensitive profile fields are
// searchable. `hr.read_own` is applied as a stricter self/direct-report
// fallback by the global-search service; tenant-wide results require the
// registry permission below.
employee: {
table: "HrEmployeeProfile",
index: "hr-directory",
searchable: ["name", "email", "position", "team"],
permission: "hr.read_all",
},
user: {
table: "TenantUser",
index: "users",
@@ -177,7 +177,7 @@ describe("searchInIndex — primary-key restoration", () => {
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" } }],
hits: [{ document: { id: "hg_7431_s_726177", tenantId: "t1", [ORIGINAL_PRIMARY_KEY_FIELD]: "raw" } }],
estimatedTotalHits: 1,
processingTimeMs: 0,
});
@@ -191,7 +191,7 @@ describe("searchInIndex — primary-key restoration", () => {
hits: [
{
document: {
id: "t1:raw",
id: "hg_7431_s_726177",
tenantId: "t1",
title: "X",
[ORIGINAL_PRIMARY_KEY_FIELD]: { nested: true },
@@ -202,7 +202,7 @@ describe("searchInIndex — primary-key restoration", () => {
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(res.hits[0]?.document).toEqual({ id: "hg_7431_s_726177", tenantId: "t1", title: "X" });
expect(ORIGINAL_PRIMARY_KEY_FIELD in (res.hits[0]?.document ?? {})).toBe(false);
});
});
@@ -1,9 +1,11 @@
import { describe, expect, it, vi } from "vitest";
import { createSearchClient, type SearchHits } from "./client.js";
import { createSearchClient, type MeiliFactory, type SearchClient, type SearchHits } from "./client.js";
import { createSearchIndex } from "./index-helper.js";
import { toPhysicalSearchIndexUid } from "./index-name.js";
import {
bulkIndex,
deleteFromIndex,
deleteTenantFromIndex,
health,
searchInIndex,
searchWithFallback,
@@ -63,19 +65,25 @@ describe("searchInIndex", () => {
});
it("escapes special characters in the tenant id", async () => {
const { meili, client } = await setup();
const handle = meili.factory({ host: "http://memory" }).index(kbArticlesIndex.name);
const searchSpy = vi.spyOn(handle, "search");
// Replace the proxied index in the in-memory state via a fresh call;
// easier: just inspect via the real-client path with a custom factory.
const search = vi.fn(async () => ({ hits: [] }));
const factory: MeiliFactory = () => ({
index() {
return {
async updateSettings() {},
search,
async addDocuments() {},
async deleteDocuments() {},
};
},
async health() {
return { status: "available" };
},
});
const client = createSearchClient({ url: "http://memory", meiliFactory: factory });
const tenantId = 'evil " OR tenantId = "other';
await searchInIndex({ client, schema: kbArticlesIndex, tenantId, query: "x" });
// The internal handle was used; assert escape by re-running via testing fake directly.
searchSpy.mockRestore();
// The filter sent should not break out of the quotes.
// (We can't intercept easily without rewiring; this test is here to
// pin the escape behavior at the build-string level too.)
expect(tenantId).toContain('"');
expect(search).toHaveBeenCalledWith("x", expect.objectContaining({ filter: 'tenantId = "evil \\" OR tenantId = \\"other"' }));
});
it("AND-merges caller-supplied extra filters", async () => {
@@ -156,7 +164,51 @@ describe("bulkIndex / deleteFromIndex", () => {
expect.objectContaining({ id: "shared-1", tenantId: "tenant-b", title: "Tenant B onboarding" }),
]);
expect(meili.state.indexes.get(kbArticlesIndex.name)?.documents.size).toBe(2);
expect(meili.state.indexes.get(toPhysicalSearchIndexUid(kbArticlesIndex.name))?.documents.size).toBe(2);
const scopedIds = [...(meili.state.indexes.get(toPhysicalSearchIndexUid(kbArticlesIndex.name))?.documents.keys() ?? [])].map(String);
expect(scopedIds).toHaveLength(2);
expect(new Set(scopedIds).size).toBe(2);
expect(scopedIds.every((id) => /^hg_[0-9a-f]+_[ns]_[0-9a-f]+$/u.test(id))).toBe(true);
expect(meili.state.indexes.has(kbArticlesIndex.name)).toBe(false);
});
it("encodes arbitrary tenant and document ids into Meilisearch-compatible identifiers", async () => {
const { meili, client } = await setup();
const tenantId = "tenant / ü?";
const documentId = "document:1/ä";
await bulkIndex({
client,
schema: kbArticlesIndex,
tenantId,
documents: [{ id: documentId, tenantId, title: "Encoded identifier" }],
});
const index = meili.state.indexes.get(toPhysicalSearchIndexUid(kbArticlesIndex.name));
const scopedIds = [...(index?.documents.keys() ?? [])].map(String);
expect(scopedIds).toHaveLength(1);
expect(scopedIds[0]).toMatch(/^hg_[0-9a-f]+_[ns]_[0-9a-f]+$/u);
await deleteFromIndex({ client, schema: kbArticlesIndex, tenantId, documentIds: [documentId] });
expect(index?.documents.size).toBe(0);
});
it("keeps string and numeric domain identifiers distinct", async () => {
const { meili, client } = await setup();
const tenantId = "t1";
await bulkIndex({
client,
schema: kbArticlesIndex,
tenantId,
documents: [
{ id: "1", tenantId, title: "String identifier" },
{ id: 1, tenantId, title: "Numeric identifier" },
],
});
const scopedIds = [...(meili.state.indexes.get(toPhysicalSearchIndexUid(kbArticlesIndex.name))?.documents.keys() ?? [])].map(String);
expect(scopedIds.sort()).toEqual(["hg_7431_n_31", "hg_7431_s_31"]);
});
it("does not delete another tenant's document with the same domain id", async () => {
@@ -204,6 +256,53 @@ describe("bulkIndex / deleteFromIndex", () => {
deleteFromIndex({ client, schema: kbArticlesIndex, tenantId: "", documentIds: ["x"] })
).rejects.toThrow(TenantScopeError);
});
it("deletes one complete tenant slice and leaves other tenants untouched", async () => {
const { meili, client } = await setup();
await bulkIndex({
client,
schema: kbArticlesIndex,
tenantId: "tenant-a",
documents: [{ id: "shared", tenantId: "tenant-a", title: "Tenant A" }],
});
await bulkIndex({
client,
schema: kbArticlesIndex,
tenantId: "tenant-b",
documents: [{ id: "shared", tenantId: "tenant-b", title: "Tenant B" }],
});
await deleteTenantFromIndex({ client, schema: kbArticlesIndex, tenantId: "tenant-a" });
await expect(searchInIndex({ client, schema: kbArticlesIndex, tenantId: "tenant-a", query: "Tenant" })).resolves.toMatchObject({ hits: [] });
await expect(searchInIndex({ client, schema: kbArticlesIndex, tenantId: "tenant-b", query: "Tenant" })).resolves.toMatchObject({
hits: [{ document: expect.objectContaining({ id: "shared", tenantId: "tenant-b" }) }],
});
expect(meili.state.indexes.has(toPhysicalSearchIndexUid(kbArticlesIndex.name))).toBe(true);
expect(meili.state.indexes.has(kbArticlesIndex.name)).toBe(false);
});
it("escapes tenant ids before deleting a complete tenant slice", async () => {
const deleteByFilter = vi.fn(async () => undefined);
const client: SearchClient = {
index: vi.fn(() => ({
async ensure() {},
async search() {
return { hits: [], estimatedTotalHits: 0, processingTimeMs: 0 };
},
async upsert() {},
async delete() {},
deleteByFilter,
})),
async health() {
return { status: "available" };
},
};
await deleteTenantFromIndex({ client, schema: kbArticlesIndex, tenantId: 'tenant\\" OR tenantId = "other' });
expect(deleteByFilter).toHaveBeenCalledWith('tenantId = "tenant\\\\\\" OR tenantId = \\"other"');
});
});
describe("searchWithFallback", () => {
@@ -15,6 +15,8 @@ import { sanitizeDocument } from "./sanitize.js";
import type { SearchIndexSchema } from "./schemas/index.js";
const ORIGINAL_PRIMARY_KEY_FIELD = "__hivegridOriginalPrimaryKey";
const SCOPED_PRIMARY_KEY_PREFIX = "hg_";
const UTF8_ENCODER = new TextEncoder();
export class TenantScopeError extends Error {
override readonly name = "TenantScopeError";
@@ -71,6 +73,7 @@ export async function bulkIndex<TDocument extends SearchDocument = SearchDocumen
): Promise<void> {
assertTenantId(input.tenantId);
if (input.documents.length === 0) return;
const scopedPrimaryKeyPrefix = buildScopedPrimaryKeyPrefix(input.tenantId);
const sanitized = input.documents.map((doc) => {
if ("tenantId" in doc && doc.tenantId !== input.tenantId) {
throw new TenantScopeError(
@@ -85,7 +88,7 @@ export async function bulkIndex<TDocument extends SearchDocument = SearchDocumen
"INVALID_TENANT"
);
}
return scopeDocumentPrimaryKey(input.schema, input.tenantId, projected);
return scopeDocumentPrimaryKey(input.schema, scopedPrimaryKeyPrefix, projected);
});
const handle = input.client.index<TDocument>(input.schema.name);
await handle.upsert(sanitized as readonly TDocument[]);
@@ -102,7 +105,21 @@ export async function deleteFromIndex(input: DeleteFromIndexInput): Promise<void
assertTenantId(input.tenantId);
if (input.documentIds.length === 0) return;
const handle = input.client.index(input.schema.name);
await handle.delete(input.documentIds.map((documentId) => buildScopedPrimaryKey(input.tenantId, documentId)));
const scopedPrimaryKeyPrefix = buildScopedPrimaryKeyPrefix(input.tenantId);
await handle.delete(input.documentIds.map((documentId) => buildScopedPrimaryKey(scopedPrimaryKeyPrefix, documentId)));
}
export interface DeleteTenantFromIndexInput {
readonly client: SearchClient;
readonly schema: SearchIndexSchema;
readonly tenantId: string;
}
/** Delete one tenant's complete slice without exposing raw filters to callers. */
export async function deleteTenantFromIndex(input: DeleteTenantFromIndexInput): Promise<void> {
assertTenantId(input.tenantId);
const handle = input.client.index(input.schema.name);
await handle.deleteByFilter(buildFilter(input.tenantId, undefined));
}
export interface SearchFallback<TDocument extends SearchDocument = SearchDocument> {
@@ -160,7 +177,7 @@ function buildFilter(tenantId: string, extra: string | readonly string[] | undef
function scopeDocumentPrimaryKey<TDocument extends SearchDocument>(
schema: SearchIndexSchema,
tenantId: string,
scopedPrimaryKeyPrefix: string,
document: TDocument
): TDocument {
const primaryKey = document[schema.primaryKey];
@@ -169,7 +186,7 @@ function scopeDocumentPrimaryKey<TDocument extends SearchDocument>(
}
return {
...document,
[schema.primaryKey]: buildScopedPrimaryKey(tenantId, primaryKey),
[schema.primaryKey]: buildScopedPrimaryKey(scopedPrimaryKeyPrefix, primaryKey),
[ORIGINAL_PRIMARY_KEY_FIELD]: primaryKey,
} as TDocument;
}
@@ -191,8 +208,25 @@ function restoreDocumentPrimaryKey<TDocument extends SearchDocument>(
} as TDocument;
}
function buildScopedPrimaryKey(tenantId: string, documentId: string | number): string {
return `${encodeURIComponent(tenantId)}:${encodeURIComponent(String(documentId))}`;
function buildScopedPrimaryKeyPrefix(tenantId: string): string {
return `${SCOPED_PRIMARY_KEY_PREFIX}${encodePrimaryKeyPart(tenantId)}_`;
}
function buildScopedPrimaryKey(scopedPrimaryKeyPrefix: string, documentId: string | number): string {
const typeMarker = typeof documentId === "number" ? "n" : "s";
return `${scopedPrimaryKeyPrefix}${typeMarker}_${encodePrimaryKeyPart(String(documentId))}`;
}
/**
* Meilisearch document identifiers only allow ASCII letters, digits, hyphens,
* and underscores. UTF-8 hex is injective for well-formed database identifiers
* while staying inside that alphabet; underscores cannot occur in encoded parts.
*/
function encodePrimaryKeyPart(value: string): string {
const bytes = UTF8_ENCODER.encode(value);
let encoded = "";
for (const byte of bytes) encoded += byte.toString(16).padStart(2, "0");
return encoded;
}
function unique<T>(values: readonly T[]): T[] {
@@ -0,0 +1,12 @@
// @vitest-environment node
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
describe("search RLS artifact", () => {
const sql = readFileSync(new URL("../../../prisma/rls/search-isolation.sql", import.meta.url), "utf8");
it("uses the canonical tenant context set by withTenantRLS", () => {
expect(sql).toContain("current_setting('app.tenant_id', true)");
expect(sql).not.toContain("app.current_tenant_id");
});
});
@@ -0,0 +1,17 @@
import type { SearchIndexSchema } from "./types.js";
/**
* Team-chat messages (AK-P15b). The in-chat search remains authoritative in
* PostgreSQL because channel membership is finer grained than a tenant-wide
* permission. This schema registers the safe, tenant-scoped projection for
* read-all/admin search consumers without indexing mentions or attachments.
*/
export const chatMessagesIndex: SearchIndexSchema = {
name: "chat-messages",
primaryKey: "id",
searchableAttributes: ["body"],
filterableAttributes: ["tenantId", "chatId", "authorUserId", "parentMessageId", "deleted"],
sortableAttributes: ["createdAt", "updatedAt"],
rankingRules: ["words", "typo", "proximity", "attribute", "sort", "exactness"],
allowedDocumentFields: ["id", "tenantId", "chatId", "authorUserId", "parentMessageId", "body", "deleted", "createdAt", "updatedAt"],
};
@@ -1,3 +1,4 @@
import { chatMessagesIndex } from "./chat-messages.js";
import { crmContactsIndex } from "./crm-contacts.js";
import { filesIndex } from "./files.js";
import { hrDirectoryIndex } from "./hr-directory.js";
@@ -8,6 +9,7 @@ import { tasksIndex } from "./tasks.js";
import type { SearchIndexSchema } from "./types.js";
import { usersIndex } from "./users.js";
export { chatMessagesIndex } from "./chat-messages.js";
export { crmContactsIndex } from "./crm-contacts.js";
export { filesIndex } from "./files.js";
export { hrDirectoryIndex } from "./hr-directory.js";
@@ -26,6 +28,7 @@ export type { SearchIndexSchema } from "./types.js";
*/
export const ALL_SEARCH_INDEXES: readonly SearchIndexSchema[] = [
kbArticlesIndex,
chatMessagesIndex,
crmContactsIndex,
usersIndex,
projectsIndex,
@@ -3,7 +3,7 @@ import type { SearchIndexSchema } from "./types.js";
export const projectsIndex: SearchIndexSchema = {
name: "projects",
primaryKey: "id",
searchableAttributes: ["projectNumber", "name", "description", "type", "source"],
searchableAttributes: ["projectNumber", "externalReferences", "name", "description", "type", "source"],
filterableAttributes: ["tenantId", "pipelineId", "stageId", "ownerId", "projectLeadId", "archived"],
sortableAttributes: ["createdAt", "updatedAt", "deadline", "potentialValue", "orderVolume"],
rankingRules: ["words", "typo", "proximity", "attribute", "sort", "exactness"],
@@ -11,6 +11,7 @@ export const projectsIndex: SearchIndexSchema = {
"id",
"tenantId",
"projectNumber",
"externalReferences",
"name",
"description",
"type",
@@ -17,6 +17,8 @@ export interface InMemoryMeiliOptions {
readonly throwOnHealthCheck?: boolean;
readonly throwOnSearch?: boolean;
readonly throwOnIndex?: boolean;
/** Mirrors Meilisearch's pagination.maxTotalHits cap for regression tests. */
readonly maxTotalHits?: number;
}
export interface InMemoryMeiliState {
@@ -73,9 +75,13 @@ export function createInMemoryMeili(options: InMemoryMeiliOptions = {}): {
if (lowered.length > 0 && !documentMatches(doc, lowered)) continue;
hits.push(doc);
}
const facets = Array.isArray(opts.facets) ? opts.facets.filter((facet): facet is string => typeof facet === "string") : [];
const facetDistribution = buildFacetDistribution(hits, facets);
const estimatedTotalHits = Math.min(hits.length, mutable.options.maxTotalHits ?? Number.POSITIVE_INFINITY);
return {
hits: hits.slice(offset, offset + limit) as unknown as readonly (Record<string, unknown> & { id: string | number })[],
estimatedTotalHits: hits.length,
estimatedTotalHits,
...(facets.length > 0 ? { facetDistribution } : {}),
processingTimeMs: 0,
limit,
offset,
@@ -120,6 +126,23 @@ export function createInMemoryMeili(options: InMemoryMeiliOptions = {}): {
};
}
function buildFacetDistribution(documents: readonly Record<string, unknown>[], facets: readonly string[]): Record<string, Record<string, number>> {
return Object.fromEntries(
facets.flatMap((facet) => {
const counts: Record<string, number> = {};
for (const document of documents) {
const rawValues = Array.isArray(document[facet]) ? document[facet] : [document[facet]];
for (const value of rawValues) {
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") continue;
const key = String(value);
counts[key] = (counts[key] ?? 0) + 1;
}
}
return Object.keys(counts).length > 0 ? [[facet, counts] as const] : [];
})
);
}
function documentMatches(doc: Record<string, unknown>, lowered: string): boolean {
for (const value of Object.values(doc)) {
if (typeof value === "string" && value.toLowerCase().includes(lowered)) return true;