import { describe, expect, it, vi } from "vitest"; import { publishSearchBulkReindexEvent, publishSearchDeleteEvent, publishSearchUpsertEvent, searchEventType, } from "./outbox-publisher.js"; import { kbArticlesIndex } from "./schemas/index.js"; describe("searchEventType", () => { it("returns the canonical four-segment form", () => { expect(searchEventType("kb-article", "upsert")).toBe("search.index.kbarticle.upsert"); expect(searchEventType("kb-article", "delete")).toBe("search.index.kbarticle.delete"); expect(searchEventType("kb-article", "bulk-reindex")).toBe("search.index.kbarticle.bulkreindex"); }); it("matches the outbox event-type regex", () => { const regex = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*){2,}$/u; for (const verb of ["upsert", "delete", "bulk-reindex"] as const) { expect(regex.test(searchEventType("kb-article", verb))).toBe(true); } }); }); describe("publish*Event", () => { it("publishes a tenant-scoped upsert envelope with a sanitized document", async () => { const publish = vi.fn().mockResolvedValue(undefined); await publishSearchUpsertEvent({ publish, schema: kbArticlesIndex, tenantId: "tenant-a", entityName: "kb-article", document: { id: "a", tenantId: "tenant-a", title: "Hello", // The following field is NOT in the schema allow-list; the // sanitizer should drop it before the payload is built. notes: "secret", } as Record & { id: string; tenantId: string }, }); expect(publish).toHaveBeenCalledOnce(); const call = publish.mock.calls[0][0] as { tenantId: string; type: string; payload: { action: string; document: Record }; }; expect(call.tenantId).toBe("tenant-a"); expect(call.type).toBe("search.index.kbarticle.upsert"); expect(call.payload.action).toBe("upsert"); expect(call.payload.document).not.toHaveProperty("notes"); }); it("publishes a delete event with the document id and tenantId", async () => { const publish = vi.fn().mockResolvedValue(undefined); await publishSearchDeleteEvent({ publish, schema: kbArticlesIndex, tenantId: "tenant-a", entityName: "kb-article", documentId: "a", }); expect(publish).toHaveBeenCalledWith( expect.objectContaining({ type: "search.index.kbarticle.delete", tenantId: "tenant-a", payload: expect.objectContaining({ action: "delete", documentId: "a", indexName: kbArticlesIndex.name }), }) ); }); it("publishes a bulk-reindex event without document payload", async () => { const publish = vi.fn().mockResolvedValue(undefined); await publishSearchBulkReindexEvent({ publish, schema: kbArticlesIndex, tenantId: "tenant-a", entityName: "kb-article", }); expect(publish).toHaveBeenCalledWith( expect.objectContaining({ type: "search.index.kbarticle.bulkreindex", payload: expect.objectContaining({ action: "bulk-reindex", indexName: kbArticlesIndex.name }), }) ); }); });