Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

test: theme import, contrast and presets

ogsamrat6568503ffd54
diff --git a/apps/app/tests/theme-analytics.test.ts b/apps/app/tests/theme-analytics.test.ts
new file mode 100644
index 00000000..912ce34d
--- /dev/null
+++ b/apps/app/tests/theme-analytics.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+
+class MemoryStorage {
+ private values = new Map<string, string>();
+ getItem(key: string) { return this.values.has(key) ? this.values.get(key)! : null; }
+ setItem(key: string, value: string) { this.values.set(key, String(value)); }
+ removeItem(key: string) { this.values.delete(key); }
+ clear() { this.values.clear(); }
+}
+
+Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: { localStorage: new MemoryStorage(), addEventListener: () => undefined },
+});
+type Inspector = { events: (limit?: number) => Array<{ name: string; data: unknown }>; clearEvents: () => void };
+const inspector = () => (window as unknown as { __omnirush: Inspector }).__omnirush;
+
+const { ensureInspectorInstalled } = await import("../src/app/lib/app-inspector");
+const { trackThemeChanged, customThemeFromPreset } = await import("../src/react-app/domains/settings/appearance/theme-state");
+const { findPreset } = await import("../src/app/themes/palette");
+
+describe("theme_changed", () => {
+ beforeEach(() => {
+ ensureInspectorInstalled();
+ inspector().clearEvents();
+ });
+
+ test("preset picks carry kind, preset id and mode only", () => {
+ trackThemeChanged({ kind: "preset", preset: "fjord", mode: "light" });
+ const event = inspector().events(10).find((entry) => entry.name === "analytics.theme_changed")!;
+ expect(event.data).toEqual({ kind: "preset", preset: "fjord", mode: "light" });
+ });
+
+ test("custom themes never send colours or the theme name", () => {
+ trackThemeChanged({ kind: "custom", mode: "dark" });
+ const event = inspector().events(10).find((entry) => entry.name === "analytics.theme_changed")!;
+ expect(event.data).toEqual({ kind: "custom", mode: "dark" });
+ expect(JSON.stringify(event.data)).not.toMatch(/#[0-9a-f]{6}/i);
+ });
+
+ test("a new custom theme copies the preset's versions", () => {
+ const midnight = customThemeFromPreset(findPreset("midnight")!);
+ expect(midnight.modes).toEqual(["dark"]);
+ expect(midnight.dark).toEqual(findPreset("midnight")!.variants.dark!);
+ expect(midnight.dark).not.toBe(findPreset("midnight")!.variants.dark!);
+ expect(midnight.name).toBe("My theme");
+ });
+});
diff --git a/apps/app/tests/theme-presets.test.ts b/apps/app/tests/theme-presets.test.ts
new file mode 100644
index 00000000..e3b0a74f
--- /dev/null
+++ b/apps/app/tests/theme-presets.test.ts
@@ -0,0 +1,422 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ contrastRatio,
+ contrastRows,
+ contrastWarnings,
+ fixContrast,
+ suggestColour,
+ textBackgrounds,
+ textSafeAccent,
+ worstRatio,
+} from "../src/app/themes/contrast";
+import { LEGACY_XTERM_THEME, monacoThemeFor, xtermThemeFor } from "../src/app/themes/editor-themes";
+import {
+ allPaletteVarNames,
+ applyPaletteVars,
+ findPreset,
+ isSafeVar,
+ paletteVars,
+ pickVariant,
+ presetModes,
+ resetAppliedPaletteForTests,
+ resolveActiveTheme,
+} from "../src/app/themes/palette";
+import { THEME_PRESETS } from "../src/app/themes/presets";
+import { ANSI_KEYS, type CustomTheme } from "../src/app/themes/types";
+
+const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
+
+describe("contrast maths", () => {
+ test("WCAG ratios", () => {
+ expect(contrastRatio("#000000", "#ffffff")).toBeCloseTo(21, 5);
+ expect(contrastRatio("#ffffff", "#ffffff")).toBe(1);
+ expect(contrastRatio("#4c6e98", "#e5e9f0")).toBeCloseTo(4.321, 3);
+ expect(contrastRatio("#777777", "#ffffff")).toBeCloseTo(4.478, 2);
+ });
+
+ test("fixContrast matches the preset generator", () => {
+ expect(fixContrast("#777b84", "#111113", 4.5)).toBe("#787c85");
+ expect(fixContrast("#218358", "#f9f9fb", 4.5)).toBe("#208157");
+ expect(fixContrast("#4c6e98", "#e5e9f0", 4.5)).toBe("#496a93");
+ expect(fixContrast("#b08f95", "#fff8f6", 4.5)).toBe("#93676f");
+ expect(fixContrast("#ffffff", "#ffffff", 4.5)).toBe("#757575");
+ expect(fixContrast("#123456", "#000000", 7)).toBe("#589adc");
+ expect(fixContrast("#000000", "#ffffff", 4.5)).toBe("#000000");
+ });
+
+ test("suggestions pass on every background", () => {
+ const bgs = ["#fff8f6", "#fbefec", "#ffffff", "#fbefec"];
+ const suggestion = suggestColour("#b08f95", bgs, 4.5);
+ expect(worstRatio(suggestion, bgs)).toBeGreaterThanOrEqual(4.5);
+ });
+
+ test("every preset variant passes every pair (AA, AAA body text for high contrast)", () => {
+ for (const preset of THEME_PRESETS) {
+ for (const mode of presetModes(preset)) {
+ const rows = contrastRows(preset.variants[mode]!, preset.target === "AAA");
+ const failing = rows.filter((row) => !row.pass).map((row) => `${preset.id}/${mode}: ${row.label} ${row.ratio.toFixed(2)}`);
+ expect(failing).toEqual([]);
+ expect(rows.length).toBeGreaterThanOrEqual(45);
+ }
+ }
+ });
+
+ test("text-safe accent fixes Fjord light links and keeps passing accents", () => {
+ const fjord = findPreset("fjord")!.variants.light!;
+ expect(worstRatio(fjord.accent, textBackgrounds(fjord))).toBeLessThan(4.5);
+ const safe = textSafeAccent(fjord);
+ expect(safe).not.toBe(fjord.accent);
+ expect(worstRatio(safe, textBackgrounds(fjord))).toBeGreaterThanOrEqual(4.5);
+ const midnight = findPreset("midnight")!.variants.dark!;
+ expect(textSafeAccent(midnight)).toBe(midnight.accent);
+ });
+
+ test("warnings group failing pairs with a passing suggestion", () => {
+ const v = clone(findPreset("rose")!.variants.light!);
+ v.textMuted = "#b08f95";
+ const warnings = contrastWarnings(v);
+ const muted = warnings.find((w) => w.token === "textMuted")!;
+ expect(muted).toBeDefined();
+ expect(muted.rows.length).toBeGreaterThan(0);
+ expect(worstRatio(muted.suggestion, textBackgrounds(v))).toBeGreaterThanOrEqual(4.5);
+ expect(contrastWarnings(findPreset("rose")!.variants.light!)).toEqual([]);
+ });
+
+ test("text on accent failure suggests a new accent fill", () => {
+ const v = clone(findPreset("default")!.variants.light!);
+ v.accent = "#e0e1e6";
+ const warning = contrastWarnings(v).find((w) => w.token === "accent")!;
+ expect(warning).toBeDefined();
+ expect(contrastRatio(v.accentText, warning.suggestion)).toBeGreaterThanOrEqual(4.5);
+ });
+});
+
+describe("preset resolution", () => {
+ const custom: CustomTheme = {
+ v: 1,
+ name: "Mine",
+ modes: ["light", "dark"],
+ light: clone(findPreset("sol")!.variants.light!),
+ dark: clone(findPreset("sol")!.variants.dark!),
+ radiusPx: 4,
+ fontSizePx: 14,
+ };
+
+ test("there are 8 presets and 15 variants with the agreed ids", () => {
+ expect(THEME_PRESETS.map((p) => p.id)).toEqual([
+ "default",
+ "midnight",
+ "fjord",
+ "sol",
+ "rose",
+ "forest",
+ "high-contrast",
+ "omnirush",
+ ]);
+ expect(THEME_PRESETS.reduce((sum, p) => sum + presetModes(p).length, 0)).toBe(15);
+ expect(presetModes(findPreset("midnight")!)).toEqual(["dark"]);
+ });
+
+ test("preset x mode picks the variant", () => {
+ for (const preset of THEME_PRESETS) {
+ for (const mode of ["light", "dark"] as const) {
+ const active = resolveActiveTheme({ kind: "preset", id: preset.id }, mode, null);
+ const expectedMode = preset.variants[mode] ? mode : "dark";
+ expect(active.mode).toBe(expectedMode);
+ expect(active.variant).toBe(preset.variants[expectedMode]!);
+ expect(active.legacy).toBe(preset.id === "default");
+ }
+ }
+ });
+
+ test("Midnight in light mode shows its dark version", () => {
+ const active = resolveActiveTheme({ kind: "preset", id: "midnight" }, "light", null);
+ expect(active.mode).toBe("dark");
+ });
+
+ test("unknown presets and a missing custom theme fall back to Default", () => {
+ expect(resolveActiveTheme({ kind: "preset", id: "nope" }, "light", null).selection).toEqual({ kind: "preset", id: "default" });
+ const active = resolveActiveTheme({ kind: "custom" }, "dark", null);
+ expect(active.selection).toEqual({ kind: "preset", id: "default" });
+ expect(active.legacy).toBe(true);
+ });
+
+ test("custom themes resolve per mode with their radius and font size", () => {
+ const light = resolveActiveTheme({ kind: "custom" }, "light", custom);
+ expect(light.variant).toBe(custom.light!);
+ expect([light.radiusPx, light.fontSizePx, light.legacy]).toEqual([4, 14, false]);
+ const darkOnly: CustomTheme = { ...custom, modes: ["dark"], light: undefined };
+ expect(resolveActiveTheme({ kind: "custom" }, "light", darkOnly).mode).toBe("dark");
+ });
+
+ test("pickVariant", () => {
+ expect(pickVariant({}, "light")).toBeNull();
+ const dark = findPreset("midnight")!.variants.dark!;
+ expect(pickVariant({ dark }, "light")).toEqual({ mode: "dark", variant: dark });
+ });
+});
+
+describe("CSS variables", () => {
+ test("Default keeps today's stylesheet apart from the dark muted text fix", () => {
+ const light = resolveActiveTheme({ kind: "preset", id: "default" }, "light", null);
+ const dark = resolveActiveTheme({ kind: "preset", id: "default" }, "dark", null);
+ expect(paletteVars(light)).toEqual({});
+ expect(paletteVars(dark)).toEqual({ "--muted-foreground": "#858991" });
+ });
+
+ test("presets map tokens to the app's variables, all values safe", () => {
+ for (const preset of THEME_PRESETS.filter((p) => p.id !== "default")) {
+ for (const mode of presetModes(preset)) {
+ const active = resolveActiveTheme({ kind: "preset", id: preset.id }, mode, null);
+ const vars = paletteVars(active, preset.variants.dark);
+ const v = preset.variants[mode]!;
+ expect(vars["--background"]).toBe(v.background);
+ expect(vars["--primary"]).toBe(v.accent);
+ expect(vars["--dls-accent"]).toBe(v.accent);
+ expect(vars["--primary-foreground"]).toBe(v.accentText);
+ expect(vars["--muted-foreground"]).toBe(v.textMuted);
+ expect(vars["--border"]).toBe(v.border);
+ expect(vars["--gray-12"]).toBe(v.text);
+ expect(vars["--slate-1"]).toBe(v.background);
+ expect(vars["--omnirush-terminal-bg"]).toBe(v.terminal.bg);
+ expect(vars["--omnirush-syntax-keyword"]).toBe(v.code.keyword);
+ expect(vars["--omnirush-highlight"]).toBe(v.highlight ?? v.accent);
+ expect(worstRatio(vars["--omnirush-link"]!, textBackgrounds(v))).toBeGreaterThanOrEqual(4.5);
+ expect(vars["--radius"]).toBeUndefined();
+ for (const [name, value] of Object.entries(vars)) expect(isSafeVar(name, value)).toBe(true);
+ }
+ }
+ });
+
+ test("custom radius and font size become variables", () => {
+ const custom = resolveActiveTheme({ kind: "custom" }, "light", {
+ v: 1,
+ name: "x",
+ modes: ["light"],
+ light: findPreset("forest")!.variants.light!,
+ radiusPx: 0,
+ fontSizePx: 16,
+ });
+ const vars = paletteVars(custom);
+ expect(vars["--radius"]).toBe("0px");
+ expect(Number(vars["--omnirush-theme-font-scale"])).toBeCloseTo(16 / 13, 3);
+ });
+
+ test("isSafeVar only allows known shapes", () => {
+ expect(isSafeVar("--background", "#aabbcc")).toBe(true);
+ expect(isSafeVar("--gray-a3", "#aabbcc0f")).toBe(true);
+ expect(isSafeVar("--dls-accent-rgb", "12 34 255")).toBe(true);
+ expect(isSafeVar("--radius", "4px")).toBe(true);
+ expect(isSafeVar("--background", "red;}body{display:none")).toBe(false);
+ expect(isSafeVar("--background", "#AABBCC")).toBe(false);
+ expect(isSafeVar("background", "#aabbcc")).toBe(false);
+ expect(isSafeVar("--x;}", "#aabbcc")).toBe(false);
+ expect(isSafeVar("--background", "url(x)")).toBe(false);
+ });
+
+ test("applyPaletteVars writes safe values and removes stale ones", () => {
+ resetAppliedPaletteForTests();
+ const store = new Map<string, string>([["--background", "#010101"], ["--keyboard-inset", "4px"]]);
+ const style = {
+ setProperty: (name: string, value: string) => void store.set(name, value),
+ removeProperty: (name: string) => {
+ const had = store.get(name) ?? "";
+ store.delete(name);
+ return had;
+ },
+ getPropertyValue: (name: string) => store.get(name) ?? "",
+ };
+ applyPaletteVars(style, { "--primary": "#123456", "--evil": "red;}body{x}" });
+ // The early-script value is adopted and removed; unrelated variables stay.
+ expect(store.has("--background")).toBe(false);
+ expect(store.get("--keyboard-inset")).toBe("4px");
+ expect(store.get("--primary")).toBe("#123456");
+ expect(store.has("--evil")).toBe(false);
+ applyPaletteVars(style, {});
+ expect(store.has("--primary")).toBe(false);
+ expect(allPaletteVarNames()).toContain("--muted-foreground");
+ });
+});
+
+describe("editor and terminal colours", () => {
+ test("Monaco theme uses the code colours", () => {
+ const active = resolveActiveTheme({ kind: "preset", id: "midnight" }, "dark", null);
+ const theme = monacoThemeFor(active);
+ expect(theme.base).toBe("vs-dark");
+ expect(theme.colors["editor.background"]).toBe(active.variant.code.bg);
+ expect(theme.rules.find((rule) => rule.token === "keyword")?.foreground).toBe(active.variant.code.keyword.slice(1));
+ expect(theme.colors["diffEditor.insertedLineBackground"]).toBe(`${active.variant.success}1f`);
+ for (const value of Object.values(theme.colors)) expect(value).toMatch(/^#[0-9a-f]{6}([0-9a-f]{2})?$/);
+ });
+
+ test("xterm gets all 16 ANSI colours; Default keeps today's terminal", () => {
+ const fjord = resolveActiveTheme({ kind: "preset", id: "fjord" }, "light", null);
+ const theme = xtermThemeFor(fjord);
+ expect(theme.background).toBe(fjord.variant.terminal.bg);
+ for (const key of ANSI_KEYS) expect(theme[key]).toBe(fjord.variant.terminal[key]);
+ expect(xtermThemeFor(resolveActiveTheme({ kind: "preset", id: "default" }, "light", null))).toBe(LEGACY_XTERM_THEME);
+ });
+});
+
+describe("theme state and persistence", () => {
+ class MemoryStorage {
+ values = new Map<string, string>();
+ getItem(key: string) {
+ return this.values.has(key) ? this.values.get(key)! : null;
+ }
+ setItem(key: string, value: string) {
+ this.values.set(key, String(value));
+ }
+ removeItem(key: string) {
+ this.values.delete(key);
+ }
+ }
+ const storage = new MemoryStorage();
+ let prefersDark = false;
+ const props = new Map<string, string>();
+ const root = {
+ dataset: {} as Record<string, string>,
+ style: {
+ colorScheme: "",
+ setProperty: (name: string, value: string) => void props.set(name, value),
+ removeProperty: (name: string) => {
+ props.delete(name);
+ return "";
+ },
+ getPropertyValue: (name: string) => props.get(name) ?? "",
+ },
+ };
+ let theme: typeof import("../src/app/theme");
+
+ beforeEach(async () => {
+ storage.values.clear();
+ props.clear();
+ root.dataset = {};
+ prefersDark = false;
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ localStorage: storage,
+ matchMedia: () => ({ matches: prefersDark, addEventListener: () => undefined, removeEventListener: () => undefined }),
+ },
+ });
+ Object.defineProperty(globalThis, "document", { configurable: true, value: { documentElement: root } });
+ theme = await import("../src/app/theme");
+ theme.resetThemeStateForTests();
+ resetAppliedPaletteForTests();
+ });
+
+ afterEach(() => {
+ delete (globalThis as Record<string, unknown>).window;
+ delete (globalThis as Record<string, unknown>).document;
+ });
+
+ test("defaults to Default preset, system mode", () => {
+ theme.bootstrapTheme();
+ expect(theme.getThemeSelection()).toEqual({ kind: "preset", id: "default" });
+ expect(root.dataset.theme).toBe("light");
+ expect(root.dataset.omnirushPalette).toBeUndefined();
+ expect(props.size).toBe(0);
+ });
+
+ test("system mode follows the OS for presets", () => {
+ prefersDark = true;
+ storage.setItem(theme.THEME_PRESET_KEY, "fjord");
+ theme.bootstrapTheme();
+ expect(root.dataset.theme).toBe("dark");
+ expect(props.get("--background")).toBe(findPreset("fjord")!.variants.dark!.background);
+ });
+
+ test("a preset choice is remembered across restarts", () => {
+ theme.bootstrapTheme();
+ theme.setThemeMode("light");
+ theme.setThemeSelection({ kind: "preset", id: "sol" });
+ expect(storage.getItem(theme.THEME_PRESET_KEY)).toBe("sol");
+ expect(root.dataset.omnirushPalette).toBe("sol");
+ theme.resetThemeStateForTests();
+ props.clear();
+ theme.bootstrapTheme();
+ expect(theme.getThemeSelection()).toEqual({ kind: "preset", id: "sol" });
+ expect(props.get("--primary")).toBe(findPreset("sol")!.variants.light!.accent);
+ });
+
+ test("Midnight with Mode light: the window is dark and the mode switch is requested", () => {
+ theme.bootstrapTheme();
+ theme.setThemeMode("light");
+ theme.setThemeSelection({ kind: "preset", id: "midnight" });
+ expect(root.dataset.theme).toBe("dark");
+ expect(theme.getResolvedThemeMode()).toBe("dark");
+ expect(theme.modeSwitchFor(["dark"], "light")).toBe("dark");
+ expect(theme.modeSwitchFor(["dark"], "dark")).toBeNull();
+ expect(theme.modeSwitchFor(["dark"], "system")).toBeNull();
+ expect(theme.modeSwitchFor(["light", "dark"], "light")).toBeNull();
+ expect(theme.modeSwitchFor(["light"], "dark")).toBe("light");
+ });
+
+ test("custom theme is saved validated and survives restart; corrupt storage is ignored", () => {
+ theme.bootstrapTheme();
+ const custom: CustomTheme = {
+ v: 1,
+ name: "Mine",
+ modes: ["dark"],
+ dark: clone(findPreset("forest")!.variants.dark!),
+ radiusPx: 12,
+ fontSizePx: 13,
+ };
+ theme.saveCustomTheme(custom);
+ theme.setThemeSelection({ kind: "custom" });
+ expect(root.dataset.omnirushPalette).toBe("custom");
+ expect(props.get("--radius")).toBe("12px");
+ theme.resetThemeStateForTests();
+ expect(theme.getCustomTheme()).toEqual(custom);
+ storage.setItem(theme.THEME_CUSTOM_KEY, '{"v":1,"name":"x","modes":["light"],"light":{"background":"red;}"}}');
+ theme.resetThemeStateForTests();
+ expect(theme.getCustomTheme()).toBeNull();
+ theme.bootstrapTheme();
+ expect(theme.getActiveTheme().selection).toEqual({ kind: "preset", id: "default" });
+ expect(() => theme.saveCustomTheme({ ...custom, name: "" })).toThrow();
+ });
+
+ test("preview shows a theme without saving it", () => {
+ theme.bootstrapTheme();
+ const custom: CustomTheme = {
+ v: 1,
+ name: "Preview",
+ modes: ["light", "dark"],
+ light: clone(findPreset("rose")!.variants.light!),
+ dark: clone(findPreset("rose")!.variants.dark!),
+ radiusPx: 7.2,
+ fontSizePx: 13,
+ };
+ theme.setThemePreview(custom);
+ expect(props.get("--primary")).toBe(custom.light!.accent);
+ expect(storage.getItem(theme.THEME_CUSTOM_KEY)).toBeNull();
+ theme.setThemePreview(null);
+ expect(props.has("--primary")).toBe(false);
+ });
+
+ test("listeners hear mode and theme changes", () => {
+ theme.bootstrapTheme();
+ let calls = 0;
+ const off = theme.subscribeToTheme(() => {
+ calls += 1;
+ });
+ theme.setThemeMode("dark");
+ theme.setThemeSelection({ kind: "preset", id: "omnirush" });
+ off();
+ theme.setThemeMode("light");
+ expect(calls).toBe(2);
+ });
+
+ test("boot variables for the early script are stored and filtered on read", () => {
+ theme.bootstrapTheme();
+ theme.setThemeSelection({ kind: "preset", id: "midnight" });
+ const raw = storage.getItem(theme.THEME_BOOT_KEY);
+ const boot = theme.readBootVars(raw, "light")!;
+ expect(boot.mode).toBe("dark");
+ expect(boot.vars["--background"]).toBe(findPreset("midnight")!.variants.dark!.background);
+ const tampered = JSON.stringify({ only: null, light: { "--background": "red;}body{x}", "--primary": "#123456", "x": "#ffffff" } });
+ expect(theme.readBootVars(tampered, "light")).toEqual({ mode: "light", vars: { "--primary": "#123456" } });
+ expect(theme.readBootVars("garbage", "light")).toBeNull();
+ });
+});
diff --git a/apps/app/tests/theme-share.test.ts b/apps/app/tests/theme-share.test.ts
new file mode 100644
index 00000000..372a16fb
--- /dev/null
+++ b/apps/app/tests/theme-share.test.ts
@@ -0,0 +1,360 @@
+import { describe, expect, test } from "bun:test";
+import { deflateRawSync } from "node:zlib";
+import { THEME_PRESETS } from "../src/app/themes/presets";
+import {
+ MAX_THEME_BYTES,
+ base64UrlToBytes,
+ bytesToBase64Url,
+ decodeShareCode,
+ encodeShareCode,
+ parseThemeJson,
+ serializeTheme,
+ themeFileName,
+ validateThemeData,
+ type Codec,
+} from "../src/app/themes/share";
+import type { CustomTheme } from "../src/app/themes/types";
+
+const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
+
+function sampleTheme(): CustomTheme {
+ const rose = THEME_PRESETS.find((preset) => preset.id === "rose")!;
+ return {
+ v: 1,
+ name: "My theme",
+ modes: ["light", "dark"],
+ light: clone(rose.variants.light!),
+ dark: clone(rose.variants.dark!),
+ radiusPx: 7,
+ fontSizePx: 13,
+ };
+}
+
+const raw = () => JSON.parse(serializeTheme(sampleTheme())) as Record<string, any>;
+
+function expectError(input: unknown, fragment: string) {
+ const result = validateThemeData(input);
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error).toContain(fragment);
+}
+
+const plainCodec: Codec = { compress: null, decompress: null };
+
+describe("validateThemeData", () => {
+ test("accepts a full theme and normalises colours to lower case", () => {
+ const doc = raw();
+ doc.light.accent = "#C2185B";
+ const result = validateThemeData(doc);
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.theme.light!.accent).toBe("#c2185b");
+ expect(result.theme.modes).toEqual(["light", "dark"]);
+ }
+ });
+
+ test("accepts every preset variant as a single-mode theme", () => {
+ for (const preset of THEME_PRESETS) {
+ for (const mode of ["light", "dark"] as const) {
+ const variant = preset.variants[mode];
+ if (!variant) continue;
+ const result = validateThemeData({ v: 1, name: preset.name, modes: [mode], [mode]: variant });
+ expect(result.ok).toBe(true);
+ }
+ }
+ });
+
+ test("rejects non-objects", () => {
+ expectError(null, "JSON object");
+ expectError([], "JSON object");
+ expectError("theme", "JSON object");
+ expectError(42, "JSON object");
+ });
+
+ test("rejects unknown top-level keys", () => {
+ expectError({ ...raw(), fontFamily: "Comic Sans" }, 'unknown key "fontFamily"');
+ expectError({ ...raw(), css: "body{}" }, 'unknown key "css"');
+ });
+
+ test("rejects __proto__ and constructor keys", () => {
+ expectError(JSON.parse(`{"v":1,"name":"x","modes":["light"],"__proto__":{"polluted":true}}`), 'unknown key "__proto__"');
+ const doc = raw();
+ doc.light.constructor = "#000000";
+ expectError(doc, 'unknown key "constructor"');
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+
+ test("rejects unknown keys inside variants and groups", () => {
+ const a = raw();
+ a.dark.shadow = "#000000";
+ expectError(a, 'unknown key "shadow" in dark');
+ const b = raw();
+ b.light.code.decorator = "#000000";
+ expectError(b, 'unknown key "decorator" in light.code');
+ const c = raw();
+ c.light.terminal.selection = "#000000";
+ expectError(c, 'unknown key "selection" in light.terminal');
+ });
+
+ test("requires version 1", () => {
+ expectError({ ...raw(), v: 2 }, "version");
+ expectError({ ...raw(), v: "1" }, "version");
+ const { v: _v, ...rest } = raw();
+ expectError(rest, "version");
+ });
+
+ test("checks the name", () => {
+ expectError({ ...raw(), name: 5 }, "name");
+ expectError({ ...raw(), name: " " }, "empty");
+ expectError({ ...raw(), name: "x".repeat(41) }, "longer than 40");
+ expectError({ ...raw(), name: "bad\u0000name" }, "cannot be shown");
+ expectError({ ...raw(), name: "rtl‮override" }, "cannot be shown");
+ expectError({ ...raw(), name: "zero​width" }, "cannot be shown");
+ expectError({ ...raw(), name: "new\nline" }, "cannot be shown");
+ const ok = validateThemeData({ ...raw(), name: " Moss été <b>bold</b> " });
+ expect(ok.ok && ok.theme.name).toBe("Moss été <b>bold</b>");
+ expect(validateThemeData({ ...raw(), name: "x".repeat(40) }).ok).toBe(true);
+ });
+
+ test("checks modes against the versions present", () => {
+ expectError({ ...raw(), modes: [] }, "modes");
+ expectError({ ...raw(), modes: "light" }, "modes");
+ expectError({ ...raw(), modes: ["light", "light"] }, "twice");
+ expectError({ ...raw(), modes: ["light", "sepia"] }, '"light" and "dark"');
+ expectError({ ...raw(), modes: ["light", "dark", "light"] }, "modes");
+ const { dark: _dark, ...lightOnly } = raw();
+ expectError({ ...lightOnly, modes: ["light", "dark"] }, "no dark version");
+ expectError({ ...raw(), modes: ["light"] }, "does not list it");
+ const ok = validateThemeData({ ...lightOnly, modes: ["light"] });
+ expect(ok.ok && ok.theme.modes).toEqual(["light"]);
+ });
+
+ test("every colour must be exactly #rrggbb", () => {
+ for (const bad of ["#fff", "#ffff", "#fffffff", "#ffffff00", "red", "ffffff", "#gggggg", " #ffffff", "rgb(0,0,0)", 123, null]) {
+ const doc = raw();
+ doc.light.background = bad;
+ expectError(doc, '"light.background" must be a colour');
+ }
+ const doc = raw();
+ doc.dark.terminal.brightCyan = "#12345";
+ expectError(doc, '"dark.terminal.brightCyan" must be a colour');
+ });
+
+ test("CSS injection attempts are rejected", () => {
+ const attempts = [
+ "red;}body{display:none",
+ "#ffffff;}body{display:none}",
+ "#fff;background:url(x)",
+ "var(--x)",
+ "expression(alert(1))",
+ "#ffffff !important",
+ "#ffffff\n}",
+ ];
+ for (const value of attempts) {
+ const doc = raw();
+ doc.light.accent = value;
+ expectError(doc, "must be a colour");
+ const doc2 = raw();
+ doc2.dark.code.keyword = value;
+ expectError(doc2, "must be a colour");
+ }
+ expectError({ ...raw(), radiusPx: "4px;}body{display:none" }, "radiusPx");
+ });
+
+ test("requires every colour", () => {
+ const a = raw();
+ delete a.light.textMuted;
+ expectError(a, 'missing colour "light.textMuted"');
+ const b = raw();
+ delete b.dark.code.comment;
+ expectError(b, 'missing colour "dark.code.comment"');
+ const c = raw();
+ delete c.dark.terminal.cursor;
+ expectError(c, 'missing colour "dark.terminal.cursor"');
+ const d = raw();
+ d.light.code = "#ffffff";
+ expectError(d, '"light.code" must be an object');
+ });
+
+ test("highlight is optional but must be a colour", () => {
+ const a = raw();
+ delete a.light.highlight;
+ expect(validateThemeData(a).ok).toBe(true);
+ const b = raw();
+ b.light.highlight = "lime";
+ expectError(b, "light.highlight");
+ });
+
+ test("clamps radius and font size and defaults them", () => {
+ const big = validateThemeData({ ...raw(), radiusPx: 400, fontSizePx: 99 });
+ expect(big.ok && [big.theme.radiusPx, big.theme.fontSizePx]).toEqual([16, 16]);
+ const small = validateThemeData({ ...raw(), radiusPx: -3, fontSizePx: 2 });
+ expect(small.ok && [small.theme.radiusPx, small.theme.fontSizePx]).toEqual([0, 12]);
+ const { radiusPx: _r, fontSizePx: _f, ...rest } = raw();
+ const defaults = validateThemeData(rest);
+ expect(defaults.ok && [defaults.theme.radiusPx, defaults.theme.fontSizePx]).toEqual([7.2, 13]);
+ expectError({ ...raw(), radiusPx: Number.NaN }, "radiusPx");
+ expectError({ ...raw(), fontSizePx: "14" }, "fontSizePx");
+ expectError({ ...raw(), fontSizePx: null }, "fontSizePx");
+ });
+
+ test("never carries strings other than name and colours", () => {
+ const result = validateThemeData(raw());
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const strings: string[] = [];
+ const walk = (value: unknown, key: string) => {
+ if (typeof value === "string" && key !== "name" && key !== "modes") strings.push(value);
+ else if (Array.isArray(value)) value.forEach((item) => walk(item, "modes"));
+ else if (value && typeof value === "object") for (const [k, v] of Object.entries(value)) walk(v, k);
+ };
+ walk(result.theme, "");
+ expect(strings.every((value) => /^#[0-9a-f]{6}$/.test(value))).toBe(true);
+ });
+});
+
+describe("parseThemeJson", () => {
+ test("round-trips through the file format", () => {
+ const theme = sampleTheme();
+ const result = parseThemeJson(serializeTheme(theme, true));
+ expect(result.ok && result.theme).toEqual(theme);
+ });
+
+ test("rejects garbage and oversize text", () => {
+ expect(parseThemeJson("not json").ok).toBe(false);
+ expect(parseThemeJson("").ok).toBe(false);
+ const big = parseThemeJson(JSON.stringify({ ...raw(), pad: "x".repeat(MAX_THEME_BYTES) }));
+ expect(big.ok).toBe(false);
+ if (!big.ok) expect(big.error).toContain("8 KB");
+ });
+
+ test("a full two-mode theme fits well under the cap", () => {
+ expect(new TextEncoder().encode(serializeTheme(sampleTheme())).length).toBeLessThan(MAX_THEME_BYTES / 2);
+ });
+
+ test("file names are safe slugs", () => {
+ expect(themeFileName({ name: "My theme" })).toBe("my-theme.omnirush-theme.json");
+ expect(themeFileName({ name: "../../etc/passwd" })).toBe("etc-passwd.omnirush-theme.json");
+ expect(themeFileName({ name: "???" })).toBe("theme.omnirush-theme.json");
+ });
+});
+
+describe("share codes", () => {
+ test("round-trip with compression", async () => {
+ const theme = sampleTheme();
+ const code = await encodeShareCode(theme);
+ expect(code.startsWith("omnirush-theme:1:")).toBe(true);
+ expect(code.slice("omnirush-theme:1:".length)).toMatch(/^[A-Za-z0-9_-]+$/);
+ const result = await decodeShareCode(` ${code}\n`);
+ expect(result.ok && result.theme).toEqual(theme);
+ });
+
+ test("compressed codes are shorter than plain ones", async () => {
+ const theme = sampleTheme();
+ const compressed = await encodeShareCode(theme);
+ const plain = await encodeShareCode(theme, plainCodec);
+ expect(compressed.length).toBeLessThan(plain.length);
+ });
+
+ test("plain base64url JSON codes decode with or without compression support", async () => {
+ const theme = sampleTheme();
+ const code = await encodeShareCode(theme, plainCodec);
+ expect((await decodeShareCode(code)).ok).toBe(true);
+ const plainOnly = await decodeShareCode(code, plainCodec);
+ expect(plainOnly.ok && plainOnly.theme).toEqual(theme);
+ });
+
+ test("decodes codes made by another deflate-raw implementation", async () => {
+ const payload = deflateRawSync(Buffer.from(serializeTheme(sampleTheme())));
+ const code = `omnirush-theme:1:${bytesToBase64Url(new Uint8Array(payload))}`;
+ const result = await decodeShareCode(code);
+ expect(result.ok).toBe(true);
+ });
+
+ test("rejects a wrong prefix or version", async () => {
+ for (const [code, fragment] of [
+ ["", "starts with"],
+ ["theme:1:abc", "starts with"],
+ ["omnirush-theme:", "starts with"],
+ ["omnirush-theme:2:abcd", "version"],
+ ["omnirush-theme:x:abcd", "version"],
+ ] as const) {
+ const result = await decodeShareCode(code);
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error).toContain(fragment);
+ }
+ });
+
+ test("rejects garbage base64", async () => {
+ for (const payload of ["", "!!!!", "abc$def", "a", "ab+cd/==", "%%%"]) {
+ const result = await decodeShareCode(`omnirush-theme:1:${payload}`);
+ expect(result.ok).toBe(false);
+ }
+ });
+
+ test("rejects payloads that decode to garbage", async () => {
+ const random = bytesToBase64Url(new Uint8Array([1, 2, 3, 250, 251, 252, 9, 9, 9]));
+ expect((await decodeShareCode(`omnirush-theme:1:${random}`)).ok).toBe(false);
+ const notJson = bytesToBase64Url(new Uint8Array(deflateRawSync(Buffer.from("hello world"))));
+ expect((await decodeShareCode(`omnirush-theme:1:${notJson}`)).ok).toBe(false);
+ const badUtf8 = bytesToBase64Url(new Uint8Array(deflateRawSync(Buffer.from([0xff, 0xfe, 0xfd]))));
+ expect((await decodeShareCode(`omnirush-theme:1:${badUtf8}`)).ok).toBe(false);
+ });
+
+ test("validates the decoded theme (unknown key, bad colour, injection)", async () => {
+ const cases: Array<[Record<string, any>, string]> = [];
+ cases.push([{ ...raw(), fontFamily: "x" }, 'unknown key "fontFamily"']);
+ const badColour = raw();
+ badColour.light.accent = "#12";
+ cases.push([badColour, "must be a colour"]);
+ const injection = raw();
+ injection.dark.background = "red;}body{display:none";
+ cases.push([injection, "must be a colour"]);
+ for (const [doc, fragment] of cases) {
+ const payload = deflateRawSync(Buffer.from(JSON.stringify(doc)));
+ const result = await decodeShareCode(`omnirush-theme:1:${bytesToBase64Url(new Uint8Array(payload))}`);
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error).toContain(fragment);
+ }
+ });
+
+ test("rejects oversize codes before decoding", async () => {
+ const huge = `omnirush-theme:1:${"A".repeat(20_000)}`;
+ const result = await decodeShareCode(huge);
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error).toContain("8 KB");
+ const plain = bytesToBase64Url(new TextEncoder().encode(JSON.stringify({ ...raw(), pad: "x".repeat(7000) })));
+ const plainResult = await decodeShareCode(`omnirush-theme:1:${plain}`);
+ expect(plainResult.ok).toBe(false);
+ });
+
+ test("stops decompression bombs at 8 KB", async () => {
+ // 2 MB of spaces compresses to a few KB; the decoder must stop at the cap.
+ const bomb = deflateRawSync(Buffer.from(`{"v":1,"name":"x","modes":["light"]${" ".repeat(2_000_000)}}`), { level: 9 });
+ expect(bomb.length).toBeLessThan(MAX_THEME_BYTES);
+ const result = await decodeShareCode(`omnirush-theme:1:${bytesToBase64Url(new Uint8Array(bomb))}`);
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error).toContain("8 KB once decoded");
+ });
+
+ test("the decompressor reads no more than the cap", async () => {
+ let seen = 0;
+ const codec: Codec = {
+ compress: null,
+ decompress: async (bytes, limit) => {
+ const inflated = (await import("node:zlib")).inflateRawSync(Buffer.from(bytes));
+ seen = limit;
+ return inflated.length > limit ? null : new Uint8Array(inflated);
+ },
+ };
+ const bomb = deflateRawSync(Buffer.from(" ".repeat(100_000)));
+ const result = await decodeShareCode(`omnirush-theme:1:${bytesToBase64Url(new Uint8Array(bomb))}`, codec);
+ expect(result.ok).toBe(false);
+ expect(seen).toBe(MAX_THEME_BYTES);
+ });
+
+ test("base64url helpers round-trip all byte values", () => {
+ const bytes = new Uint8Array(256).map((_, index) => index);
+ expect(Array.from(base64UrlToBytes(bytesToBase64Url(bytes))!)).toEqual(Array.from(bytes));
+ expect(base64UrlToBytes("a+b/")).toBeNull();
+ });
+});