import { describe, expect, it, vi } from "vitest"; import { Capsule } from "../src/capsule.js"; function streamFrom(text: string): ReadableStream { return new ReadableStream({ start(controller) { controller.enqueue(Buffer.from(text)); controller.close(); }, }); } describe("FileManager", () => { it("reads and writes files through the capsule file client", async () => { const capsule = new Capsule("cap_1", { baseUrl: "https://api.example.com", }); const download = vi .spyOn(capsule.client.files, "download") .mockResolvedValue(streamFrom("hello")); const upload = vi .spyOn(capsule.client.files, "upload") .mockResolvedValue(undefined); await expect(capsule.files.read("/tmp/a.txt")).resolves.toEqual( Buffer.from("hello"), ); await expect( capsule.files.write("/tmp/a.txt", "hello"), ).resolves.toBeUndefined(); expect(download).toHaveBeenCalledWith("cap_1", { path: "/tmp/a.txt" }); expect(upload).toHaveBeenCalledWith("cap_1", { file: "hello", path: "/tmp/a.txt", }); }); it("maps directory operations", async () => { const capsule = new Capsule("cap_1", { baseUrl: "https://api.example.com", }); const list = vi.spyOn(capsule.client.files, "list").mockResolvedValue({ entries: [{ name: "a.txt", path: "/tmp/a.txt", type: "file" }], }); const mkdir = vi.spyOn(capsule.client.files, "mkdir").mockResolvedValue({ entry: { path: "/tmp/new", type: "directory" }, }); const remove = vi .spyOn(capsule.client.files, "remove") .mockResolvedValue(undefined); await expect( capsule.files.list("/tmp", { depth: 2 }), ).resolves.toMatchObject({ entries: [{ name: "a.txt" }], }); await expect(capsule.files.mkdir("/tmp/new")).resolves.toMatchObject({ entry: { type: "directory" }, }); await expect(capsule.files.remove("/tmp/a.txt")).resolves.toBeUndefined(); expect(list).toHaveBeenCalledWith("cap_1", { depth: 2, path: "/tmp" }); expect(mkdir).toHaveBeenCalledWith("cap_1", { path: "/tmp/new" }); expect(remove).toHaveBeenCalledWith("cap_1", { path: "/tmp/a.txt" }); }); it("streams downloads as Buffer chunks and uploads streaming content", async () => { const capsule = new Capsule("cap_1", { baseUrl: "https://api.example.com", }); vi.spyOn(capsule.client.files, "streamDownload").mockResolvedValue( streamFrom("hello"), ); const streamUpload = vi .spyOn(capsule.client.files, "streamUpload") .mockResolvedValue(undefined); const chunks: Buffer[] = []; for await (const chunk of capsule.files.downloadStream("/tmp/a.txt")) { chunks.push(chunk); } await capsule.files.uploadStream("/tmp/a.txt", Buffer.from("hello")); expect(Buffer.concat(chunks).toString()).toBe("hello"); expect(streamUpload).toHaveBeenCalledWith("cap_1", { file: expect.any(Blob), path: "/tmp/a.txt", }); }); });