From fc4e82c26da29b3bbd2e6c07f342870ade1962cb Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 26 Sep 2025 11:59:36 -0500 Subject: [PATCH] Remove legacy migrations from configUtils, parse with zod --- src/lib/configUtils.test.ts | 42 +-------- src/lib/configUtils.ts | 169 +++++++++--------------------------- src/lib/schema.test.ts | 149 +++++++++++++++++++++++++++++++ src/lib/schema.ts | 12 +++ 4 files changed, 201 insertions(+), 171 deletions(-) create mode 100644 src/lib/schema.test.ts create mode 100644 src/lib/schema.ts diff --git a/src/lib/configUtils.test.ts b/src/lib/configUtils.test.ts index 2936d823..6cfdf9f8 100644 --- a/src/lib/configUtils.test.ts +++ b/src/lib/configUtils.test.ts @@ -61,7 +61,7 @@ describe('configUtils', () => { apiKey: 'sk-test123', }, ], - recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'], + recentlyUsedModels: ['openai/gpt-4', 'openai/gpt-3.5-turbo'], }; describe('readAISettings', () => { @@ -97,26 +97,6 @@ describe('configUtils', () => { recentlyUsedModels: [], }); }); - - it('should migrate from localStorage if VFS file does not exist', async () => { - vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); - vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found')); - vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); - vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); - - mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleAISettings)); - - const result = await readAISettings(mockFS); - - expect(result).toEqual(sampleAISettings); - expect(mockLocalStorage.getItem).toHaveBeenCalledWith('ai-settings'); - expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('ai-settings'); - expect(mockFS.writeFile).toHaveBeenCalledWith( - '/config/ai.json', - JSON.stringify(sampleAISettings, null, 2), - 'utf8' - ); - }); }); describe('writeAISettings', () => { @@ -188,26 +168,6 @@ describe('configUtils', () => { corsProxy: 'https://proxy.shakespeare.diy/?url={href}', }); }); - - it('should migrate from localStorage if VFS file does not exist', async () => { - vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); - vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found')); - vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); - vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); - - mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleGitSettings)); - - const result = await readGitSettings(mockFS); - - expect(result).toEqual(sampleGitSettings); - expect(mockLocalStorage.getItem).toHaveBeenCalledWith('git-settings'); - expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('git-settings'); - expect(mockFS.writeFile).toHaveBeenCalledWith( - '/config/git.json', - JSON.stringify(sampleGitSettings, null, 2), - 'utf8' - ); - }); }); describe('writeGitSettings', () => { diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 394ae951..032b3c7b 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -1,11 +1,40 @@ +import z from 'zod'; +import { filteredArray } from '@/lib/schema'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; -import type { AISettings, AIProvider } from '@/contexts/AISettingsContext'; +import type { AIProvider, AISettings } from '@/contexts/AISettingsContext'; import type { GitSettings } from '@/contexts/GitSettingsContext'; const CONFIG_DIR = '/config'; const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`; const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.json`; +const aiProviderSchema: z.ZodType = z.object({ + id: z.string(), + baseURL: z.string().url(), + apiKey: z.string().optional(), + nostr: z.boolean().optional(), +}); + +const providerModelSchema = z.string().regex( + /^[^/]+\/.+$/, + 'Must be in format provider/model (e.g., "openai/gpt-4o")', +); + +const aiSettingsSchema = z.object({ + providers: filteredArray(aiProviderSchema), + recentlyUsedModels: filteredArray(providerModelSchema), +}); + +const gitCredentialSchema = z.object({ + username: z.string(), + password: z.string(), +}); + +const gitSettingsSchema = z.object({ + credentials: z.record(z.string(), gitCredentialSchema), + corsProxy: z.string().url().catch('https://proxy.shakespeare.diy/?url={href}') +}); + /** * Ensures the config directory exists */ @@ -17,49 +46,6 @@ async function ensureConfigDir(fs: JSRuntimeFS): Promise { } } -/** - * Migrate AI settings from localStorage to VFS (internal function) - */ -async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise { - // If not in VFS, try to migrate from localStorage - const stored = localStorage.getItem('ai-settings'); - if (stored) { - try { - const parsed = JSON.parse(stored); - if (parsed && typeof parsed === 'object' && 'providers' in parsed) { - // Handle migration from old map format to new array format - let providers; - if (Array.isArray(parsed.providers)) { - providers = parsed.providers; - } else if (parsed.providers && typeof parsed.providers === 'object') { - // Convert map to array - providers = Object.entries(parsed.providers).map(([id, connection]) => ({ - id, - ...(connection as Omit), - })); - } else { - providers = []; - } - - const settings: AISettings = { - providers, - recentlyUsedModels: parsed.recentlyUsedModels || [], - }; - - // Write to VFS and remove from localStorage - await writeAISettings(fs, settings); - localStorage.removeItem('ai-settings'); - - return settings; - } - } catch { - // If parsing fails, return null - } - } - - return null; -} - /** * Read AI settings from VFS (with automatic migration from localStorage) */ @@ -69,50 +55,16 @@ export async function readAISettings(fs: JSRuntimeFS): Promise { recentlyUsedModels: [], }; - // Try to read from VFS first try { const content = await fs.readFile(AI_CONFIG_PATH, 'utf8'); - const parsed = JSON.parse(content); - - if (parsed && typeof parsed === 'object' && 'providers' in parsed) { - // Handle migration from old map format to new array format - let providers; - if (Array.isArray(parsed.providers)) { - providers = parsed.providers; - } else if (parsed.providers && typeof parsed.providers === 'object') { - // Convert map to array - providers = Object.entries(parsed.providers).map(([id, connection]) => ({ - id, - ...(connection as Omit), - })); - - // Write back the migrated format - const migratedSettings: AISettings = { - providers, - recentlyUsedModels: parsed.recentlyUsedModels || [], - }; - await writeAISettings(fs, migratedSettings); - return migratedSettings; - } else { - providers = []; - } - - return { - providers, - recentlyUsedModels: parsed.recentlyUsedModels || [], - }; + const data = JSON.parse(content); + return aiSettingsSchema.parse(data); + } catch (error) { + if (error instanceof z.ZodError) { + console.error('AI settings parsing error:', error.errors); } - } catch { - // File doesn't exist or is invalid, try migration + return defaultSettings; } - - // If not in VFS, try to migrate from localStorage - const migratedSettings = await migrateAISettingsFromLocalStorage(fs); - if (migratedSettings) { - return migratedSettings; - } - - return defaultSettings; } /** @@ -123,35 +75,6 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Pr await fs.writeFile(AI_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8'); } -/** - * Migrate Git settings from localStorage to VFS (internal function) - */ -async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise { - // If not in VFS, try to migrate from localStorage - const stored = localStorage.getItem('git-settings'); - if (stored) { - try { - const parsed = JSON.parse(stored); - if (parsed && typeof parsed === 'object' && 'credentials' in parsed) { - const settings: GitSettings = { - credentials: parsed.credentials || {}, - corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}', - }; - - // Write to VFS and remove from localStorage - await writeGitSettings(fs, settings); - localStorage.removeItem('git-settings'); - - return settings; - } - } catch { - // If parsing fails, return null - } - } - - return null; -} - /** * Read Git settings from VFS (with automatic migration from localStorage) */ @@ -164,25 +87,11 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise { // Try to read from VFS first try { const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8'); - const parsed = JSON.parse(content); - - if (parsed && typeof parsed === 'object' && 'credentials' in parsed) { - return { - credentials: parsed.credentials || {}, - corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}', - }; - } + const data = JSON.parse(content); + return gitSettingsSchema.parse(data); } catch { - // File doesn't exist or is invalid, try migration + return defaultSettings; } - - // If not in VFS, try to migrate from localStorage - const migratedSettings = await migrateGitSettingsFromLocalStorage(fs); - if (migratedSettings) { - return migratedSettings; - } - - return defaultSettings; } /** diff --git a/src/lib/schema.test.ts b/src/lib/schema.test.ts new file mode 100644 index 00000000..567e7a82 --- /dev/null +++ b/src/lib/schema.test.ts @@ -0,0 +1,149 @@ +import { describe, it, expect } from 'vitest'; +import z from 'zod'; +import { filteredArray } from './schema'; + +describe('filteredArray', () => { + it('filters out invalid items and keeps valid ones', () => { + const numberSchema = z.number(); + const schema = filteredArray(numberSchema); + + const input = [1, 'invalid', 2, null, 3, undefined, 4]; + const result = schema.parse(input); + + expect(result).toEqual([1, 2, 3, 4]); + }); + + it('returns empty array when all items are invalid', () => { + const numberSchema = z.number(); + const schema = filteredArray(numberSchema); + + const input = ['string', null, undefined, {}, []]; + const result = schema.parse(input); + + expect(result).toEqual([]); + }); + + it('returns all items when all are valid', () => { + const stringSchema = z.string(); + const schema = filteredArray(stringSchema); + + const input = ['hello', 'world', 'test']; + const result = schema.parse(input); + + expect(result).toEqual(['hello', 'world', 'test']); + }); + + it('works with complex object schemas', () => { + const userSchema = z.object({ + id: z.number(), + name: z.string(), + email: z.string().email(), + }); + const schema = filteredArray(userSchema); + + const input = [ + { id: 1, name: 'John', email: 'john@example.com' }, + { id: 'invalid', name: 'Jane', email: 'jane@example.com' }, // invalid id + { id: 2, name: 'Bob', email: 'invalid-email' }, // invalid email + { id: 3, name: 'Alice', email: 'alice@example.com' }, + 'not an object', + null, + ]; + + const result = schema.parse(input); + + expect(result).toEqual([ + { id: 1, name: 'John', email: 'john@example.com' }, + { id: 3, name: 'Alice', email: 'alice@example.com' }, + ]); + }); + + it('handles empty array input', () => { + const numberSchema = z.number(); + const schema = filteredArray(numberSchema); + + const result = schema.parse([]); + + expect(result).toEqual([]); + }); + + it('catches non-array input and returns empty array', () => { + const numberSchema = z.number(); + const schema = filteredArray(numberSchema); + + const result1 = schema.parse('not an array'); + const result2 = schema.parse(null); + const result3 = schema.parse(undefined); + const result4 = schema.parse(123); + + expect(result1).toEqual([]); + expect(result2).toEqual([]); + expect(result3).toEqual([]); + expect(result4).toEqual([]); + }); + + it('works with union schemas', () => { + const unionSchema = z.union([z.string(), z.number()]); + const schema = filteredArray(unionSchema); + + const input = ['hello', 42, true, 'world', null, 99, {}]; + const result = schema.parse(input); + + expect(result).toEqual(['hello', 42, 'world', 99]); + }); + + it('preserves transformed values from schema', () => { + const transformSchema = z.string().transform((str) => str.toUpperCase()); + const schema = filteredArray(transformSchema); + + const input = ['hello', 123, 'world', null, 'test']; + const result = schema.parse(input); + + expect(result).toEqual(['HELLO', 'WORLD', 'TEST']); + }); + + it('works with optional fields in object schemas', () => { + const optionalSchema = z.object({ + required: z.string(), + optional: z.string().optional(), + }); + const schema = filteredArray(optionalSchema); + + const input = [ + { required: 'test1' }, + { required: 'test2', optional: 'value' }, + { optional: 'value' }, // missing required field + { required: 'test3', optional: undefined }, + ]; + + const result = schema.parse(input); + + expect(result).toEqual([ + { required: 'test1' }, + { required: 'test2', optional: 'value' }, + { required: 'test3', optional: undefined }, + ]); + }); + + it('handles nested arrays', () => { + const nestedSchema = z.object({ + name: z.string(), + tags: z.string().array(), + }); + const schema = filteredArray(nestedSchema); + + const input = [ + { name: 'item1', tags: ['tag1', 'tag2'] }, + { name: 'item2', tags: 'not an array' }, // invalid tags + { name: 'item3', tags: [] }, + 'invalid item', + ]; + + const result = schema.parse(input); + + expect(result).toEqual([ + { name: 'item1', tags: ['tag1', 'tag2'] }, + { name: 'item3', tags: [] }, + ]); + }); +}); \ No newline at end of file diff --git a/src/lib/schema.ts b/src/lib/schema.ts new file mode 100644 index 00000000..58fec346 --- /dev/null +++ b/src/lib/schema.ts @@ -0,0 +1,12 @@ +import z from "zod"; + +/** Validates individual items in an array, dropping any that aren't valid. */ +export function filteredArray(schema: T) { + return z.any().array().catch([]) + .transform((arr) => ( + arr.map((item) => { + const parsed = schema.safeParse(item); + return parsed.success ? parsed.data : undefined; + }).filter((item): item is z.infer => Boolean(item)) + )); +} \ No newline at end of file