| 1 | import { AuthFilesystemReadScope, type EnvironmentId } from "@t3tools/contracts"; |
| 2 | import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks"; |
| 3 | import { normalizeProjectPathForComparison, isAbsolutePath } from "@t3tools/shared/path"; |
| 4 | import { useContext } from "react"; |
| 5 | |
| 6 | import { useEnvironmentScope } from "../state/session"; |
| 7 | import { projectEnvironment } from "../state/projects"; |
| 8 | import { useEnvironmentQuery } from "../state/query"; |
| 9 | import { FileMetadataThreadContext } from "./FileMetadataThreadProvider"; |
| 10 | |
| 11 | export function useFileMetadata( |
| 12 | environmentId: EnvironmentId | null | undefined, |
| 13 | path: string, |
| 14 | cwd?: string, |
| 15 | ) { |
| 16 | const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope); |
| 17 | const threadRef = useContext(FileMetadataThreadContext); |
| 18 | const hostPath = splitFilePathPosition(path).path; |
| 19 | const targetPath = normalizeProjectPathForComparison( |
| 20 | hostPath.startsWith("~/") || !cwd ? hostPath : resolvePathLinkTarget(hostPath, cwd), |
| 21 | ); |
| 22 | const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/"); |
| 23 | return useEnvironmentQuery( |
| 24 | environmentId && canRead && absolute && targetPath.length <= 512 |
| 25 | ? projectEnvironment.fileMetadata({ |
| 26 | environmentId, |
| 27 | input: { |
| 28 | path: targetPath, |
| 29 | ...(threadRef?.environmentId === environmentId ? { threadId: threadRef.threadId } : {}), |
| 30 | }, |
| 31 | }) |
| 32 | : null, |
| 33 | ).data; |
| 34 | } |