Open History to see the last commit
1/** Resolves web references without inheriting the desktop renderer's custom app scheme. */
2export function resolveProtocolRelativeMediaUrl(src: string): string {
3 if (!src.startsWith("//")) return src;
4 const protocol =
5 typeof window !== "undefined" && window.location.protocol === "http:" ? "http:" : "https:";
6 return `${protocol}${src}`;
7}
8
9// Data URL escapes are raw bytes, not UTF-8, so `%89` must stay one byte.
10function decodePercentBytes(payload: string) {
11 const encoder = new TextEncoder();
12 return Uint8Array.from(
13 payload
14 .split(/(%[0-9a-f]{2})/i)
15 .flatMap((part) =>
16 /^%[0-9a-f]{2}$/i.test(part)
17 ? [Number.parseInt(part.slice(1), 16)]
18 : [...encoder.encode(part)],
19 ),
20 );
21}
22
23/** Decodes inline media locally; desktop connect-src omits `data:`, so fetch() cannot read it. */
24function readDataUrlBlob(src: string): Blob {
25 // A fragment is never part of the payload; a literal `#` in data must be escaped as `%23`.
26 const url = src.split("#", 1)[0] ?? src;
27 const comma = url.indexOf(",");
28 const [mimeType = "", ...parameters] = url.slice("data:".length, comma).split(";");
29 const payload = url.slice(comma + 1);
30 try {
31 if (comma < 0) throw new Error("Missing data URL payload.");
32 const isBase64 = parameters.some((parameter) => parameter.trim().toLowerCase() === "base64");
33 // Base64 text is ASCII, so any escape that is not valid UTF-8 is malformed anyway.
34 const bytes = isBase64
35 ? Uint8Array.from(atob(decodeURIComponent(payload)), (char) => char.charCodeAt(0))
36 : decodePercentBytes(payload);
37 return new Blob([bytes], { type: mimeType || "text/plain" });
38 } catch (cause) {
39 throw new Error("This inline media could not be decoded.", { cause });
40 }
41}
42
43async function fetchMediaBlob(src: string): Promise<Blob> {
44 const response = await fetch(src).catch(() => null);
45 if (response?.ok) return response.blob();
46 // An <img> can show media that fetch() may not read (CORS, CSP, cookies); desktop reads it natively.
47 const desktop = typeof window === "undefined" ? undefined : window.desktopBridge;
48 const native =
49 desktop && /^https?:/i.test(src) ? await desktop.readMedia(src).catch(() => null) : null;
50 if (native && native.status >= 200 && native.status < 300) {
51 return new Blob([new Uint8Array(native.data)], { type: native.mimeType });
52 }
53 const status = native?.status ?? response?.status;
54 if (status !== undefined) throw new Error(`The file could not be fetched (HTTP ${status}).`);
55 throw new Error(
56 desktop
57 ? "The file could not be fetched. Check the connection and try again."
58 : "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.",
59 );
60}
61
62async function readMediaBlob(src: string): Promise<Blob> {
63 if (/^data:/i.test(src)) return readDataUrlBlob(src);
64 const blob = await fetchMediaBlob(src);
65 if (blob.type.split(";", 1)[0] === "text/html") {
66 throw new Error("This link returned a web page instead of media. Open the original URL.");
67 }
68 return blob;
69}
70
71export async function downloadMedia(src: string, name: string): Promise<void> {
72 const url = URL.createObjectURL(await readMediaBlob(src));
73 try {
74 const anchor = document.createElement("a");
75 anchor.href = url;
76 anchor.download = name;
77 anchor.click();
78 } finally {
79 setTimeout(() => URL.revokeObjectURL(url), 30_000);
80 }
81}
82
83export async function readMediaPng(src: string): Promise<Blob> {
84 const blob = await readMediaBlob(src);
85 if (blob.type.split(";", 1)[0] === "image/png") return blob;
86
87 const url = URL.createObjectURL(blob);
88 const image = new Image();
89 image.src = url;
90 try {
91 try {
92 await image.decode();
93 } catch (cause) {
94 throw new Error(
95 "The browser could not decode this image for copying. Try saving it instead.",
96 {
97 cause,
98 },
99 );
100 }
101 const { naturalWidth: width, naturalHeight: height } = image;
102 if (width <= 0 || height <= 0 || width * height > 64_000_000) {
103 throw new Error(
104 "This image is too large or has no usable dimensions. Try saving it instead.",
105 );
106 }
107 const canvas = document.createElement("canvas");
108 canvas.width = width;
109 canvas.height = height;
110 const context = canvas.getContext("2d");
111 if (!context) throw new Error("Image copying is unavailable in this browser.");
112 context.drawImage(image, 0, 0);
113 return await new Promise<Blob>((resolve, reject) => {
114 canvas.toBlob(
115 (png) =>
116 png ? resolve(png) : reject(new Error("The image could not be converted to PNG.")),
117 "image/png",
118 );
119 });
120 } finally {
121 URL.revokeObjectURL(url);
122 }
123}