Cotton code
165 lines · 7.6 KB · TypeScriptRaw
/** * The envelope contract, ported case for case from * `crates/cotton-core/src/import/envelope_tests.rs`, plus its vector tables * (`vectors/import.json`: `envelopeMessages`, `batches`, `caps`) — every issue * SENTENCE the Rust produces, the same literal here. */import { describe, expect, it } from "vitest";import vectors from "../../../crates/cotton-rules/vectors/import.json";import { MAX_BATCH_MESSAGES, validateEnvelopeMessage, validateImportBatch } from "../src/import/envelope.ts";const WORKSPACE = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";type Json = Record<string, unknown>;function message(overrides: Json = {}, drop: string[] = []): Json {  const base: Json = { phone: "919876543210", direction: "in", body: "hello", sentAt: "2025-07-26T10:12:45.000Z", externalId: "3EB0A1B2C3D4E5F60718", ...overrides };  for (const key of drop) delete base[key];  return base;}const dm = (value: unknown): string[] => validateEnvelopeMessage(value, "message", "dm");const group = (value: unknown): string[] => validateEnvelopeMessage(value, "m", "group");describe("validateEnvelopeMessage", () => {  it("accepts the minimal section eight shape", () => {    expect(dm(message())).toEqual([]);  });  it("accepts every optional field", () => {    const value = message({ displayName: "Anita Rao", replyToExternalId: "3EB0000000000000AAAA", reactions: [{ emoji: "x", actor: "owner", at: "2025-07-26T10:13:00.000Z" }], meta: { edited: true } });    expect(dm(value)).toEqual([]);  });  it("rejects a phone carrying a leading plus — the canonical form has none", () => {    expect(dm(message({ phone: "+919876543210" })).some((i) => i.includes("message.phone"))).toBe(true);  });  it("rejects a bad direction, sentAt, externalId or body", () => {    for (const [field, patch] of [      ["direction", { direction: "outgoing" }],      ["sentAt", { sentAt: "26/07/2025" }],      ["externalId", { externalId: "" }],      ["body", { body: 42 }],    ] as const) {      expect(dm(message(patch)).join(" "), field).toContain(field);    }  });  it("rejects a reaction missing its actor", () => {    expect(dm(message({ reactions: [{ emoji: "x" }] })).join(" ")).toContain("actor");  });  it("reports the path so a failing message in a batch can be found", () => {    expect(validateEnvelopeMessage(message({ direction: "sideways" }), "messages[7]", "dm").join(" ")).toContain("messages[7].direction");  });  it("an explicit null is present where an absent key is not", () => {    expect(dm(message({ phone: null })).join(" ")).toContain("got null");    expect(dm(message({}, ["phone"]))).toEqual([]);  });  it("media needs a key and refuses remote urls", () => {    for (const scheme of ["http", "https"]) {      const entry = { url: `${scheme}://example.invalid/synthetic.jpg`, contentType: "image/jpeg" };      expect(dm(message({ media: [entry] })).join(" ")).toContain('expected a non-empty "key"');    }  });  it("the typed message's wire spelling validates", () => {    const value = { phone: "919876543210", displayName: "Anita Rao", direction: "in", body: "hello", sentAt: "2025-07-26T10:12:45.000Z", externalId: "txt2:abc" };    expect(dm(value)).toEqual([]);  });  // The Rust's `iso_instant` is `regex`'s `\d`, which is Unicode `Nd`.  it("reads sentAt's digits as the Rust regex does (any decimal digit)", () => {    expect(dm(message({ sentAt: "٢٠٢٥-07-26T10:12:45.000Z" }))).toEqual([]);  });});describe("validateImportBatch", () => {  it("accepts a well-formed batch", () => {    expect(validateImportBatch({ workspaceId: WORKSPACE, channel: "whatsapp", messages: [message()] })).toEqual([]);  });  it("requires a uuid workspace", () => {    expect(validateImportBatch({ workspaceId: "mine", channel: "whatsapp", messages: [message()] }).join(" ")).toContain("workspaceId");  });  it("requires the channel, which the envelope items do not carry", () => {    expect(validateImportBatch({ workspaceId: WORKSPACE, messages: [message()] }).join(" ")).toContain("channel");  });  it("enforces the five hundred message cap", () => {    const messages = Array.from({ length: MAX_BATCH_MESSAGES + 1 }, () => message());    expect(validateImportBatch({ workspaceId: WORKSPACE, channel: "whatsapp", messages }).join(" ")).toContain("exceeds the 500-message cap");  });  it("accepts exactly the cap", () => {    const messages = Array.from({ length: MAX_BATCH_MESSAGES }, () => message());    expect(validateImportBatch({ workspaceId: WORKSPACE, channel: "whatsapp", messages })).toEqual([]);  });});describe("group context", () => {  it("requires a sender label on inbound human messages and forbids phone", () => {    expect(group(message({ senderLabel: "Asha" }, ["phone"]))).toEqual([]);    expect(group(message({}, ["phone"])).join(" ")).toContain("senderLabel");    expect(group(message({ senderLabel: "Asha" })).join(" ")).toContain("phone");    expect(group(message({ direction: "out", senderLabel: "Asha" }, ["phone"])).join(" ")).toContain("senderLabel");    expect(group(message({ meta: { system: true } }, ["phone"]))).toEqual([]);  });  it("forbids a sender label in a dm", () => {    expect(dm(message({ senderLabel: "Asha" })).join(" ")).toContain("senderLabel");  });});describe("identity blocks", () => {  const thread = (): Json => ({    kind: "group",    title: "T",    externalKey: "wa:group:t",    participants: [{ label: "Asha" }, { label: "Vik", phone: "918123456780", personId: "p1" }],  });  it("accepts a dm batch whose messages carry no phone when the dm block names the person", () => {    expect(validateImportBatch({ workspaceId: WORKSPACE, channel: "whatsapp", dm: { label: "Asha" }, messages: [message({}, ["phone"])] })).toEqual([]);  });  it("accepts participants with or without a phone and rejects a blank label or a bad phone", () => {    const messages = [message({ senderLabel: "Asha" }, ["phone"])];    expect(validateImportBatch({ workspaceId: WORKSPACE, channel: "whatsapp", thread: thread(), messages })).toEqual([]);    expect(validateImportBatch({ workspaceId: WORKSPACE, channel: "whatsapp", thread: { ...thread(), participants: [{ label: " " }] }, messages }).join(" ")).toContain("label");    expect(validateImportBatch({ workspaceId: WORKSPACE, channel: "whatsapp", thread: { ...thread(), participants: [{ label: "Asha", phone: "+91" }] }, messages }).join(" ")).toContain("phone");  });  it("refuses a batch that is both a dm and a group", () => {    const batch = { workspaceId: WORKSPACE, channel: "whatsapp", thread: thread(), dm: { label: "Asha" }, messages: [message({ senderLabel: "Asha" }, ["phone"])] };    expect(validateImportBatch(batch).join(" ")).toContain("not both");  });});describe("the vector tables", () => {  it("every message issue is the Rust's own sentence", () => {    expect(vectors.envelopeMessages.length).toBeGreaterThanOrEqual(27);    for (const c of vectors.envelopeMessages as { name: string; value: unknown; at?: string; kind?: string; issues: string[] }[]) {      expect(validateEnvelopeMessage(c.value, c.at ?? "message", c.kind === "group" ? "group" : "dm"), c.name).toEqual(c.issues);    }  });  it("every batch issue is the Rust's own sentence", () => {    expect(vectors.batches.length).toBeGreaterThanOrEqual(16);    for (const c of vectors.batches as { name: string; value: unknown; issues: string[] }[]) {      expect(validateImportBatch(c.value), c.name).toEqual(c.issues);    }  });  it("the cap is the Rust's cap", () => {    for (const c of vectors.caps) {      const messages = Array.from({ length: c.count }, () => message());      expect(validateImportBatch({ workspaceId: WORKSPACE, channel: "whatsapp", messages }), String(c.count)).toEqual(c.issues);    }  });});