Open History to see the last commit
1import { videoMimeType } from "./video.ts";
2
3const ICON_EXTENSION_BY_MIME_TYPE: Readonly<Record<string, string>> = {
4 "image/png": "png",
5 "image/jpeg": "jpg",
6 "image/gif": "gif",
7 "image/webp": "webp",
8 "application/pdf": "pdf",
9 "application/zip": "zip",
10 "application/vnd.sqlite3": "sqlite",
11 "text/x-python": "py",
12 "text/javascript": "js",
13 "text/x-ruby": "rb",
14 "text/x-shellscript": "sh",
15};
16
17export function fileIconPathForMimeType(path: string, mimeType?: string): string {
18 const extension = ICON_EXTENSION_BY_MIME_TYPE[mimeType ?? ""];
19 return extension ? `file.${extension}` : path;
20}
21
22export type FilePreviewKind =
23 | "image"
24 | "video"
25 | "audio"
26 | "pdf"
27 | "html"
28 | "markdown"
29 | "text"
30 | "unsupported";
31
32export function filePreviewKind(file: {
33 readonly name: string;
34 readonly mimeType?: string;
35}): FilePreviewKind {
36 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
37 const name = file.name.toLowerCase();
38 const extension = name.slice(name.lastIndexOf("."));
39 const generic = !mime || mime === "application/octet-stream" || mime === "text/plain";
40 if (mime === "application/pdf") return "pdf";
41 if (mime === "text/html") return "html";
42 if (mime === "text/markdown" || mime === "text/x-markdown") return "markdown";
43 if (mime.startsWith("image/")) return "image";
44 if (mime.startsWith("video/")) return "video";
45 if (mime.startsWith("audio/")) return "audio";
46 if (generic) {
47 if (extension === ".pdf") return "pdf";
48 if (/^\.html?$/.test(extension)) return "html";
49 if (/^\.(md|markdown|mdown|mkd|mdx)$/.test(extension)) return "markdown";
50 const media = mediaMimeTypeFromExtension(extension);
51 if (media?.startsWith("image/")) return "image";
52 if (media?.startsWith("video/")) return "video";
53 if (audioMimeTypeFromExtension(extension) !== null) return "audio";
54 if (
55 /^\.(txt|log|json|jsonc|jsonl|ndjson|yaml|yml|toml|ini|conf|config|env|csv|tsv|xml|css|scss|sass|less|js|jsx|mjs|cjs|ts|tsx|mts|cts|py|pyi|rb|go|rs|swift|kt|kts|java|c|h|cc|cpp|hpp|cs|php|sh|bash|zsh|fish|sql|graphql|gql|vue|svelte|r|lua|ex|exs|erl|hs|clj|dart|diff|patch|lock|properties|gradle)$/.test(
56 extension,
57 ) ||
58 /^(dockerfile|makefile|gemfile|rakefile|license|readme|\.gitignore|\.gitattributes|\.editorconfig|\.env)(\.|$)/i.test(
59 name.split(/[\\/]/).at(-1) ?? "",
60 )
61 )
62 return "text";
63 }
64 if (
65 mime.startsWith("text/") ||
66 /^(application\/(json|.*\+json|xml|.*\+xml|javascript|x-javascript|yaml|x-yaml|toml|sql))$/.test(
67 mime,
68 )
69 )
70 return "text";
71 return "unsupported";
72}
73
74export const FILE_TEXT_PREVIEW_MAX_BYTES = 1024 * 1024;
75
76export function decodeFilePreviewText(bytes: Uint8Array, truncated = false) {
77 const bounded = bytes.subarray(0, FILE_TEXT_PREVIEW_MAX_BYTES);
78 if (bounded.some((byte) => byte === 0))
79 throw new Error("This file contains binary data and cannot be shown as text.");
80 const decoder = new TextDecoder("utf-8", { fatal: true });
81 try {
82 return {
83 text: decoder.decode(bounded, { stream: truncated || bytes.length > bounded.length }),
84 truncated: truncated || bytes.length > bounded.length,
85 };
86 } catch {
87 throw new Error("This file is not UTF-8 text. Open it in another app to view its contents.");
88 }
89}
90
91export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const;
92
93export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
94 ".avif",
95 ".gif",
96 ".ico",
97 ".jpeg",
98 ".jpg",
99 ".png",
100 ".svg",
101 ".webp",
102] as const;
103
104const IMAGE_MIME_TYPE_BY_EXTENSION = new Map([
105 [".avif", "image/avif"],
106 [".gif", "image/gif"],
107 [".ico", "image/x-icon"],
108 [".jpeg", "image/jpeg"],
109 [".jpg", "image/jpeg"],
110 [".png", "image/png"],
111 [".svg", "image/svg+xml"],
112 [".webp", "image/webp"],
113]);
114
115const BROWSER_MIME_TYPE_BY_EXTENSION = new Map([
116 [".htm", "text/html"],
117 [".html", "text/html"],
118 [".pdf", "application/pdf"],
119]);
120
121const AUDIO_MIME_TYPE_BY_EXTENSION = new Map([
122 [".mp3", "audio/mpeg"],
123 [".wav", "audio/wav"],
124 [".ogg", "audio/ogg"],
125 [".oga", "audio/ogg"],
126 [".flac", "audio/flac"],
127 [".aac", "audio/aac"],
128 [".m4a", "audio/mp4"],
129 [".opus", "audio/ogg"],
130 [".aiff", "audio/aiff"],
131 [".webm-audio", "audio/webm"],
132]);
133
134export function audioMimeTypeFromExtension(extension: string): string | null {
135 if (!/^\.[a-z0-9-]+$/i.test(extension)) return null;
136 return AUDIO_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ?? null;
137}
138
139/** Classifies a literal filesystem extension, without URL decoding or suffix removal. */
140export function mediaMimeTypeFromExtension(extension: string): string | null {
141 if (!/^\.[a-z0-9]+$/i.test(extension)) return null;
142 return (
143 IMAGE_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
144 videoMimeType({ name: `media${extension}`, mimeType: "" })
145 );
146}
147
148export function hostPreviewMimeTypeFromExtension(extension: string): string | null {
149 if (!/^\.[a-z0-9-]+$/i.test(extension)) return null;
150 return (
151 mediaMimeTypeFromExtension(extension) ??
152 audioMimeTypeFromExtension(extension) ??
153 BROWSER_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
154 null
155 );
156}
157
158/** Classifies an authored media path or URL. Filesystem validation uses the literal extension. */
159export function mediaMimeType(path: string): string | null {
160 const trimmed = path.trim();
161 const source = trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
162 const dataMimeType = /^data:((?:image|video|audio)\/[\w.+-]+)[;,]/i.exec(source)?.[1];
163 if (dataMimeType) return dataMimeType.toLowerCase();
164
165 let sourcePath = source.split(/[?#]/, 1)[0] ?? "";
166 if (/^(?:https?:|file:|\/\/)/i.test(source)) {
167 try {
168 sourcePath = new URL(source, "https://media.invalid").pathname;
169 } catch {
170 return null;
171 }
172 }
173 try {
174 sourcePath = decodeURIComponent(sourcePath);
175 } catch {}
176 const basename = sourcePath.split(/[\\/]/).at(-1) ?? "";
177 const extensionIndex = basename.lastIndexOf(".");
178 return extensionIndex < 0
179 ? null
180 : (mediaMimeTypeFromExtension(basename.slice(extensionIndex)) ??
181 audioMimeTypeFromExtension(basename.slice(extensionIndex)));
182}
183
184export function mediaKindFromPath(path: string): "image" | "video" | "audio" | null {
185 const mimeType = mediaMimeType(path);
186 if (mimeType === null) return null;
187 return mimeType.startsWith("audio/")
188 ? "audio"
189 : mimeType.startsWith("video/")
190 ? "video"
191 : "image";
192}
193
194function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
195 const literalPath = path.toLowerCase();
196 return extensions.some((extension) => literalPath.endsWith(extension));
197}
198
199export function isWorkspaceBrowserPreviewPath(path: string): boolean {
200 return hasPreviewExtension(path, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS);
201}
202
203export function isWorkspaceImagePreviewPath(path: string): boolean {
204 return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);
205}
206
207/** File viewers receive literal filesystem paths, not Markdown URLs. */
208export function isWorkspaceVideoPreviewPath(path: string): boolean {
209 return videoMimeType({ name: path, mimeType: "" }) !== null;
210}
211
212export function isWorkspaceAudioPreviewPath(path: string): boolean {
213 const extensionIndex = path.lastIndexOf(".");
214 return extensionIndex >= 0 && audioMimeTypeFromExtension(path.slice(extensionIndex)) !== null;
215}
216
217export function isWorkspacePreviewEntryPath(path: string): boolean {
218 return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);
219}