Open History to see the last commit
1import {
2 audioMimeTypeFromExtension,
3 isWorkspaceImagePreviewPath,
4 mediaMimeTypeFromExtension,
5} from "./mediaPreview.ts";
6export {
7 isWorkspaceAudioPreviewPath,
8 isWorkspaceImagePreviewPath,
9 mediaKindFromPath,
10 mediaMimeTypeFromExtension,
11} from "./mediaPreview.ts";
12import { GENERIC_MIME_TYPES } from "./image.ts";
13import { parseUrl } from "./url.ts";
14import { videoMimeType } from "./video.ts";
15
16const EPUB_PREVIEW_PATH = "/epub-preview.html";
17
18export function epubPreviewRequest(url: URL): { src: string; name: string } | null {
19 const params = new URLSearchParams(url.hash.slice(1));
20 const path = params.get("file");
21 if (!path?.startsWith("/api/assets/")) return null;
22 const asset = parseUrl(path, url.origin);
23 if (asset?.origin !== url.origin || !asset.pathname.startsWith("/api/assets/")) return null;
24 return { src: asset.href, name: params.get("name")?.slice(0, 300) || "EPUB" };
25}
26
27export function epubPreviewUrl(uri: string, name: string) {
28 const asset = parseUrl(uri);
29 if (!asset || (asset.protocol !== "https:" && asset.protocol !== "http:")) return null;
30 if (!asset.pathname.startsWith("/api/assets/") || asset.username || asset.password) return null;
31 const viewer = new URL(EPUB_PREVIEW_PATH, asset.origin);
32 viewer.hash = new URLSearchParams({ file: asset.pathname + asset.search, name }).toString();
33 return viewer.href;
34}
35
36export type FilePreviewKind =
37 | "image"
38 | "video"
39 | "audio"
40 | "pdf"
41 | "html"
42 | "markdown"
43 | "mermaid"
44 | "font"
45 | "archive"
46 | "sqlite"
47 | "docx"
48 | "xlsx"
49 | "pptx"
50 | "odt"
51 | "ods"
52 | "odp"
53 | "rtf"
54 | "epub"
55 | "ipynb"
56 | "text"
57 | "unsupported";
58
59export function filePreviewKind(
60 file: { readonly name: string; readonly mimeType?: string },
61 options?: { readonly richDocuments?: boolean },
62): FilePreviewKind {
63 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
64 const name = file.name.toLowerCase();
65 const extension = name.slice(name.lastIndexOf("."));
66 const generic = !mime || GENERIC_MIME_TYPES.has(mime) || mime === "text/plain";
67 const richDocuments = options?.richDocuments !== false;
68 const office = richDocuments ? officePreviewKind(file) : null;
69 if (office) return office;
70 const binary = binaryPreviewKind(file);
71 if (binary) return binary;
72 if (mime === "application/pdf") return "pdf";
73 if (mime === "text/html") return "html";
74 if (mime === "text/markdown" || mime === "text/x-markdown") return "markdown";
75 // Linux's MIME database assigns .mdx to Sega 32X ROMs; text decoding still rejects binary bytes.
76 if (extension === ".mdx" && mime === "application/x-genesis-32x-rom") return "markdown";
77 if (richDocuments && mime === "text/vnd.mermaid") return "mermaid";
78 if (richDocuments && mime.startsWith("font/")) return "font";
79 // Linux's MIME database also assigns .otf to OpenDocument formula templates.
80 // FontFace validates the actual bytes before a specimen is shown.
81 if (
82 richDocuments &&
83 extension === ".otf" &&
84 mime === "application/vnd.oasis.opendocument.formula-template"
85 )
86 return "font";
87 if (mime.startsWith("image/")) return "image";
88 if (mime.startsWith("video/") && !generic) return "video";
89 if (mime.startsWith("audio/")) return "audio";
90 if (generic) {
91 if (extension === ".pdf") return "pdf";
92 if (/^\.html?$/.test(extension)) return "html";
93 if (/^\.(md|markdown|mdown|mkd|mdx)$/.test(extension)) return "markdown";
94 if (richDocuments && /^\.(mmd|mermaid)$/.test(extension)) return "mermaid";
95 if (richDocuments && isWorkspaceFontPreviewPath(name)) return "font";
96 if (richDocuments && extension === ".rtf") return "text";
97 const media = mediaMimeTypeFromExtension(extension);
98 if (media?.startsWith("image/")) return "image";
99 if (media?.startsWith("video/")) return "video";
100 if (audioMimeTypeFromExtension(extension) !== null) return "audio";
101 if (
102 /^\.(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(
103 extension,
104 ) ||
105 /^(dockerfile|makefile|gemfile|rakefile|license|readme|\.gitignore|\.gitattributes|\.editorconfig|\.env)(\.|$)/i.test(
106 name.split(/[\\/]/).at(-1) ?? "",
107 )
108 )
109 return "text";
110 }
111 if (
112 mime.startsWith("text/") ||
113 (extension === ".tsx" && mime === "application/x-tiled-tsx") ||
114 /^(application\/(json|.*\+json|xml|.*\+xml|javascript|x-javascript|yaml|x-yaml|toml|sql|typescript|x-shellscript|x-ruby|x-php|x-perl|x-awk|x-csh|x-fishscript|vnd\.dart))$/.test(
115 mime,
116 )
117 )
118 return "text";
119 return "unsupported";
120}
121
122const BINARY_MIME_TYPES = new Map([
123 [".zip", "application/zip"],
124 [".jar", "application/java-archive"],
125 [".tar", "application/x-tar"],
126 [".gz", "application/gzip"],
127 [".tgz", "application/gzip"],
128 [".dmg", "application/x-apple-diskimage"],
129 [".sqlite", "application/vnd.sqlite3"],
130 [".sqlite3", "application/vnd.sqlite3"],
131 [".db", "application/vnd.sqlite3"],
132]);
133
134export function binaryPreviewKind(file: {
135 readonly name: string;
136 readonly mimeType?: string;
137}): "archive" | "sqlite" | null {
138 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
139 if (["application/vnd.sqlite3", "application/x-sqlite3", "application/x-sqlite"].includes(mime))
140 return "sqlite";
141 if (
142 [
143 "application/zip",
144 "application/x-zip-compressed",
145 "application/java-archive",
146 "application/x-java-archive",
147 "application/x-tar",
148 "application/gzip",
149 "application/x-gzip",
150 "application/x-compressed-tar",
151 "application/x-apple-diskimage",
152 ].includes(mime)
153 )
154 return "archive";
155 if (mime && !GENERIC_MIME_TYPES.has(mime) && mime !== "text/plain") return null;
156 const extension = file.name.slice(file.name.lastIndexOf(".")).toLowerCase();
157 const inferred = BINARY_MIME_TYPES.get(extension);
158 return inferred === "application/vnd.sqlite3" ? "sqlite" : inferred ? "archive" : null;
159}
160
161export const FILE_TEXT_PREVIEW_MAX_BYTES = 1024 * 1024;
162
163const OFFICE_MIME_TYPES = {
164 docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
165 xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
166 pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
167 odt: "application/vnd.oasis.opendocument.text",
168 ods: "application/vnd.oasis.opendocument.spreadsheet",
169 odp: "application/vnd.oasis.opendocument.presentation",
170 rtf: "application/rtf",
171 epub: "application/epub+zip",
172 ipynb: "application/x-ipynb+json",
173} as const;
174
175export type OfficePreviewKind = keyof typeof OFFICE_MIME_TYPES;
176
177export function officePreviewKind(file: {
178 readonly name: string;
179 readonly mimeType?: string;
180}): OfficePreviewKind | null {
181 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
182 if (mime === "text/rtf") return "rtf";
183 for (const kind of Object.keys(OFFICE_MIME_TYPES) as OfficePreviewKind[]) {
184 if (mime === OFFICE_MIME_TYPES[kind]) return kind;
185 if (
186 (!mime ||
187 GENERIC_MIME_TYPES.has(mime) ||
188 mime === "text/plain" ||
189 ((kind === "docx" || kind === "xlsx" || kind === "pptx") &&
190 (mime === "application/x-ole-storage" || mime === "application/cdfv2")) ||
191 (kind === "ipynb" && mime === "application/json")) &&
192 file.name.toLowerCase().endsWith(`.${kind}`)
193 )
194 return kind;
195 }
196 return null;
197}
198
199// GB18030 (a superset of GBK) covers Chinese sources that are not UTF-8. Hermes lacks it, so mobile
200// installs a TextDecoder polyfill; any other runtime without it keeps the UTF-8-only error.
201const FILE_PREVIEW_ENCODINGS = ["utf-8", "gb18030"] as const;
202
203function decodeBoundedText(bounded: Uint8Array, truncated: boolean) {
204 for (const encoding of FILE_PREVIEW_ENCODINGS) {
205 try {
206 // `stream` drops a multi-byte character the byte cap cut in half instead of failing on it.
207 return new TextDecoder(encoding, { fatal: true }).decode(bounded, { stream: truncated });
208 } catch {}
209 }
210 return null;
211}
212
213export function decodeFilePreviewText(bytes: Uint8Array, truncated = false) {
214 const bounded = bytes.subarray(0, FILE_TEXT_PREVIEW_MAX_BYTES);
215 if (bounded.some((byte) => byte === 0))
216 throw new Error("This file contains binary data and cannot be shown as text.");
217 const isTruncated = truncated || bytes.length > bounded.length;
218 const text = decodeBoundedText(bounded, isTruncated);
219 if (text === null)
220 throw new Error("This file is not UTF-8 text. Open it in another app to view its contents.");
221 return { text, truncated: isTruncated };
222}
223
224export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const;
225
226const BROWSER_MIME_TYPE_BY_EXTENSION = new Map([
227 [".htm", "text/html"],
228 [".html", "text/html"],
229 [".pdf", "application/pdf"],
230]);
231
232const FONT_MIME_TYPE_BY_EXTENSION = new Map([
233 [".ttf", "font/ttf"],
234 [".otf", "font/otf"],
235 [".woff", "font/woff"],
236 [".woff2", "font/woff2"],
237]);
238
239export function isWorkspaceFontPreviewPath(path: string): boolean {
240 return /\.(ttf|otf|woff2?)$/i.test(path);
241}
242
243export function hostPreviewMimeTypeFromExtension(extension: string): string | null {
244 if (!/^\.[a-z0-9-]+$/i.test(extension)) return null;
245 return (
246 mediaMimeTypeFromExtension(extension) ??
247 audioMimeTypeFromExtension(extension) ??
248 BROWSER_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
249 FONT_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
250 BINARY_MIME_TYPES.get(extension.toLowerCase()) ??
251 (Object.hasOwn(OFFICE_MIME_TYPES, extension.toLowerCase().slice(1))
252 ? OFFICE_MIME_TYPES[extension.toLowerCase().slice(1) as OfficePreviewKind]
253 : null) ??
254 null
255 );
256}
257
258function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
259 const literalPath = path.toLowerCase();
260 return extensions.some((extension) => literalPath.endsWith(extension));
261}
262
263export function isWorkspaceBrowserPreviewPath(path: string): boolean {
264 return hasPreviewExtension(path, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS);
265}
266
267/** File viewers receive literal filesystem paths, not Markdown URLs. */
268export function isWorkspaceVideoPreviewPath(path: string): boolean {
269 return videoMimeType({ name: path, mimeType: "" }) !== null;
270}
271
272export function isWorkspacePreviewEntryPath(path: string): boolean {
273 return (
274 isWorkspaceBrowserPreviewPath(path) ||
275 isWorkspaceImagePreviewPath(path) ||
276 isWorkspaceFontPreviewPath(path) ||
277 officePreviewKind({ name: path }) !== null ||
278 binaryPreviewKind({ name: path }) !== null
279 );
280}