"use client"; import { useMemo } from "react"; import { AlertTriangle, Download, FileArchive, FileText, Loader2, Upload, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { useI18n } from "@/i18n/i18n-context"; import { cn } from "@/lib/utils"; export const MAX_FILE_PATH_BYTES = 1024; export const MAX_FILE_CONTENT_BYTES = 2_000_000; export type FilePathValidationError = "path-required" | "path-traversal" | "path-too-large"; export type FileContentValidationError = "content-too-large"; export function normalizeFileMemoryPath(value: string): string { const trimmed = value.trim().normalize("NFC"); return `/${trimmed.replace(/^\/+/, "")}`; } export function validateFileMemoryPath( value: string, ): FilePathValidationError | null { const path = normalizeFileMemoryPath(value); if (path === "/") return "path-required"; const segments = path.slice(1).split("/"); if ( path.includes("\\") || path.includes("\0") || segments.some((segment) => !segment || segment === "." || segment === "..") ) { return "path-traversal"; } if (new TextEncoder().encode(path).byteLength > MAX_FILE_PATH_BYTES) { return "path-too-large"; } return null; } export function validateFileMemoryContent( value: string, ): FileContentValidationError | null { return new TextEncoder().encode(value).byteLength > MAX_FILE_CONTENT_BYTES ? "content-too-large" : null; } export function FileEditor({ path, content, dirty, readOnly, loading, error, conflict, binary, mediaType, sizeBytes, binaryReady, replacing, binaryAccept, onChange, onDownload, onReplace, }: { path: string | null; content: string; dirty: boolean; readOnly: boolean; loading: boolean; error?: string; conflict?: string | null; binary: boolean; mediaType?: string; sizeBytes?: number; binaryReady: boolean; replacing: boolean; binaryAccept: string; onChange: (content: string) => void; onDownload: () => void; onReplace: (file: File) => void; }) { const { t } = useI18n(); const byteLength = useMemo( () => new TextEncoder().encode(content).byteLength, [content], ); if (!path) { return (

{t("memory.files.selectFile")}

); } if (loading) { return (
{t("common.loading")}
); } if (error) { return (
{t("memory.files.readFailed", { error })}
); } if (binary) { return (
{path}
{conflict ? (
{t("memory.files.versionConflict")}
) : null}

{t("memory.files.binaryFile")}

{t("memory.files.binaryDescription", { mediaType: mediaType ?? "application/octet-stream", size: (sizeBytes ?? 0).toLocaleString(), })}

{t("memory.files.binaryEditHint")}

); } return (
{path} {dirty ? ( {t("memory.files.unsaved")} ) : null}
MAX_FILE_CONTENT_BYTES && "text-[hsl(var(--destructive))]", )} > {t("memory.files.byteCount", { count: byteLength, limit: MAX_FILE_CONTENT_BYTES, })}
{conflict ? (
{t("memory.files.versionConflict")}
) : null}