Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5
6import { describe, expect, it } from "vite-plus/test";
7
8import {
9 createAttachmentId,
10 parseThreadSegmentFromAttachmentId,
11 resolveAttachmentPathById,
12} from "./attachmentStore.ts";
13
14describe("attachmentStore", () => {
15 it("sanitizes thread ids when creating attachment ids", () => {
16 const attachmentId = createAttachmentId("thread.folder/unsafe space");
17 expect(attachmentId).toBeTruthy();
18 if (!attachmentId) {
19 return;
20 }
21
22 const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
23 expect(threadSegment).toBeTruthy();
24 expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
25 expect(threadSegment).not.toContain(".");
26 expect(threadSegment).not.toContain("%");
27 expect(threadSegment).not.toContain("/");
28 });
29
30 it("parses exact thread segments from attachment ids without prefix collisions", () => {
31 const fooId = "foo-00000000-0000-4000-8000-000000000001";
32 const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
33
34 expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo");
35 expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar");
36 });
37
38 it("normalizes created thread segments to lowercase", () => {
39 const attachmentId = createAttachmentId("Thread.Foo");
40 expect(attachmentId).toBeTruthy();
41 if (!attachmentId) {
42 return;
43 }
44 expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
45 });
46
47 it("resolves attachment path by id using the extension that exists on disk", () => {
48 const attachmentsDir = NodeFS.mkdtempSync(
49 NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
50 );
51 try {
52 const attachmentId = "thread-1-attachment";
53 const pngPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
54 NodeFS.writeFileSync(pngPath, Buffer.from("hello"));
55
56 const resolved = resolveAttachmentPathById({
57 attachmentsDir,
58 attachmentId,
59 });
60 expect(resolved).toBe(pngPath);
61 } finally {
62 NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
63 }
64 });
65
66 it("returns null when no attachment file exists for the id", () => {
67 const attachmentsDir = NodeFS.mkdtempSync(
68 NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
69 );
70 try {
71 const resolved = resolveAttachmentPathById({
72 attachmentsDir,
73 attachmentId: "thread-1-missing",
74 });
75 expect(resolved).toBeNull();
76 } finally {
77 NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
78 }
79 });
80});