Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeCrypto from "node:crypto";
3import * as NodeURL from "node:url";
4import * as NodeFS from "node:fs";
5
6import type { ChatAttachment } from "@t3tools/contracts";
7
8import {
9 normalizeAttachmentRelativePath,
10 resolveAttachmentRelativePath,
11} from "./attachmentPaths.ts";
12import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
13
14const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
15const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
16const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
17const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
18const ATTACHMENT_ID_PATTERN = new RegExp(
19 `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
20 "i",
21);
22
23export function toSafeThreadAttachmentSegment(threadId: string): string | null {
24 const segment = threadId
25 .trim()
26 .toLowerCase()
27 .replace(/[^a-z0-9_-]+/gi, "-")
28 .replace(/-+/g, "-")
29 .replace(/^[-_]+|[-_]+$/g, "")
30 .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
31 .replace(/[-_]+$/g, "");
32 if (segment.length === 0) {
33 return null;
34 }
35 return segment;
36}
37
38export function createAttachmentId(threadId: string): string | null {
39 const threadSegment = toSafeThreadAttachmentSegment(threadId);
40 if (!threadSegment) {
41 return null;
42 }
43 return `${threadSegment}-${NodeCrypto.randomUUID()}`;
44}
45
46export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
47 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
48 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
49 return null;
50 }
51 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
52 if (!match) {
53 return null;
54 }
55 return match[1]?.toLowerCase() ?? null;
56}
57
58export function attachmentRelativePath(attachment: ChatAttachment): string {
59 switch (attachment.type) {
60 case "image": {
61 const extension = inferImageExtension({
62 mimeType: attachment.mimeType,
63 fileName: attachment.name,
64 });
65 return `${attachment.id}${extension}`;
66 }
67 }
68}
69
70export function resolveAttachmentPath(input: {
71 readonly attachmentsDir: string;
72 readonly attachment: ChatAttachment;
73}): string | null {
74 return resolveAttachmentRelativePath({
75 attachmentsDir: input.attachmentsDir,
76 relativePath: attachmentRelativePath(input.attachment),
77 });
78}
79
80/**
81 * `file:` URL for a resolved attachment path.
82 *
83 * Providers that hand attachments to an external agent by reference need a URI
84 * rather than a bare path. `pathToFileURL` is used rather than string
85 * concatenation because it escapes `#` and `?` — which would otherwise
86 * truncate the path on the way back through `fileURLToPath` — and handles
87 * Windows drive letters.
88 */
89export function attachmentFileUrl(attachmentPath: string): string {
90 return NodeURL.pathToFileURL(attachmentPath).href;
91}
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;
111}
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;
124}