Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

attachmentStore.ts

124 lines3.9 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeCrypto from "node:crypto";
3import * as NodeFS from "node:fs";
4​
5import type { ChatAttachment } from "@t3tools/contracts";
6​
7import {
8 normalizeAttachmentRelativePath,
9 resolveAttachmentRelativePath,
10} from "./attachmentPaths.ts";
11import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
12​
13const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
14const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
15const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
16const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
17const ATTACHMENT_ID_PATTERN = new RegExp(
18 `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
19 "i",
20);
21​
22export function toSafeThreadAttachmentSegment(threadId: string): string | null {
23 const segment = threadId
24 .trim()
25 .toLowerCase()
26 .replace(/[^a-z0-9_-]+/gi, "-")
27 .replace(/-+/g, "-")
28 .replace(/^[-_]+|[-_]+$/g, "")
29 .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
30 .replace(/[-_]+$/g, "");
31 if (segment.length === 0) {
32 return null;
33 }
34 return segment;
36​
37export function createAttachmentId(threadId: string): string | null {
38 const threadSegment = toSafeThreadAttachmentSegment(threadId);
39 if (!threadSegment) {
40 return null;
41 }
42 return `${threadSegment}-${NodeCrypto.randomUUID()}`;
44​
45export function createDeterministicAttachmentId(
46 threadId: string,
47 stableKey: string,
48): string | null {
49 const threadSegment = toSafeThreadAttachmentSegment(threadId);
50 if (!threadSegment) return null;
51 const hash = NodeCrypto.createHash("sha256")
52 .update(JSON.stringify([threadId, stableKey]))
53 .digest("hex")
54 .slice(0, 32);
55 const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
56 return `${threadSegment}-${uuid}`;
58​
59export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
60 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
61 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
62 return null;
63 }
64 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
65 if (!match) {
66 return null;
67 }
68 return match[1]?.toLowerCase() ?? null;
70​
71export function attachmentRelativePath(attachment: ChatAttachment): string {
72 switch (attachment.type) {
73 case "image": {
74 const extension = inferImageExtension({
75 mimeType: attachment.mimeType,
76 fileName: attachment.name,
77 });
78 return `${attachment.id}${extension}`;
79 }
80 }
82​
83export function resolveAttachmentPath(input: {
84 readonly attachmentsDir: string;
85 readonly attachment: ChatAttachment;
86}): string | null {
87 return resolveAttachmentRelativePath({
88 attachmentsDir: input.attachmentsDir,
89 relativePath: attachmentRelativePath(input.attachment),
90 });
92​
93export function resolveAttachmentPathById(input: {
94 readonly attachmentsDir: string;
95 readonly attachmentId: string;
96}): string | null {
97 const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
98 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
99 return null;
100 }
101 for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
102 const maybePath = resolveAttachmentRelativePath({
103 attachmentsDir: input.attachmentsDir,
104 relativePath: `${normalizedId}${extension}`,
105 });
106 if (maybePath && NodeFS.existsSync(maybePath)) {
107 return maybePath;
108 }
109 }
110 return null;
112​
113export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
114 const normalized = normalizeAttachmentRelativePath(relativePath);
115 if (!normalized || normalized.includes("/")) {
116 return null;
117 }
118 const extensionIndex = normalized.lastIndexOf(".");
119 if (extensionIndex <= 0) {
120 return null;
121 }
122 const id = normalized.slice(0, extensionIndex);
123 return id.length > 0 && !id.includes(".") ? id : null;