Open History to see the last commit
1import { sha256 } from "@noble/hashes/sha2";
2import JSZip from "jszip";
3import { parse, type ParseError } from "jsonc-parser";
4
5import type { ThemeDefinition } from "./themePalette";
6import {
7 isVsCodeThemeFile,
8 pairVsCodeThemes,
9 parseVsCodeThemeFile,
10 resolveThemeLabelCollisions,
11} from "./vscodeThemeImport";
12
13const OPEN_VSX_SEARCH_URL = "https://open-vsx.org/api/-/search";
14const MAX_VSIX_BYTES = 20 * 1024 * 1024;
15const MAX_SEARCH_BYTES = 512 * 1024;
16const MAX_DETAIL_BYTES = 256 * 1024;
17const MAX_MANIFEST_BYTES = 256 * 1024;
18const SEARCH_REQUEST_TIMEOUT_MS = 10_000;
19const MAX_THEME_BYTES = 256 * 1024;
20const MAX_ZIP_ENTRIES = 5_000;
21const MAX_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
22const MAX_COMPRESSION_RATIO = 200;
23const MAX_THEMES_PER_EXTENSION = 40;
24const MAX_INCLUDE_DEPTH = 8;
25const MAX_PACKAGE_PATH_LENGTH = 1_024;
26const MAX_COLOR_VALUE_LENGTH = 128;
27const MAX_RESOLVED_THEME_FILES = MAX_THEMES_PER_EXTENSION * MAX_INCLUDE_DEPTH;
28const SUPPORTED_LICENSES = new Set([
29 "0BSD",
30 "Apache-2.0",
31 "BSD-2-Clause",
32 "BSD-3-Clause",
33 "CC0-1.0",
34 "ISC",
35 "MIT",
36 "MPL-2.0",
37 "Unlicense",
38]);
39const USED_WORKBENCH_COLORS = new Set([
40 "activityBar.background",
41 "activityBarBadge.background",
42 "badge.background",
43 "button.background",
44 "button.foreground",
45 "contrastBorder",
46 "descriptionForeground",
47 "disabledForeground",
48 "dropdown.background",
49 "dropdown.border",
50 "editor.background",
51 "editor.foreground",
52 "editor.findMatchBackground",
53 "editor.findMatchForeground",
54 "editor.findMatchHighlightBackground",
55 "editor.findMatchHighlightForeground",
56 "editor.selectionBackground",
57 "editorCursor.foreground",
58 "editorError.foreground",
59 "editorGroup.border",
60 "editorPane.background",
61 "editorWarning.foreground",
62 "editorWidget.background",
63 "errorForeground",
64 "focusBorder",
65 "foreground",
66 "input.border",
67 "input.placeholderForeground",
68 "list.activeSelectionBackground",
69 "list.hoverBackground",
70 "list.inactiveSelectionBackground",
71 "menu.background",
72 "panel.background",
73 "panel.border",
74 "progressBar.background",
75 "quickInput.background",
76 "scrollbarSlider.background",
77 "sideBar.background",
78 "sideBar.border",
79 "sideBar.foreground",
80 "terminal.background",
81 "terminal.foreground",
82 "terminal.selectionBackground",
83 "terminalCursor.foreground",
84 "textCodeBlock.background",
85 "textLink.foreground",
86]);
87
88export type OpenVsxThemeSort = "downloadCount" | "rating" | "timestamp" | "relevance";
89
90export type OpenVsxThemeExtension = {
91 id: string;
92 collectionId: string;
93 name: string;
94 publisher: string;
95 description: string;
96 downloadCount: number;
97 iconUrl: string | null;
98 sourceUrl: string | null;
99 manifestUrl: string;
100 sha256Url: string;
101 vsixUrl: string;
102 version: string;
103 license: string;
104};
105
106export type OpenVsxThemeSearchOptions = {
107 signal?: AbortSignal;
108 sortBy?: OpenVsxThemeSort;
109};
110
111type ThemeContribution = { label?: unknown; uiTheme?: unknown; path?: unknown };
112
113function isRecord(value: unknown): value is Record<string, unknown> {
114 return typeof value === "object" && value !== null && !Array.isArray(value);
115}
116
117function shortHash(value: string): string {
118 return [...sha256(new TextEncoder().encode(value))]
119 .slice(0, 6)
120 .map((byte) => byte.toString(16).padStart(2, "0"))
121 .join("");
122}
123
124function openVsxThemeId(extensionId: string, source: string): string {
125 return `ovx-theme-${shortHash(`${extensionId}:${source}`)}`;
126}
127
128function openVsxCollectionId(extensionId: string): string {
129 const normalized = `open-vsx:${extensionId.toLowerCase()}`;
130 return /^[a-z0-9][a-z0-9.:-]{0,127}$/.test(normalized)
131 ? normalized
132 : `open-vsx:${shortHash(extensionId)}`;
133}
134
135function trustedOpenVsxUrl(value: unknown): string | null {
136 if (typeof value !== "string") return null;
137 try {
138 const url = new URL(value);
139 return url.protocol === "https:" && url.hostname.toLowerCase() === "open-vsx.org"
140 ? url.toString()
141 : null;
142 } catch {
143 return null;
144 }
145}
146
147function publicSourceUrl(value: unknown): string | null {
148 const rawValue =
149 typeof value === "string"
150 ? value
151 : isRecord(value) && typeof value.url === "string"
152 ? value.url
153 : null;
154 if (!rawValue) return null;
155 try {
156 const url = new URL(rawValue);
157 return url.protocol === "https:" && !url.username && !url.password ? url.toString() : null;
158 } catch {
159 return null;
160 }
161}
162
163function themeContributions(manifest: Record<string, unknown>): ThemeContribution[] {
164 const contributes = isRecord(manifest.contributes) ? manifest.contributes : null;
165 return Array.isArray(contributes?.themes)
166 ? (contributes.themes.filter(isRecord) as ThemeContribution[])
167 : [];
168}
169
170function manifestLicenseMatches(manifest: Record<string, unknown>, license: string): boolean {
171 return (
172 typeof manifest.license === "string" &&
173 manifest.license.trim().toLowerCase() === license.toLowerCase()
174 );
175}
176
177function extensionFromDetail(value: unknown): OpenVsxThemeExtension | null {
178 if (!isRecord(value) || !isRecord(value.files)) {
179 throw new Error("Open VSX returned malformed theme details.");
180 }
181 const namespace = typeof value.namespace === "string" ? value.namespace.trim() : "";
182 const extensionName = typeof value.name === "string" ? value.name.trim() : "";
183 const displayName =
184 (typeof value.displayName === "string" ? value.displayName.trim() : "") || extensionName;
185 const version = typeof value.version === "string" ? value.version.trim() : "";
186 const license = typeof value.license === "string" ? value.license.trim() : "";
187 const manifestUrl = trustedOpenVsxUrl(value.files.manifest);
188 const sha256Url = trustedOpenVsxUrl(value.files.sha256);
189 const vsixUrl = trustedOpenVsxUrl(value.files.download);
190 if (!namespace || !extensionName || !version || !manifestUrl || !sha256Url || !vsixUrl) {
191 throw new Error("Open VSX returned malformed theme details.");
192 }
193 if (!SUPPORTED_LICENSES.has(license)) return null;
194 const id = `${namespace}.${extensionName}`;
195 return {
196 id,
197 collectionId: openVsxCollectionId(id),
198 name: displayName,
199 publisher: namespace,
200 description: typeof value.description === "string" ? value.description : "",
201 downloadCount:
202 typeof value.downloadCount === "number" && Number.isFinite(value.downloadCount)
203 ? value.downloadCount
204 : 0,
205 iconUrl: trustedOpenVsxUrl(value.files.icon),
206 sourceUrl:
207 publicSourceUrl(value.repository) ??
208 publicSourceUrl(value.homepage) ??
209 publicSourceUrl(value.url),
210 manifestUrl,
211 sha256Url,
212 vsixUrl,
213 version,
214 license,
215 };
216}
217
218async function withSearchTimeout<T>(
219 operation: (signal: AbortSignal) => Promise<T>,
220 parentSignal?: AbortSignal,
221): Promise<T> {
222 const controller = new AbortController();
223 const abort = () => controller.abort();
224 if (parentSignal?.aborted) abort();
225 else parentSignal?.addEventListener("abort", abort, { once: true });
226 const timeout = setTimeout(abort, SEARCH_REQUEST_TIMEOUT_MS);
227 try {
228 return await operation(controller.signal);
229 } catch (cause) {
230 if (controller.signal.aborted && !parentSignal?.aborted) {
231 throw new Error("Open VSX took too long to respond.", { cause });
232 }
233 throw cause;
234 } finally {
235 clearTimeout(timeout);
236 parentSignal?.removeEventListener("abort", abort);
237 }
238}
239
240export async function searchOpenVsxThemes(
241 query: string,
242 { signal, sortBy = "downloadCount" }: OpenVsxThemeSearchOptions = {},
243): Promise<OpenVsxThemeExtension[]> {
244 const searchText = query.trim();
245 if (!searchText) return [];
246 const url = new URL(OPEN_VSX_SEARCH_URL);
247 url.searchParams.set("query", searchText);
248 url.searchParams.set("category", "Themes");
249 url.searchParams.set("sortBy", sortBy);
250 url.searchParams.set("sortOrder", "desc");
251 url.searchParams.set("size", "16");
252 const value = await withSearchTimeout(async (requestSignal) => {
253 const response = await fetch(url, { signal: requestSignal });
254 if (!response.ok) throw new Error("Open VSX search is unavailable right now.");
255 const searchBytes = await readCappedResponse(
256 response,
257 MAX_SEARCH_BYTES,
258 "Open VSX returned an unexpectedly large response.",
259 );
260 try {
261 return JSON.parse(new TextDecoder().decode(searchBytes)) as unknown;
262 } catch {
263 throw new Error("Open VSX returned an unreadable response.");
264 }
265 }, signal);
266 if (!isRecord(value) || !Array.isArray(value.extensions)) {
267 throw new Error("Open VSX returned an unreadable search response.");
268 }
269 const identities = value.extensions.flatMap((candidate): Array<[string, string]> => {
270 if (!isRecord(candidate)) return [];
271 const namespace = typeof candidate.namespace === "string" ? candidate.namespace : "";
272 const name = typeof candidate.name === "string" ? candidate.name : "";
273 return namespace && name ? [[namespace, name]] : [];
274 });
275 const details = await Promise.allSettled(
276 identities.slice(0, 16).map(([namespace, name]) =>
277 withSearchTimeout(async (requestSignal) => {
278 const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;
279 const detailResponse = await fetch(detailUrl, { signal: requestSignal });
280 if (!detailResponse.ok) throw new Error("Open VSX theme details are unavailable.");
281 const detailBytes = await readCappedResponse(
282 detailResponse,
283 MAX_DETAIL_BYTES,
284 "Open VSX returned an unexpectedly large detail response.",
285 );
286 try {
287 const extension = extensionFromDetail(JSON.parse(new TextDecoder().decode(detailBytes)));
288 if (!extension) return null;
289 const [manifestResponse, packageResponse] = await Promise.all([
290 fetch(extension.manifestUrl, { signal: requestSignal }),
291 fetch(extension.vsixUrl, { method: "HEAD", signal: requestSignal }),
292 ]);
293 if (!manifestResponse.ok) throw new Error("manifest unavailable");
294 if (!packageResponse.ok) return null;
295 const packageLength = Number(packageResponse.headers.get("content-length"));
296 if (Number.isFinite(packageLength) && packageLength > MAX_VSIX_BYTES) {
297 return null;
298 }
299 const manifestBytes = await readCappedResponse(
300 manifestResponse,
301 MAX_MANIFEST_BYTES,
302 "Open VSX returned an unexpectedly large manifest.",
303 );
304 const manifest = parseJsoncObject(
305 new TextDecoder().decode(manifestBytes),
306 "Extension manifest",
307 );
308 return themeContributions(manifest).length > 0 &&
309 manifestLicenseMatches(manifest, extension.license)
310 ? extension
311 : null;
312 } catch {
313 throw new Error("Open VSX returned unreadable theme details.");
314 }
315 }, signal),
316 ),
317 );
318 if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");
319 const completedDetails = details.filter((result) => result.status === "fulfilled");
320 if (identities.length > 0 && completedDetails.length === 0) {
321 throw new Error("Open VSX theme details are unavailable right now.");
322 }
323 return completedDetails.flatMap((result) => (result.value ? [result.value] : [])).slice(0, 8);
324}
325
326function parseJsoncObject(source: string, description: string): Record<string, unknown> {
327 const errors: ParseError[] = [];
328 const value: unknown = parse(source, errors, { allowTrailingComma: true });
329 if (errors.length > 0 || !isRecord(value)) throw new Error(`${description} is not valid JSON.`);
330 return value;
331}
332
333function sanitizeThemeObject(value: Record<string, unknown>): Record<string, unknown> {
334 const colors: Record<string, string> = {};
335 if (isRecord(value.colors)) {
336 for (const [key, color] of Object.entries(value.colors)) {
337 if (
338 USED_WORKBENCH_COLORS.has(key) &&
339 typeof color === "string" &&
340 color.length <= MAX_COLOR_VALUE_LENGTH
341 ) {
342 colors[key] = color;
343 }
344 }
345 }
346 return {
347 ...(typeof value.include === "string" ? { include: value.include } : {}),
348 colors,
349 };
350}
351
352function normalizePackagePath(path: string, relativeTo = "extension/"): string {
353 if (
354 path.length > MAX_PACKAGE_PATH_LENGTH ||
355 path.includes("\0") ||
356 path.startsWith("/") ||
357 /^[a-zA-Z]:/.test(path)
358 ) {
359 throw new Error("Theme path is not a safe relative package path.");
360 }
361 const normalizedInput = path.replaceAll("\\", "/");
362 const baseSegments = relativeTo.split("/").slice(0, -1);
363 const segments = baseSegments;
364 for (const segment of normalizedInput.split("/")) {
365 if (!segment || segment === ".") continue;
366 if (segment === "..") {
367 if (segments.length <= 1) throw new Error("Theme path escapes the extension package.");
368 segments.pop();
369 continue;
370 }
371 segments.push(segment);
372 }
373 if (segments[0] !== "extension") segments.unshift("extension");
374 return segments.join("/");
375}
376
377function contributionType(uiTheme: unknown): string | null {
378 if (uiTheme === "vs") return "light";
379 if (uiTheme === "vs-dark") return "dark";
380 if (uiTheme === "hc-black" || uiTheme === "hc-light") return uiTheme;
381 return null;
382}
383
384type ZipEntrySizes = {
385 uncompressedSize?: unknown;
386};
387
388type InspectableZipObject = JSZip.JSZipObject & {
389 _data?: ZipEntrySizes;
390 unsafeOriginalName?: string;
391 internalStream?: (type: "uint8array") => JSZip.JSZipStreamHelper<Uint8Array>;
392};
393
394function inspectZipDirectory(bytes: Uint8Array): Uint8Array {
395 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
396 const minimumOffset = Math.max(0, bytes.byteLength - 65_557);
397 let endOffset = bytes.byteLength - 22;
398 while (
399 endOffset >= minimumOffset &&
400 (view.getUint32(endOffset, true) !== 0x06054b50 ||
401 endOffset + 22 + view.getUint16(endOffset + 20, true) !== bytes.byteLength)
402 ) {
403 endOffset -= 1;
404 }
405 if (endOffset < minimumOffset) throw new Error("That extension package has no ZIP directory.");
406
407 const directorySize = view.getUint32(endOffset + 12, true);
408 const directoryOffset = view.getUint32(endOffset + 16, true);
409 const directoryEnd = directoryOffset + directorySize;
410 if (directoryEnd !== endOffset || directoryEnd > bytes.byteLength) {
411 throw new Error("That extension package has an invalid ZIP directory.");
412 }
413
414 let entryCount = 0;
415 let totalUncompressed = 0;
416 let offset = directoryOffset;
417 while (offset < directoryEnd) {
418 if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50) {
419 throw new Error("That extension package has an invalid ZIP directory.");
420 }
421 entryCount += 1;
422 if (entryCount > MAX_ZIP_ENTRIES) {
423 throw new Error("That extension package has too many files.");
424 }
425 const compressed = view.getUint32(offset + 20, true);
426 const uncompressed = view.getUint32(offset + 24, true);
427 if (compressed === 0xffffffff || uncompressed === 0xffffffff) {
428 throw new Error("That extension package has unsupported ZIP64 metadata.");
429 }
430 totalUncompressed += uncompressed;
431 if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
432 throw new Error("That extension package expands beyond the safe import limit.");
433 }
434 if (
435 uncompressed > 0 &&
436 (compressed === 0 || uncompressed / compressed > MAX_COMPRESSION_RATIO)
437 ) {
438 throw new Error("That extension package has an unsafe compression ratio.");
439 }
440 const nameLength = view.getUint16(offset + 28, true);
441 const extraLength = view.getUint16(offset + 30, true);
442 const commentLength = view.getUint16(offset + 32, true);
443 offset += 46 + nameLength + extraLength + commentLength;
444 }
445 if (offset !== directoryEnd)
446 throw new Error("That extension package has an invalid ZIP directory.");
447
448 const commentLength = view.getUint16(endOffset + 20, true);
449 if (commentLength === 0) return bytes;
450
451 // JSZip mistakes EOCD-like bytes inside an archive comment for the real EOCD.
452 // The comment is not needed for theme import, so remove it before parsing.
453 const withoutComment = bytes.slice(0, endOffset + 22);
454 withoutComment[endOffset + 20] = 0;
455 withoutComment[endOffset + 21] = 0;
456 return withoutComment;
457}
458
459function inspectZip(zip: JSZip): void {
460 const entries = Object.values(zip.files) as InspectableZipObject[];
461 if (entries.length > MAX_ZIP_ENTRIES)
462 throw new Error("That extension package has too many files.");
463
464 for (const entry of entries) {
465 if (entry.unsafeOriginalName) normalizePackagePath(entry.unsafeOriginalName);
466 }
467}
468
469async function readZipText(
470 zip: JSZip,
471 path: string,
472 description: string,
473 signal?: AbortSignal,
474): Promise<string> {
475 signal?.throwIfAborted();
476 const file = zip.file(path) as InspectableZipObject | null;
477 if (!file) throw new Error(`${description} is missing from the extension package.`);
478 if (typeof file._data?.uncompressedSize !== "number" || !file.internalStream) {
479 throw new Error(`${description} has unreadable size metadata.`);
480 }
481 if (file._data.uncompressedSize > MAX_THEME_BYTES) {
482 throw new Error(`${description} is too large.`);
483 }
484
485 return new Promise((resolve, reject) => {
486 const chunks: Uint8Array[] = [];
487 let byteLength = 0;
488 let settled = false;
489 const stream = file.internalStream!("uint8array");
490 const cleanup = () => signal?.removeEventListener("abort", handleAbort);
491 const handleAbort = () => {
492 if (settled) return;
493 settled = true;
494 stream.pause();
495 cleanup();
496 reject(signal?.reason);
497 };
498 signal?.addEventListener("abort", handleAbort, { once: true });
499 stream
500 .on("data", (chunk) => {
501 if (settled) return;
502 byteLength += chunk.byteLength;
503 if (byteLength > MAX_THEME_BYTES) {
504 settled = true;
505 stream.pause();
506 cleanup();
507 reject(new Error(`${description} is too large.`));
508 return;
509 }
510 chunks.push(chunk);
511 })
512 .on("error", (cause) => {
513 if (settled) return;
514 settled = true;
515 cleanup();
516 reject(cause);
517 })
518 .on("end", () => {
519 if (settled) return;
520 settled = true;
521 cleanup();
522 const bytes = new Uint8Array(byteLength);
523 let offset = 0;
524 for (const chunk of chunks) {
525 bytes.set(chunk, offset);
526 offset += chunk.byteLength;
527 }
528 resolve(new TextDecoder().decode(bytes));
529 })
530 .resume();
531 });
532}
533
534async function loadThemeObject(
535 zip: JSZip,
536 path: string,
537 cache: Map<string, Record<string, unknown>>,
538 budget: { files: number },
539 ancestors: ReadonlySet<string> = new Set(),
540 signal?: AbortSignal,
541): Promise<Record<string, unknown>> {
542 signal?.throwIfAborted();
543 if (ancestors.size >= MAX_INCLUDE_DEPTH) throw new Error("Theme includes are nested too deeply.");
544 if (ancestors.has(path)) throw new Error("Theme includes contain a cycle.");
545 const cached = cache.get(path);
546 if (cached) return cached;
547 budget.files += 1;
548 if (budget.files > MAX_RESOLVED_THEME_FILES) {
549 throw new Error("That extension references too many theme files.");
550 }
551
552 const value = sanitizeThemeObject(
553 parseJsoncObject(await readZipText(zip, path, path, signal), path),
554 );
555 if (typeof value.include !== "string") {
556 cache.set(path, value);
557 return value;
558 }
559
560 const includePath = normalizePackagePath(value.include, path);
561 const nextAncestors = new Set(ancestors);
562 nextAncestors.add(path);
563 const base = await loadThemeObject(zip, includePath, cache, budget, nextAncestors, signal);
564 const resolved = {
565 ...base,
566 ...value,
567 colors: {
568 ...(isRecord(base.colors) ? base.colors : {}),
569 ...(isRecord(value.colors) ? value.colors : {}),
570 },
571 };
572 cache.set(path, resolved);
573 return resolved;
574}
575
576async function readCappedResponse(
577 response: Response,
578 limit: number,
579 tooLargeMessage: string,
580): Promise<Uint8Array> {
581 const contentLength = response.headers.get("content-length");
582 if (contentLength && Number(contentLength) > limit) throw new Error(tooLargeMessage);
583 if (!response.body) {
584 const bytes = new Uint8Array(await response.arrayBuffer());
585 if (bytes.byteLength > limit) throw new Error(tooLargeMessage);
586 return bytes;
587 }
588
589 const reader = response.body.getReader();
590 const chunks: Uint8Array[] = [];
591 let byteLength = 0;
592 try {
593 while (true) {
594 const { done, value } = await reader.read();
595 if (done) break;
596 byteLength += value.byteLength;
597 if (byteLength > limit) {
598 await reader.cancel();
599 throw new Error(tooLargeMessage);
600 }
601 chunks.push(value);
602 }
603 } finally {
604 reader.releaseLock();
605 }
606
607 const result = new Uint8Array(byteLength);
608 let offset = 0;
609 for (const chunk of chunks) {
610 result.set(chunk, offset);
611 offset += chunk.byteLength;
612 }
613 return result;
614}
615
616async function fetchPackage(url: string, signal?: AbortSignal): Promise<Uint8Array> {
617 const response = await fetch(url, signal ? { signal } : {});
618 if (!response.ok) throw new Error("That Open VSX theme could not be downloaded.");
619 return readCappedResponse(
620 response,
621 MAX_VSIX_BYTES,
622 "That theme extension is too large to import safely.",
623 );
624}
625
626export async function importOpenVsxThemeExtension(
627 extension: OpenVsxThemeExtension,
628 signal?: AbortSignal,
629): Promise<ReadonlyArray<ThemeDefinition>> {
630 const manifestResponse = await fetch(extension.manifestUrl, signal ? { signal } : {});
631 if (!manifestResponse.ok) throw new Error("That Open VSX extension has no readable manifest.");
632 const manifestBytes = await readCappedResponse(
633 manifestResponse,
634 MAX_MANIFEST_BYTES,
635 "That Open VSX extension manifest is too large.",
636 );
637 const manifest = parseJsoncObject(new TextDecoder().decode(manifestBytes), "Extension manifest");
638 const advertisedContributions = themeContributions(manifest);
639 if (advertisedContributions.length === 0) {
640 throw new Error("That extension does not contain color themes.");
641 }
642 if (advertisedContributions.length > MAX_THEMES_PER_EXTENSION) {
643 throw new Error("That extension contains too many color themes to import safely.");
644 }
645
646 const packageBytes = await fetchPackage(extension.vsixUrl, signal);
647 signal?.throwIfAborted();
648 const checksumResponse = await fetch(extension.sha256Url, signal ? { signal } : {});
649 if (!checksumResponse.ok) throw new Error("That Open VSX theme has no readable checksum.");
650 const expectedChecksum = new TextDecoder()
651 .decode(
652 await readCappedResponse(
653 checksumResponse,
654 256,
655 "That Open VSX checksum response is invalid.",
656 ),
657 )
658 .trim()
659 .split(/\s+/)[0];
660 if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) {
661 throw new Error("That Open VSX theme has an invalid checksum.");
662 }
663 signal?.throwIfAborted();
664 const actualChecksum = [...sha256(packageBytes)]
665 .map((byte) => byte.toString(16).padStart(2, "0"))
666 .join("");
667 if (actualChecksum.toLowerCase() !== expectedChecksum.toLowerCase()) {
668 throw new Error("That Open VSX theme failed its integrity check.");
669 }
670 signal?.throwIfAborted();
671 let zip: JSZip;
672 try {
673 const inspectedPackageBytes = inspectZipDirectory(packageBytes);
674 zip = await JSZip.loadAsync(inspectedPackageBytes);
675 signal?.throwIfAborted();
676 inspectZip(zip);
677 } catch (cause) {
678 if (signal?.aborted) signal.throwIfAborted();
679 if (cause instanceof Error && cause.message.startsWith("That extension package")) throw cause;
680 throw new Error("That Open VSX extension package could not be opened.", { cause });
681 }
682
683 const packagedManifest = parseJsoncObject(
684 await readZipText(zip, "extension/package.json", "Extension manifest", signal),
685 "Extension manifest",
686 );
687 if (
688 typeof packagedManifest.publisher !== "string" ||
689 packagedManifest.publisher.toLowerCase() !== extension.publisher.toLowerCase() ||
690 typeof packagedManifest.name !== "string" ||
691 `${packagedManifest.publisher}.${packagedManifest.name}`.toLowerCase() !==
692 extension.id.toLowerCase() ||
693 packagedManifest.version !== extension.version
694 ) {
695 throw new Error("That extension package does not match the selected Open VSX theme.");
696 }
697 if (!manifestLicenseMatches(packagedManifest, extension.license)) {
698 throw new Error("That extension package does not match its advertised license.");
699 }
700 const contributions = themeContributions(packagedManifest);
701 if (contributions.length === 0) throw new Error("That extension does not contain color themes.");
702 if (contributions.length > MAX_THEMES_PER_EXTENSION) {
703 throw new Error("That extension contains too many color themes to import safely.");
704 }
705
706 const parsed: Array<{ theme: ThemeDefinition; sourceName: string; sourcePath: string }> = [];
707 const failures: string[] = [];
708 const themeCache = new Map<string, Record<string, unknown>>();
709 const themeBudget = { files: 0 };
710 for (const contribution of contributions) {
711 signal?.throwIfAborted();
712 if (typeof contribution.path !== "string") {
713 failures.push("theme path is missing");
714 continue;
715 }
716 try {
717 const path = normalizePackagePath(contribution.path);
718 const themeValue = await loadThemeObject(
719 zip,
720 path,
721 themeCache,
722 themeBudget,
723 new Set(),
724 signal,
725 );
726 const type = contributionType(contribution.uiTheme);
727 const label =
728 typeof contribution.label === "string" && contribution.label.trim()
729 ? contribution.label.trim()
730 : extension.name;
731 const decorated = {
732 ...themeValue,
733 displayName: label,
734 ...(type ? { type } : {}),
735 };
736 if (!isVsCodeThemeFile(decorated)) throw new Error("not a VS Code color theme");
737 parsed.push({
738 theme: parseVsCodeThemeFile(decorated),
739 sourceName: path.split("/").at(-1)!,
740 sourcePath: path,
741 });
742 } catch (cause) {
743 signal?.throwIfAborted();
744 failures.push(cause instanceof Error ? cause.message : "theme could not be read");
745 }
746 }
747 if (failures.length > 0) {
748 throw new Error("One or more color themes in that extension could not be imported safely.");
749 }
750 if (parsed.length === 0) {
751 throw new Error("That extension has no compatible color themes.");
752 }
753 const extensionId = extension.id.toLowerCase();
754 const sourcePathCounts = new Map<string, number>();
755 for (const { sourcePath } of parsed) {
756 sourcePathCounts.set(sourcePath, (sourcePathCounts.get(sourcePath) ?? 0) + 1);
757 }
758 const sourcePathOccurrences = new Map<string, number>();
759 const sourceIdentities = parsed.map(({ sourcePath }) => {
760 if (sourcePathCounts.get(sourcePath) === 1) return sourcePath;
761 const occurrence = sourcePathOccurrences.get(sourcePath) ?? 0;
762 sourcePathOccurrences.set(sourcePath, occurrence + 1);
763 return occurrence === 0 ? sourcePath : `${sourcePath}\0${occurrence}`;
764 });
765 const resolved = resolveThemeLabelCollisions(parsed).map((theme, index) => ({
766 ...theme,
767 id: openVsxThemeId(extensionId, sourceIdentities[index]!),
768 }));
769 const paired = pairVsCodeThemes(resolved, {
770 pairedId: (light, dark) => openVsxThemeId(extensionId, [light.id, dark.id].sort().join(":")),
771 });
772 const themes = resolveThemeLabelCollisions(paired.map((theme) => ({ theme })));
773 const collection = {
774 id: extension.collectionId,
775 label: extension.name.slice(0, 48),
776 };
777 return themes.map((theme) => ({ ...theme, collection }));
778}