feat(web): add open vsx theme search
This commit is contained in:
1 parent
31891a1a0c
commit
d1d74f1397
6 files changed
+978
-2
No files matched your search
@@ -23,6 +23,7 @@
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -33,6 +34,8 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"jose": "catalog:",
|
||||
"jsonc-parser": "3.3.1",
|
||||
"jszip": "3.10.1",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "19.2.6",
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
import { CheckCircle2Icon, PlusIcon, SearchIcon, ShieldCheckIcon } from "lucide-react";
|
||||
import type { FormEvent } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
importOpenVsxThemeExtension,
|
||||
searchOpenVsxThemes,
|
||||
type OpenVsxThemeExtension,
|
||||
} from "../../openVsxThemes";
|
||||
import {
|
||||
getCustomThemes,
|
||||
installCustomTheme,
|
||||
removeCustomTheme,
|
||||
type ThemeDefinition,
|
||||
} from "../../themePalette";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import { Input } from "../ui/input";
|
||||
import { Spinner } from "../ui/spinner";
|
||||
|
||||
const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, {
|
||||
notation: "compact",
|
||||
maximumFractionDigits: 1,
|
||||
});
|
||||
const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"];
|
||||
|
||||
export function ThemeSearchDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onInstalled,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onInstalled: (themes: ReadonlyArray<ThemeDefinition>) => void;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
const [installingId, setInstallingId] = useState<string | null>(null);
|
||||
const requestRef = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
requestRef.current?.abort();
|
||||
requestRef.current = null;
|
||||
if (!open) return;
|
||||
setQuery("");
|
||||
setResults(null);
|
||||
setError(null);
|
||||
setIsSearching(false);
|
||||
setInstallingId(null);
|
||||
}, [open]);
|
||||
|
||||
const runSearch = useCallback(async (searchText: string) => {
|
||||
const trimmed = searchText.trim();
|
||||
if (!trimmed) return;
|
||||
requestRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
requestRef.current = controller;
|
||||
setQuery(trimmed);
|
||||
setIsSearching(true);
|
||||
setError(null);
|
||||
setResults(null);
|
||||
try {
|
||||
const nextResults = await searchOpenVsxThemes(trimmed, controller.signal);
|
||||
if (!controller.signal.aborted) setResults(nextResults);
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
|
||||
}
|
||||
} finally {
|
||||
if (requestRef.current === controller) {
|
||||
requestRef.current = null;
|
||||
setIsSearching(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSearch = useCallback(
|
||||
(event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
void runSearch(query);
|
||||
},
|
||||
[query, runSearch],
|
||||
);
|
||||
|
||||
const handleInstall = useCallback(
|
||||
async (extension: OpenVsxThemeExtension) => {
|
||||
requestRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
requestRef.current = controller;
|
||||
setInstallingId(extension.id);
|
||||
setError(null);
|
||||
try {
|
||||
const themes = await importOpenVsxThemeExtension(extension, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
const existingIds = new Set(getCustomThemes().map((theme) => theme.id));
|
||||
const duplicates = themes.filter((theme) => existingIds.has(theme.id));
|
||||
if (duplicates.length > 0) {
|
||||
throw new Error(`${duplicates.map((theme) => theme.label).join(", ")} is already added.`);
|
||||
}
|
||||
|
||||
const installed: ThemeDefinition[] = [];
|
||||
try {
|
||||
for (const theme of themes) installed.push(installCustomTheme(theme));
|
||||
} catch (cause) {
|
||||
for (const theme of installed) {
|
||||
try {
|
||||
removeCustomTheme(theme.id);
|
||||
} catch {
|
||||
// Best effort rollback. The original storage failure is clearer.
|
||||
}
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
onInstalled(installed);
|
||||
onOpenChange(false);
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause instanceof Error ? cause.message : "That theme could not be added.");
|
||||
}
|
||||
} finally {
|
||||
if (requestRef.current === controller) {
|
||||
requestRef.current = null;
|
||||
setInstallingId(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
[onInstalled, onOpenChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) requestRef.current?.abort();
|
||||
onOpenChange(nextOpen);
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-2xl overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Search themes</DialogTitle>
|
||||
<DialogDescription>
|
||||
Find community themes from Open VSX and add them in one click.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-4">
|
||||
<form className="relative flex gap-2" onSubmit={handleSearch}>
|
||||
<SearchIcon className="pointer-events-none absolute left-3 top-1/2 z-10 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label="Search Open VSX themes"
|
||||
className="rounded-xl [&_input]:pl-9"
|
||||
autoFocus
|
||||
onChange={(event) => setQuery(event.currentTarget.value)}
|
||||
placeholder="try dracula, nord, catppuccin..."
|
||||
size="lg"
|
||||
type="search"
|
||||
value={query}
|
||||
/>
|
||||
<Button disabled={!query.trim() || isSearching || installingId !== null} type="submit">
|
||||
{isSearching ? <Spinner /> : <SearchIcon />}
|
||||
Search
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{error ? (
|
||||
<div
|
||||
aria-live="polite"
|
||||
className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{results === null && !isSearching ? (
|
||||
<div className="flex min-h-48 flex-col items-center justify-center gap-4 rounded-2xl border border-dashed border-border/70 bg-muted/15 px-6 text-center">
|
||||
<div>
|
||||
<p className="text-sm font-medium">What theme are you looking for?</p>
|
||||
<p className="mt-1 text-muted-foreground text-xs">
|
||||
Only themes with a supported open-source license are shown.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap justify-center gap-2">
|
||||
{SUGGESTED_SEARCHES.map((suggestion) => (
|
||||
<Button
|
||||
key={suggestion}
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => void runSearch(suggestion)}
|
||||
>
|
||||
{suggestion}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isSearching ? (
|
||||
<div className="flex min-h-48 items-center justify-center gap-2 text-muted-foreground text-sm">
|
||||
<Spinner /> Finding themes...
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{results ? (
|
||||
results.length === 0 ? (
|
||||
<div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
|
||||
<p className="text-sm font-medium">No supported open-source themes found</p>
|
||||
<p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{results.map((extension) => {
|
||||
const isInstalling = installingId === extension.id;
|
||||
return (
|
||||
<article
|
||||
className="group flex min-w-0 flex-col gap-3 rounded-xl border border-border/70 bg-card/60 p-3 transition-colors hover:bg-accent/20"
|
||||
key={extension.id}
|
||||
>
|
||||
<div className="flex min-w-0 gap-3">
|
||||
{extension.iconUrl ? (
|
||||
<img
|
||||
alt=""
|
||||
className="size-10 shrink-0 rounded-lg bg-muted object-cover"
|
||||
src={extension.iconUrl}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">
|
||||
<SearchIcon className="size-4" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<h4 className="truncate text-sm font-medium">{extension.name}</h4>
|
||||
<p className="truncate text-muted-foreground text-xs">
|
||||
{extension.publisher} ·{" "}
|
||||
{DOWNLOAD_FORMAT.format(extension.downloadCount)} downloads
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
|
||||
{extension.description || "A community color theme for your editor."}
|
||||
</p>
|
||||
<div className="mt-auto flex items-center justify-between gap-2">
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground text-[11px]">
|
||||
<ShieldCheckIcon className="size-3" /> {extension.license}
|
||||
</span>
|
||||
<Button
|
||||
disabled={installingId !== null}
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => void handleInstall(extension)}
|
||||
>
|
||||
{isInstalling ? <Spinner /> : <PlusIcon />}
|
||||
{isInstalling ? "Adding..." : "Add"}
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center justify-center gap-1.5 text-muted-foreground text-[11px]">
|
||||
<CheckCircle2Icon className="size-3" /> Sourced from Open VSX, with license and package
|
||||
integrity checks
|
||||
</div>
|
||||
</DialogPanel>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
DownloadIcon,
|
||||
PenLineIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
Trash2Icon,
|
||||
UploadIcon,
|
||||
} from "lucide-react";
|
||||
@@ -35,6 +36,7 @@ import { Button } from "../ui/button";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
|
||||
import { ThemeImportDialog } from "./ThemeImportDialog";
|
||||
import { ThemeSearchDialog } from "./ThemeSearchDialog";
|
||||
import { useThemeEditorStore } from "./themeEditorStore";
|
||||
import {
|
||||
STANDARD_THEME_CARDS,
|
||||
@@ -250,6 +252,7 @@ export function ThemeLibrary({
|
||||
setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean;
|
||||
}) {
|
||||
const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor);
|
||||
const [isSearchOpen, setIsSearchOpen] = useState(false);
|
||||
const [themeToRemove, setThemeToRemove] = useState<ThemeDefinition | null>(null);
|
||||
// Keep the last removal target so the dialog title stays populated while the
|
||||
// close animation plays after confirming.
|
||||
@@ -553,9 +556,12 @@ export function ThemeLibrary({
|
||||
{renderModeTiles()}
|
||||
<div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4">
|
||||
<h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>
|
||||
<div className="flex flex-wrap items-center justify-end gap-3">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<Button size="xs" variant="outline" onClick={() => setIsSearchOpen(true)}>
|
||||
<SearchIcon />
|
||||
Search themes
|
||||
</Button>
|
||||
<Button
|
||||
className="h-7 rounded-md border border-border/70 bg-muted/30 px-2 text-xs font-medium text-foreground shadow-none hover:bg-accent/40"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
@@ -577,6 +583,22 @@ export function ThemeLibrary({
|
||||
</div>
|
||||
</div>
|
||||
{renderPairGrid()}
|
||||
<ThemeSearchDialog
|
||||
onInstalled={(installedThemes) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "success",
|
||||
title:
|
||||
installedThemes.length === 1
|
||||
? `${installedThemes[0]!.label} added`
|
||||
: `${installedThemes.length} themes added`,
|
||||
description: installedThemes.map((installed) => installed.label).join(", "),
|
||||
}),
|
||||
);
|
||||
}}
|
||||
onOpenChange={setIsSearchOpen}
|
||||
open={isSearchOpen}
|
||||
/>
|
||||
<ThemeImportDialog
|
||||
onImportedMany={(importedThemes, { updated }) => {
|
||||
// An updated theme that is showing (as the base or either half)
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import JSZip from "jszip";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
importOpenVsxThemeExtension,
|
||||
searchOpenVsxThemes,
|
||||
type OpenVsxThemeExtension,
|
||||
} from "./openVsxThemes";
|
||||
import { getThemeColorsForMode } from "./themePalette";
|
||||
|
||||
const ASSET_ROOT = "https://open-vsx.org/api/demo/theme/1.0.0/file";
|
||||
|
||||
function extensionDetail(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
namespace: "demo",
|
||||
name: "theme",
|
||||
displayName: "Demo Theme",
|
||||
description: "A nice theme",
|
||||
version: "1.0.0",
|
||||
downloadCount: 123456,
|
||||
license: "MIT",
|
||||
files: {
|
||||
icon: `${ASSET_ROOT}/icon.png`,
|
||||
manifest: `${ASSET_ROOT}/package.json`,
|
||||
sha256: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
|
||||
download: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("Open VSX themes", () => {
|
||||
it("searches theme extensions and keeps only supported open-source licenses", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/-/search?")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
extensions: [
|
||||
{ namespace: "demo", name: "theme" },
|
||||
{ namespace: "closed", name: "theme" },
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
if (url.endsWith("/closed/theme")) {
|
||||
return new Response(
|
||||
JSON.stringify(extensionDetail({ namespace: "closed", license: "All Rights Reserved" })),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify(extensionDetail()), { status: 200 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const results = await searchOpenVsxThemes(" dracula ");
|
||||
|
||||
expect(results).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "demo.theme",
|
||||
name: "Demo Theme",
|
||||
publisher: "demo",
|
||||
downloadCount: 123456,
|
||||
license: "MIT",
|
||||
}),
|
||||
]);
|
||||
const searchUrl = new URL(String(fetchMock.mock.calls[0]![0]));
|
||||
expect(searchUrl.searchParams.get("query")).toBe("dracula");
|
||||
expect(searchUrl.searchParams.get("category")).toBe("Themes");
|
||||
expect(searchUrl.searchParams.get("size")).toBe("16");
|
||||
});
|
||||
|
||||
it("downloads a verified VSIX, reads JSONC includes, and pairs contributed variants", async () => {
|
||||
const zip = new JSZip();
|
||||
zip.file(
|
||||
"extension/themes/base.jsonc",
|
||||
`{
|
||||
// inherited workbench colors
|
||||
"colors": {
|
||||
"editor.foreground": "#eeeeee",
|
||||
"focusBorder": "#8b5cf6",
|
||||
},
|
||||
}`,
|
||||
);
|
||||
zip.file(
|
||||
"extension/themes/demo-dark.json",
|
||||
`{
|
||||
"include": "./base.jsonc",
|
||||
"colors": { "editor.background": "#111111" }
|
||||
}`,
|
||||
);
|
||||
zip.file(
|
||||
"extension/themes/demo-light.json",
|
||||
`{
|
||||
"colors": {
|
||||
"editor.background": "#fafafa",
|
||||
"editor.foreground": "#222222",
|
||||
"focusBorder": "#8b5cf6"
|
||||
}
|
||||
}`,
|
||||
);
|
||||
zip.file(
|
||||
"extension/themes/demo.json",
|
||||
`{
|
||||
"colors": {
|
||||
"editor.background": "#181818",
|
||||
"editor.foreground": "#eeeeee"
|
||||
}
|
||||
}`,
|
||||
);
|
||||
const packageBytes = await zip.generateAsync({ type: "arraybuffer" });
|
||||
const checksum = [...sha256(new Uint8Array(packageBytes))]
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
const manifest = {
|
||||
contributes: {
|
||||
themes: [
|
||||
{ label: "Demo Dark", uiTheme: "vs-dark", path: "./themes/demo-dark.json" },
|
||||
{ label: "Demo Light", uiTheme: "vs", path: "./themes/demo-light.json" },
|
||||
{ label: "Demo", uiTheme: "vs-dark", path: "./themes/demo.json" },
|
||||
],
|
||||
},
|
||||
};
|
||||
const extension: OpenVsxThemeExtension = {
|
||||
id: "demo.theme",
|
||||
name: "Demo Theme",
|
||||
publisher: "demo",
|
||||
description: "",
|
||||
downloadCount: 1,
|
||||
iconUrl: null,
|
||||
license: "MIT",
|
||||
manifestUrl: `${ASSET_ROOT}/package.json`,
|
||||
sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
|
||||
version: "1.0.0",
|
||||
vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
|
||||
};
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
if (url === extension.manifestUrl) {
|
||||
return new Response(JSON.stringify(manifest), { status: 200 });
|
||||
}
|
||||
if (url === extension.sha256Url) return new Response(`${checksum} demo.vsix`);
|
||||
return new Response(packageBytes, {
|
||||
status: 200,
|
||||
headers: { "Content-Length": String(packageBytes.byteLength) },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const themes = await importOpenVsxThemeExtension(extension);
|
||||
|
||||
expect(themes).toHaveLength(2);
|
||||
expect(new Set(themes.map((theme) => theme.id)).size).toBe(2);
|
||||
const paired = themes.find(
|
||||
(theme) =>
|
||||
getThemeColorsForMode(theme, "light") !== null &&
|
||||
getThemeColorsForMode(theme, "dark") !== null,
|
||||
)!;
|
||||
expect(paired.label).toBe("Demo");
|
||||
expect(paired.colors.canvas).toBe("#fafafa");
|
||||
expect(getThemeColorsForMode(paired, "dark")!.canvas).toBe("#111111");
|
||||
expect(getThemeColorsForMode(paired, "dark")!.text).toBe("#eeeeee");
|
||||
});
|
||||
|
||||
it("rejects a package whose Open VSX checksum does not match", async () => {
|
||||
const extension: OpenVsxThemeExtension = {
|
||||
id: "demo.theme",
|
||||
name: "Demo Theme",
|
||||
publisher: "demo",
|
||||
description: "",
|
||||
downloadCount: 1,
|
||||
iconUrl: null,
|
||||
license: "MIT",
|
||||
manifestUrl: `${ASSET_ROOT}/package.json`,
|
||||
sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
|
||||
version: "1.0.0",
|
||||
vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
|
||||
};
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
if (url === extension.manifestUrl) {
|
||||
return new Response(
|
||||
JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
|
||||
);
|
||||
}
|
||||
if (url === extension.sha256Url) return new Response("0".repeat(64));
|
||||
return new Response(new Uint8Array([1, 2, 3]));
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow("integrity check");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,462 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import JSZip from "jszip";
|
||||
import { parse, type ParseError } from "jsonc-parser";
|
||||
|
||||
import type { ThemeDefinition } from "./themePalette";
|
||||
import {
|
||||
isVsCodeThemeFile,
|
||||
pairVsCodeThemes,
|
||||
parseVsCodeThemeFile,
|
||||
resolveThemeLabelCollisions,
|
||||
} from "./vscodeThemeImport";
|
||||
|
||||
const OPEN_VSX_SEARCH_URL = "https://open-vsx.org/api/-/search";
|
||||
const MAX_VSIX_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_SEARCH_BYTES = 512 * 1024;
|
||||
const MAX_MANIFEST_BYTES = 256 * 1024;
|
||||
const MAX_THEME_BYTES = 256 * 1024;
|
||||
const MAX_ZIP_ENTRIES = 2_000;
|
||||
const MAX_UNCOMPRESSED_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_COMPRESSION_RATIO = 200;
|
||||
const MAX_THEMES_PER_EXTENSION = 40;
|
||||
const MAX_INCLUDE_DEPTH = 8;
|
||||
const SUPPORTED_LICENSES = new Set([
|
||||
"0BSD",
|
||||
"Apache-2.0",
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"CC0-1.0",
|
||||
"ISC",
|
||||
"MIT",
|
||||
"MPL-2.0",
|
||||
"Unlicense",
|
||||
]);
|
||||
|
||||
export type OpenVsxThemeExtension = {
|
||||
id: string;
|
||||
name: string;
|
||||
publisher: string;
|
||||
description: string;
|
||||
downloadCount: number;
|
||||
iconUrl: string | null;
|
||||
manifestUrl: string;
|
||||
sha256Url: string;
|
||||
vsixUrl: string;
|
||||
version: string;
|
||||
license: string;
|
||||
};
|
||||
|
||||
type ThemeContribution = { label?: unknown; uiTheme?: unknown; path?: unknown };
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function trustedOpenVsxUrl(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "https:" && url.hostname.toLowerCase() === "open-vsx.org"
|
||||
? url.toString()
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function extensionFromDetail(value: unknown): OpenVsxThemeExtension | null {
|
||||
if (!isRecord(value) || !isRecord(value.files)) return null;
|
||||
const namespace = typeof value.namespace === "string" ? value.namespace.trim() : "";
|
||||
const extensionName = typeof value.name === "string" ? value.name.trim() : "";
|
||||
const displayName = typeof value.displayName === "string" ? value.displayName.trim() : "";
|
||||
const version = typeof value.version === "string" ? value.version.trim() : "";
|
||||
const license = typeof value.license === "string" ? value.license.trim() : "";
|
||||
const manifestUrl = trustedOpenVsxUrl(value.files.manifest);
|
||||
const sha256Url = trustedOpenVsxUrl(value.files.sha256);
|
||||
const vsixUrl = trustedOpenVsxUrl(value.files.download);
|
||||
if (
|
||||
!namespace ||
|
||||
!extensionName ||
|
||||
!displayName ||
|
||||
!version ||
|
||||
!SUPPORTED_LICENSES.has(license) ||
|
||||
!manifestUrl ||
|
||||
!sha256Url ||
|
||||
!vsixUrl
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: `${namespace}.${extensionName}`,
|
||||
name: displayName,
|
||||
publisher: namespace,
|
||||
description: typeof value.description === "string" ? value.description : "",
|
||||
downloadCount:
|
||||
typeof value.downloadCount === "number" && Number.isFinite(value.downloadCount)
|
||||
? value.downloadCount
|
||||
: 0,
|
||||
iconUrl: trustedOpenVsxUrl(value.files.icon),
|
||||
manifestUrl,
|
||||
sha256Url,
|
||||
vsixUrl,
|
||||
version,
|
||||
license,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchOpenVsxThemes(
|
||||
query: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<OpenVsxThemeExtension[]> {
|
||||
const searchText = query.trim();
|
||||
if (!searchText) return [];
|
||||
const url = new URL(OPEN_VSX_SEARCH_URL);
|
||||
url.searchParams.set("query", searchText);
|
||||
url.searchParams.set("category", "Themes");
|
||||
// Ask for a few extras because results without a supported SPDX license
|
||||
// are intentionally omitted.
|
||||
url.searchParams.set("size", "16");
|
||||
const response = await fetch(url, signal ? { signal } : {});
|
||||
if (!response.ok) throw new Error("Open VSX search is unavailable right now.");
|
||||
const searchBytes = await readCappedResponse(
|
||||
response,
|
||||
MAX_SEARCH_BYTES,
|
||||
"Open VSX returned an unexpectedly large response.",
|
||||
);
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(new TextDecoder().decode(searchBytes));
|
||||
} catch {
|
||||
throw new Error("Open VSX returned an unreadable response.");
|
||||
}
|
||||
const candidates = isRecord(value) && Array.isArray(value.extensions) ? value.extensions : [];
|
||||
const identities = candidates.flatMap((candidate): Array<[string, string]> => {
|
||||
if (!isRecord(candidate)) return [];
|
||||
const namespace = typeof candidate.namespace === "string" ? candidate.namespace : "";
|
||||
const name = typeof candidate.name === "string" ? candidate.name : "";
|
||||
return namespace && name ? [[namespace, name]] : [];
|
||||
});
|
||||
const details = await Promise.allSettled(
|
||||
identities.slice(0, 16).map(async ([namespace, name]) => {
|
||||
const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;
|
||||
const detailResponse = await fetch(detailUrl, signal ? { signal } : {});
|
||||
if (!detailResponse.ok) return null;
|
||||
return extensionFromDetail(await detailResponse.json());
|
||||
}),
|
||||
);
|
||||
if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");
|
||||
return details
|
||||
.flatMap((result) => (result.status === "fulfilled" && result.value ? [result.value] : []))
|
||||
.slice(0, 8);
|
||||
}
|
||||
|
||||
function parseJsoncObject(source: string, description: string): Record<string, unknown> {
|
||||
const errors: ParseError[] = [];
|
||||
const value: unknown = parse(source, errors, { allowTrailingComma: true });
|
||||
if (errors.length > 0 || !isRecord(value)) throw new Error(`${description} is not valid JSON.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizePackagePath(path: string, relativeTo = "extension/"): string {
|
||||
if (path.includes("\0") || path.startsWith("/") || /^[a-zA-Z]:/.test(path)) {
|
||||
throw new Error("Theme path is not a safe relative package path.");
|
||||
}
|
||||
const normalizedInput = path.replaceAll("\\", "/");
|
||||
const baseSegments = relativeTo.split("/").slice(0, -1);
|
||||
const segments = baseSegments;
|
||||
for (const segment of normalizedInput.split("/")) {
|
||||
if (!segment || segment === ".") continue;
|
||||
if (segment === "..") {
|
||||
if (segments.length <= 1) throw new Error("Theme path escapes the extension package.");
|
||||
segments.pop();
|
||||
continue;
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
if (segments[0] !== "extension") segments.unshift("extension");
|
||||
return segments.join("/");
|
||||
}
|
||||
|
||||
function contributionType(uiTheme: unknown): string | null {
|
||||
if (uiTheme === "vs") return "light";
|
||||
if (uiTheme === "vs-dark") return "dark";
|
||||
if (uiTheme === "hc-black" || uiTheme === "hc-light") return uiTheme;
|
||||
return null;
|
||||
}
|
||||
|
||||
type ZipEntrySizes = {
|
||||
compressedSize?: unknown;
|
||||
uncompressedSize?: unknown;
|
||||
};
|
||||
|
||||
type InspectableZipObject = JSZip.JSZipObject & {
|
||||
_data?: ZipEntrySizes;
|
||||
unsafeOriginalName?: string;
|
||||
internalStream?: (type: "uint8array") => JSZip.JSZipStreamHelper<Uint8Array>;
|
||||
};
|
||||
|
||||
function inspectZipDirectory(bytes: Uint8Array): void {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const minimumOffset = Math.max(0, bytes.byteLength - 65_557);
|
||||
let endOffset = bytes.byteLength - 22;
|
||||
while (endOffset >= minimumOffset && view.getUint32(endOffset, true) !== 0x06054b50) {
|
||||
endOffset -= 1;
|
||||
}
|
||||
if (endOffset < minimumOffset) throw new Error("That extension package has no ZIP directory.");
|
||||
|
||||
const directorySize = view.getUint32(endOffset + 12, true);
|
||||
const directoryOffset = view.getUint32(endOffset + 16, true);
|
||||
const directoryEnd = directoryOffset + directorySize;
|
||||
if (directoryEnd > endOffset || directoryEnd > bytes.byteLength) {
|
||||
throw new Error("That extension package has an invalid ZIP directory.");
|
||||
}
|
||||
|
||||
let entryCount = 0;
|
||||
let offset = directoryOffset;
|
||||
while (offset < directoryEnd) {
|
||||
if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50) {
|
||||
throw new Error("That extension package has an invalid ZIP directory.");
|
||||
}
|
||||
entryCount += 1;
|
||||
if (entryCount > MAX_ZIP_ENTRIES) {
|
||||
throw new Error("That extension package has too many files.");
|
||||
}
|
||||
const nameLength = view.getUint16(offset + 28, true);
|
||||
const extraLength = view.getUint16(offset + 30, true);
|
||||
const commentLength = view.getUint16(offset + 32, true);
|
||||
offset += 46 + nameLength + extraLength + commentLength;
|
||||
}
|
||||
if (offset !== directoryEnd)
|
||||
throw new Error("That extension package has an invalid ZIP directory.");
|
||||
}
|
||||
|
||||
function inspectZip(zip: JSZip): void {
|
||||
const entries = Object.values(zip.files) as InspectableZipObject[];
|
||||
if (entries.length > MAX_ZIP_ENTRIES)
|
||||
throw new Error("That extension package has too many files.");
|
||||
|
||||
let totalUncompressed = 0;
|
||||
for (const entry of entries) {
|
||||
if (entry.unsafeOriginalName) normalizePackagePath(entry.unsafeOriginalName);
|
||||
if (entry.dir) continue;
|
||||
const compressed = entry._data?.compressedSize;
|
||||
const uncompressed = entry._data?.uncompressedSize;
|
||||
if (typeof compressed !== "number" || typeof uncompressed !== "number") {
|
||||
throw new Error("That extension package has unreadable file metadata.");
|
||||
}
|
||||
totalUncompressed += uncompressed;
|
||||
if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
|
||||
throw new Error("That extension package expands beyond the safe import limit.");
|
||||
}
|
||||
if (
|
||||
uncompressed > 0 &&
|
||||
(compressed === 0 || uncompressed / compressed > MAX_COMPRESSION_RATIO)
|
||||
) {
|
||||
throw new Error("That extension package has an unsafe compression ratio.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function readZipText(zip: JSZip, path: string, description: string): Promise<string> {
|
||||
const file = zip.file(path) as InspectableZipObject | null;
|
||||
if (!file) throw new Error(`${description} is missing from the extension package.`);
|
||||
if (typeof file._data?.uncompressedSize !== "number" || !file.internalStream) {
|
||||
throw new Error(`${description} has unreadable size metadata.`);
|
||||
}
|
||||
if (file._data.uncompressedSize > MAX_THEME_BYTES) {
|
||||
throw new Error(`${description} is too large.`);
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let byteLength = 0;
|
||||
let settled = false;
|
||||
const stream = file.internalStream!("uint8array");
|
||||
stream
|
||||
.on("data", (chunk) => {
|
||||
if (settled) return;
|
||||
byteLength += chunk.byteLength;
|
||||
if (byteLength > MAX_THEME_BYTES) {
|
||||
settled = true;
|
||||
stream.pause();
|
||||
reject(new Error(`${description} is too large.`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
})
|
||||
.on("error", (cause) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(cause);
|
||||
})
|
||||
.on("end", () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
const bytes = new Uint8Array(byteLength);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
resolve(new TextDecoder().decode(bytes));
|
||||
})
|
||||
.resume();
|
||||
});
|
||||
}
|
||||
|
||||
async function loadThemeObject(
|
||||
zip: JSZip,
|
||||
path: string,
|
||||
ancestors: ReadonlySet<string> = new Set(),
|
||||
): Promise<Record<string, unknown>> {
|
||||
if (ancestors.size >= MAX_INCLUDE_DEPTH) throw new Error("Theme includes are nested too deeply.");
|
||||
if (ancestors.has(path)) throw new Error("Theme includes contain a cycle.");
|
||||
const value = parseJsoncObject(await readZipText(zip, path, path), path);
|
||||
if (typeof value.include !== "string") return value;
|
||||
|
||||
const includePath = normalizePackagePath(value.include, path);
|
||||
const nextAncestors = new Set(ancestors);
|
||||
nextAncestors.add(path);
|
||||
const base = await loadThemeObject(zip, includePath, nextAncestors);
|
||||
return {
|
||||
...base,
|
||||
...value,
|
||||
colors: {
|
||||
...(isRecord(base.colors) ? base.colors : {}),
|
||||
...(isRecord(value.colors) ? value.colors : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readCappedResponse(
|
||||
response: Response,
|
||||
limit: number,
|
||||
tooLargeMessage: string,
|
||||
): Promise<Uint8Array> {
|
||||
const contentLength = response.headers.get("content-length");
|
||||
if (contentLength && Number(contentLength) > limit) throw new Error(tooLargeMessage);
|
||||
if (!response.body) {
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
if (bytes.byteLength > limit) throw new Error(tooLargeMessage);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let byteLength = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
byteLength += value.byteLength;
|
||||
if (byteLength > limit) {
|
||||
await reader.cancel();
|
||||
throw new Error(tooLargeMessage);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
const result = new Uint8Array(byteLength);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
result.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function fetchPackage(url: string, signal?: AbortSignal): Promise<Uint8Array> {
|
||||
const response = await fetch(url, signal ? { signal } : {});
|
||||
if (!response.ok) throw new Error("That Open VSX theme could not be downloaded.");
|
||||
return readCappedResponse(
|
||||
response,
|
||||
MAX_VSIX_BYTES,
|
||||
"That theme extension is too large to import safely.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function importOpenVsxThemeExtension(
|
||||
extension: OpenVsxThemeExtension,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReadonlyArray<ThemeDefinition>> {
|
||||
const manifestResponse = await fetch(extension.manifestUrl, signal ? { signal } : {});
|
||||
if (!manifestResponse.ok) throw new Error("That Open VSX extension has no readable manifest.");
|
||||
const manifestBytes = await readCappedResponse(
|
||||
manifestResponse,
|
||||
MAX_MANIFEST_BYTES,
|
||||
"That Open VSX extension manifest is too large.",
|
||||
);
|
||||
const manifest = parseJsoncObject(new TextDecoder().decode(manifestBytes), "Extension manifest");
|
||||
const contributes = isRecord(manifest.contributes) ? manifest.contributes : null;
|
||||
const contributions = Array.isArray(contributes?.themes)
|
||||
? contributes.themes.filter(isRecord)
|
||||
: [];
|
||||
if (contributions.length === 0) throw new Error("That extension does not contain color themes.");
|
||||
if (contributions.length > MAX_THEMES_PER_EXTENSION) {
|
||||
throw new Error("That extension contains too many color themes to import safely.");
|
||||
}
|
||||
|
||||
const packageBytes = await fetchPackage(extension.vsixUrl, signal);
|
||||
const checksumResponse = await fetch(extension.sha256Url, signal ? { signal } : {});
|
||||
if (!checksumResponse.ok) throw new Error("That Open VSX theme has no readable checksum.");
|
||||
const expectedChecksum = new TextDecoder()
|
||||
.decode(
|
||||
await readCappedResponse(
|
||||
checksumResponse,
|
||||
256,
|
||||
"That Open VSX checksum response is invalid.",
|
||||
),
|
||||
)
|
||||
.trim()
|
||||
.split(/\s+/)[0];
|
||||
if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) {
|
||||
throw new Error("That Open VSX theme has an invalid checksum.");
|
||||
}
|
||||
const actualChecksum = [...sha256(packageBytes)]
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
if (actualChecksum.toLowerCase() !== expectedChecksum.toLowerCase()) {
|
||||
throw new Error("That Open VSX theme failed its integrity check.");
|
||||
}
|
||||
let zip: JSZip;
|
||||
try {
|
||||
inspectZipDirectory(packageBytes);
|
||||
zip = await JSZip.loadAsync(packageBytes);
|
||||
inspectZip(zip);
|
||||
} catch (cause) {
|
||||
if (cause instanceof Error && cause.message.startsWith("That extension package")) throw cause;
|
||||
throw new Error("That Open VSX extension package could not be opened.", { cause });
|
||||
}
|
||||
|
||||
const parsed: Array<{ theme: ThemeDefinition; sourceName: string }> = [];
|
||||
const failures: string[] = [];
|
||||
for (const contribution of contributions as ThemeContribution[]) {
|
||||
if (typeof contribution.path !== "string") continue;
|
||||
try {
|
||||
const path = normalizePackagePath(contribution.path);
|
||||
const themeValue = await loadThemeObject(zip, path);
|
||||
const type = contributionType(contribution.uiTheme);
|
||||
const label =
|
||||
typeof contribution.label === "string" && contribution.label.trim()
|
||||
? contribution.label.trim()
|
||||
: extension.name;
|
||||
const decorated = {
|
||||
...themeValue,
|
||||
displayName: label,
|
||||
...(type ? { type } : {}),
|
||||
};
|
||||
if (!isVsCodeThemeFile(decorated)) throw new Error("not a VS Code color theme");
|
||||
parsed.push({ theme: parseVsCodeThemeFile(decorated), sourceName: path.split("/").at(-1)! });
|
||||
} catch (cause) {
|
||||
failures.push(cause instanceof Error ? cause.message : "theme could not be read");
|
||||
}
|
||||
}
|
||||
if (parsed.length === 0) {
|
||||
throw new Error(failures[0] ?? "That extension has no compatible color themes.");
|
||||
}
|
||||
const paired = pairVsCodeThemes(resolveThemeLabelCollisions(parsed));
|
||||
return resolveThemeLabelCollisions(paired.map((theme) => ({ theme })));
|
||||
}
|
||||
Generated
+9
@@ -542,6 +542,9 @@ importers:
|
||||
'@lexical/react':
|
||||
specifier: ^0.41.0
|
||||
version: 0.41.0([email protected]([email protected]))([email protected])([email protected])
|
||||
'@noble/hashes':
|
||||
specifier: 'catalog:'
|
||||
version: 1.8.0
|
||||
'@pierre/diffs':
|
||||
specifier: 'catalog:'
|
||||
version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
|
||||
@@ -572,6 +575,12 @@ importers:
|
||||
jose:
|
||||
specifier: 'catalog:'
|
||||
version: 6.2.2
|
||||
jsonc-parser:
|
||||
specifier: 3.3.1
|
||||
version: 3.3.1
|
||||
jszip:
|
||||
specifier: 3.10.1
|
||||
version: 3.10.1
|
||||
lexical:
|
||||
specifier: ^0.41.0
|
||||
version: 0.41.0
|
||||
|
||||
Reference in new issue
Block a user