Skip to content

Commit 8951f54

Browse files
committed
Phase 1: Add plugin preference SDK foundation
- Add comprehensive preference schema types and validation - Implement preference registry system - Create hooks interface for plugin integration - Support for dynamic options from model providers - Zod-based validation and type safety This establishes the foundation for plugins to register preference tabs in Desktop settings, addressing feature request anomalyco#11494 Co-authored-by: Mike Wyant Jr <[email protected]>
1 parent feca42b commit 8951f54

3 files changed

Lines changed: 376 additions & 0 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export * from './types'
2+
export * from './registry'
Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
import type {
2+
PreferenceRegistration,
3+
PreferenceChange,
4+
PreferenceValidation,
5+
ValidationResult,
6+
PreferencesHook
7+
} from './types'
8+
9+
/**
10+
* In-memory registry for plugin preferences
11+
*/
12+
export class PreferenceRegistry {
13+
private static instance: PreferenceRegistry
14+
private preferences: Map<string, PreferenceRegistration> = new Map()
15+
private hooks: Map<string, PreferencesHook> = new Map()
16+
17+
private constructor() {}
18+
19+
/**
20+
* Get singleton instance
21+
*/
22+
static getInstance(): PreferenceRegistry {
23+
if (!PreferenceRegistry.instance) {
24+
PreferenceRegistry.instance = new PreferenceRegistry()
25+
}
26+
return PreferenceRegistry.instance
27+
}
28+
29+
/**
30+
* Register preferences from a plugin
31+
*/
32+
async register(pluginId: string, hook: PreferencesHook, registration: PreferenceRegistration): Promise<void> {
33+
// Validate registration
34+
const { PreferenceRegistrationSchema } = await import('./types')
35+
const { z } = await import('zod')
36+
37+
try {
38+
PreferenceRegistrationSchema.parse(registration)
39+
} catch (error) {
40+
if (error instanceof z.ZodError) {
41+
throw new Error(`Invalid preference registration for plugin ${pluginId}: ${error.message}`)
42+
}
43+
throw error
44+
}
45+
46+
// Store preference registration
47+
this.preferences.set(pluginId, registration)
48+
this.hooks.set(pluginId, hook)
49+
50+
console.log(`Registered preferences for plugin: ${pluginId}`)
51+
}
52+
53+
/**
54+
* Get all registered preference registrations
55+
*/
56+
getAllRegistrations(): Map<string, PreferenceRegistration> {
57+
return new Map(this.preferences)
58+
}
59+
60+
/**
61+
* Get specific plugin registration
62+
*/
63+
getRegistration(pluginId: string): PreferenceRegistration | undefined {
64+
return this.preferences.get(pluginId)
65+
}
66+
67+
/**
68+
* Handle preference value change
69+
*/
70+
async handleChange(pluginId: string, key: string, value: any, oldValue?: any): Promise<void> {
71+
const hook = this.hooks.get(pluginId)
72+
const registration = this.preferences.get(pluginId)
73+
74+
if (!hook || !registration) {
75+
throw new Error(`No preferences registered for plugin: ${pluginId}`)
76+
}
77+
78+
// Call validation if provided
79+
if (hook.validate) {
80+
const validationResult = await hook.validate({
81+
key,
82+
value,
83+
registration
84+
})
85+
86+
if (!validationResult.valid) {
87+
throw new Error(`Validation failed for ${key}: ${validationResult.error}`)
88+
}
89+
90+
if (validationResult.warning) {
91+
console.warn(`Preference warning for ${key}: ${validationResult.warning}`)
92+
}
93+
}
94+
95+
// Call change handler if provided
96+
if (hook.change) {
97+
await hook.change({
98+
key,
99+
value,
100+
oldValue,
101+
registration
102+
})
103+
}
104+
105+
console.log(`Preference changed for plugin ${pluginId}: ${key} = ${value}`)
106+
}
107+
108+
/**
109+
* Get current preference values for a plugin
110+
*/
111+
async getValues(pluginId: string): Promise<Record<string, any>> {
112+
const hook = this.hooks.get(pluginId)
113+
const registration = this.preferences.get(pluginId)
114+
115+
if (!registration) {
116+
return {}
117+
}
118+
119+
// If plugin provides custom value getter, use it
120+
if (hook?.getValues) {
121+
return await hook.getValues()
122+
}
123+
124+
// Otherwise, try to load from configuration (this will be implemented with Desktop integration)
125+
return registration.defaults
126+
}
127+
128+
/**
129+
* Validate a preference value without changing it
130+
*/
131+
async validateValue(pluginId: string, key: string, value: any): Promise<ValidationResult> {
132+
const hook = this.hooks.get(pluginId)
133+
const registration = this.preferences.get(pluginId)
134+
135+
if (!hook || !registration) {
136+
return { valid: false, error: `No preferences registered for plugin: ${pluginId}` }
137+
}
138+
139+
if (hook.validate) {
140+
return await hook.validate({
141+
key,
142+
value,
143+
registration
144+
})
145+
}
146+
147+
// Default validation against schema
148+
return this.validateAgainstSchema(registration.schema[key], value)
149+
}
150+
151+
/**
152+
* Basic schema validation
153+
*/
154+
private validateAgainstSchema(fieldDef: any, value: any): ValidationResult {
155+
if (!fieldDef) {
156+
return { valid: false, error: 'Unknown preference key' }
157+
}
158+
159+
const { type, validation = {} } = fieldDef
160+
161+
// Type validation
162+
switch (type) {
163+
case 'string':
164+
if (typeof value !== 'string') {
165+
return { valid: false, error: 'Value must be a string' }
166+
}
167+
break
168+
case 'number':
169+
if (typeof value !== 'number') {
170+
return { valid: false, error: 'Value must be a number' }
171+
}
172+
break
173+
case 'boolean':
174+
if (typeof value !== 'boolean') {
175+
return { valid: false, error: 'Value must be a boolean' }
176+
}
177+
break
178+
case 'select':
179+
case 'multiselect':
180+
// Array values will be validated at Desktop level
181+
break
182+
case 'file':
183+
case 'directory':
184+
if (typeof value !== 'string') {
185+
return { valid: false, error: 'Value must be a file path string' }
186+
}
187+
break
188+
}
189+
190+
// Apply validation rules
191+
if (validation.required && (value === undefined || value === null || value === '')) {
192+
return { valid: false, error: 'This field is required' }
193+
}
194+
195+
if (typeof value === 'string') {
196+
if (validation.pattern && !new RegExp(validation.pattern).test(value)) {
197+
return { valid: false, error: 'Value does not match required pattern' }
198+
}
199+
if (validation.minLength && value.length < validation.minLength) {
200+
return { valid: false, error: `Value must be at least ${validation.minLength} characters` }
201+
}
202+
if (validation.maxLength && value.length > validation.maxLength) {
203+
return { valid: false, error: `Value must be no more than ${validation.maxLength} characters` }
204+
}
205+
}
206+
207+
if (typeof value === 'number') {
208+
if (validation.min !== undefined && value < validation.min) {
209+
return { valid: false, error: `Value must be at least ${validation.min}` }
210+
}
211+
if (validation.max !== undefined && value > validation.max) {
212+
return { valid: false, error: `Value must be no more than ${validation.max}` }
213+
}
214+
}
215+
216+
return { valid: true }
217+
}
218+
}
219+
220+
/**
221+
* Global preference registry instance
222+
*/
223+
export const preferenceRegistry = PreferenceRegistry.getInstance()
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import { z } from "zod"
2+
3+
/**
4+
* Schema for defining preference fields
5+
*/
6+
export interface PreferenceSchema {
7+
[key: string]: {
8+
type: 'string' | 'number' | 'boolean' | 'select' | 'multiselect' | 'file' | 'directory'
9+
description?: string
10+
default?: any
11+
validation?: ValidationRule
12+
options?: Array<{label: string; value: any}> // For select types
13+
provider?: string // Dynamic options from providers
14+
help?: string // Help text for users
15+
}
16+
}
17+
18+
/**
19+
* Validation rules for preference values
20+
*/
21+
export interface ValidationRule {
22+
required?: boolean
23+
pattern?: string // Regex pattern for string validation
24+
min?: number // Minimum value for numbers
25+
max?: number // Maximum value for numbers
26+
minLength?: number // Minimum length for strings
27+
maxLength?: number // Maximum length for strings
28+
custom?: (value: any) => string | undefined // Custom validation function
29+
}
30+
31+
/**
32+
* Preference registration input
33+
*/
34+
export interface PreferenceRegistration {
35+
id: string // Unique identifier for this preference set
36+
title: string // Display name for the tab/window
37+
icon?: string // Icon for the preference entry
38+
requiresRestart?: boolean // Whether changes require restart
39+
schema: PreferenceSchema // Preference schema definition
40+
defaults: Record<string, any> // Default values
41+
ui?: UIPreferences // UI hints for rendering
42+
}
43+
44+
/**
45+
* UI hints for preference rendering
46+
*/
47+
export interface UIPreferences {
48+
group?: string // Group preferences together (e.g., "Models", "Integrations")
49+
order?: number // Display order within settings
50+
width?: 'normal' | 'wide' | 'full' // Preferred width
51+
}
52+
53+
/**
54+
* Preference change event
55+
*/
56+
export interface PreferenceChange {
57+
key: string
58+
value: any
59+
oldValue?: any
60+
registration: PreferenceRegistration
61+
}
62+
63+
/**
64+
* Preference validation input
65+
*/
66+
export interface PreferenceValidation {
67+
key: string
68+
value: any
69+
registration: PreferenceRegistration
70+
}
71+
72+
/**
73+
* Validation result
74+
*/
75+
export interface ValidationResult {
76+
valid: boolean
77+
error?: string
78+
warning?: string
79+
}
80+
81+
/**
82+
* Plugin preferences hook
83+
*/
84+
export interface PreferencesHook {
85+
// Register a preference tab
86+
register: (input: PreferenceRegistration) => Promise<PreferenceRegistration>
87+
88+
// Handle preference changes
89+
change?: (input: PreferenceChange) => Promise<void>
90+
91+
// Validate preference values
92+
validate?: (input: PreferenceValidation) => Promise<ValidationResult>
93+
94+
// Get current preference values (optional, defaults to schema defaults)
95+
getValues?: () => Promise<Record<string, any>>
96+
}
97+
98+
/**
99+
* Zod schemas for validation
100+
*/
101+
export const PreferenceRegistrationSchema = z.object({
102+
id: z.string(),
103+
title: z.string(),
104+
icon: z.string().optional(),
105+
requiresRestart: z.boolean().default(false),
106+
schema: z.record(z.object({
107+
type: z.enum(['string', 'number', 'boolean', 'select', 'multiselect', 'file', 'directory']),
108+
description: z.string().optional(),
109+
default: z.any().optional(),
110+
validation: z.object({
111+
required: z.boolean().optional(),
112+
pattern: z.string().optional(),
113+
min: z.number().optional(),
114+
max: z.number().optional(),
115+
minLength: z.number().optional(),
116+
maxLength: z.number().optional(),
117+
custom: z.function().optional(),
118+
}).optional(),
119+
options: z.array(z.object({
120+
label: z.string(),
121+
value: z.any(),
122+
})).optional(),
123+
provider: z.string().optional(),
124+
help: z.string().optional(),
125+
})),
126+
defaults: z.record(z.any()),
127+
ui: z.object({
128+
group: z.string().optional(),
129+
order: z.number().optional(),
130+
width: z.enum(['normal', 'wide', 'full']).optional(),
131+
}).optional(),
132+
})
133+
134+
export const PreferenceChangeSchema = z.object({
135+
key: z.string(),
136+
value: z.any(),
137+
oldValue: z.any().optional(),
138+
registration: PreferenceRegistrationSchema,
139+
})
140+
141+
export const PreferenceValidationSchema = z.object({
142+
key: z.string(),
143+
value: z.any(),
144+
registration: PreferenceRegistrationSchema,
145+
})
146+
147+
export const ValidationResultSchema = z.object({
148+
valid: z.boolean(),
149+
error: z.string().optional(),
150+
warning: z.string().optional(),
151+
})

0 commit comments

Comments
 (0)