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

useFileMetadata.ts

40 lines1.6 KB

1import { AuthFilesystemReadScope, type EnvironmentId } from "@t3tools/contracts";
2import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
3import {
4 isAbsolutePath,
5 isNetworkPath,
6 normalizeProjectPathForComparison,
7} from "@t3tools/shared/path";
8import { useContext } from "react";
9​
10import { useEnvironmentScope } from "../state/session";
11import { projectEnvironment } from "../state/projects";
12import { useEnvironmentQuery } from "../state/query";
13import { FileMetadataThreadContext } from "./FileMetadataThreadProvider";
14​
15export function useFileMetadata(
16 environmentId: EnvironmentId | null | undefined,
17 path: string,
18 cwd?: string,
19) {
20 const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
21 const threadRef = useContext(FileMetadataThreadContext);
22 const hostPath = splitFilePathPosition(path).path;
23 const targetPath = normalizeProjectPathForComparison(
24 hostPath.startsWith("~/") || !cwd ? hostPath : resolvePathLinkTarget(hostPath, cwd),
25 );
26 const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
27 return useEnvironmentQuery(
28 // Servers stat what they are asked about, and a network path leaks the
29 // Windows user's NTLM credentials to its host before any chip is clicked.
30 environmentId && canRead && absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
31 ? projectEnvironment.fileMetadata({
32 environmentId,
33 input: {
34 path: targetPath,
35 ...(threadRef?.environmentId === environmentId ? { threadId: threadRef.threadId } : {}),
36 },
37 })
38 : null,
39 ).data;