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