Generated by Spark: Reduce reliance on spark database. Just use sqlite.

This commit is contained in:
2026-01-17 18:14:23 +00:00
committed by GitHub
parent 0f01311120
commit 270d0be790
8 changed files with 1387 additions and 0 deletions

View File

@@ -0,0 +1,186 @@
import { useStorage } from '@/hooks/use-storage'
import { useIndexedDB, useIndexedDBCollection } from '@/hooks/use-indexed-db'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { useState } from 'react'
import { Database } from '@phosphor-icons/react'
interface Todo {
id: string
text: string
completed: boolean
createdAt: number
}
export function StorageExample() {
const [newTodoText, setNewTodoText] = useState('')
const [todos, setTodos] = useStorage<Todo[]>('example-todos', [])
const [counter, setCounter] = useStorage<number>('example-counter', 0)
const addTodo = () => {
if (!newTodoText.trim()) return
setTodos((current) => [
...current,
{
id: Date.now().toString(),
text: newTodoText,
completed: false,
createdAt: Date.now(),
},
])
setNewTodoText('')
}
const toggleTodo = (id: string) => {
setTodos((current) =>
current.map((todo) =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
)
)
}
const deleteTodo = (id: string) => {
setTodos((current) => current.filter((todo) => todo.id !== id))
}
const incrementCounter = () => {
setCounter((current) => current + 1)
}
return (
<div className="space-y-6 p-6">
<div>
<h1 className="text-3xl font-bold mb-2 flex items-center gap-2">
<Database size={32} />
Storage Example
</h1>
<p className="text-muted-foreground">
Demonstrates IndexedDB + Spark KV hybrid storage
</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle>Simple Counter (useStorage)</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-center gap-4">
<Badge variant="outline" className="text-4xl py-4 px-8">
{counter}
</Badge>
</div>
<Button onClick={incrementCounter} className="w-full" size="lg">
Increment
</Button>
<p className="text-xs text-muted-foreground text-center">
This counter persists across page refreshes using hybrid storage
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Todo List (useStorage)</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-2">
<Input
value={newTodoText}
onChange={(e) => setNewTodoText(e.target.value)}
placeholder="Enter todo..."
onKeyDown={(e) => e.key === 'Enter' && addTodo()}
/>
<Button onClick={addTodo}>Add</Button>
</div>
<div className="space-y-2 max-h-64 overflow-y-auto">
{todos.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">
No todos yet. Add one above!
</p>
) : (
todos.map((todo) => (
<div
key={todo.id}
className="flex items-center gap-2 p-2 rounded border"
>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(todo.id)}
className="w-4 h-4"
/>
<span
className={`flex-1 ${
todo.completed ? 'line-through text-muted-foreground' : ''
}`}
>
{todo.text}
</span>
<Button
variant="ghost"
size="sm"
onClick={() => deleteTodo(todo.id)}
>
Delete
</Button>
</div>
))
)}
</div>
<p className="text-xs text-muted-foreground">
Todos are stored in IndexedDB with Spark KV fallback
</p>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>How It Works</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<h3 className="font-semibold">1. Primary: IndexedDB</h3>
<p className="text-sm text-muted-foreground">
Data is first saved to IndexedDB for fast, structured storage with indexes
</p>
</div>
<div className="space-y-2">
<h3 className="font-semibold">2. Fallback: Spark KV</h3>
<p className="text-sm text-muted-foreground">
If IndexedDB fails or is unavailable, Spark KV is used automatically
</p>
</div>
<div className="space-y-2">
<h3 className="font-semibold">3. Sync Both</h3>
<p className="text-sm text-muted-foreground">
Data is kept in sync between both storage systems for redundancy
</p>
</div>
</div>
<div className="bg-muted p-4 rounded-lg">
<h4 className="font-semibold mb-2">Code Example:</h4>
<pre className="text-xs overflow-x-auto">
{`import { useStorage } from '@/hooks/use-storage'
// Replaces useKV from Spark
const [todos, setTodos] = useStorage('todos', [])
// Use functional updates for safety
setTodos((current) => [...current, newTodo])`}
</pre>
</div>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,252 @@
import { useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Database, HardDrive, CloudArrowUp, CloudArrowDown, Trash, Info } from '@phosphor-icons/react'
import { storage } from '@/lib/storage'
import { db } from '@/lib/db'
import { toast } from 'sonner'
export function StorageSettings() {
const [isMigrating, setIsMigrating] = useState(false)
const [isSyncing, setIsSyncing] = useState(false)
const [migrationProgress, setMigrationProgress] = useState(0)
const [stats, setStats] = useState<{
indexedDBCount: number
sparkKVCount: number
} | null>(null)
const loadStats = async () => {
try {
const [settingsCount, sparkKeys] = await Promise.all([
db.count('settings'),
window.spark?.kv.keys() || Promise.resolve([]),
])
setStats({
indexedDBCount: settingsCount,
sparkKVCount: sparkKeys.length,
})
} catch (error) {
console.error('Failed to load stats:', error)
toast.error('Failed to load storage statistics')
}
}
const handleMigrate = async () => {
setIsMigrating(true)
setMigrationProgress(0)
try {
const result = await storage.migrateFromSparkKV()
setMigrationProgress(100)
toast.success(
`Migration complete! ${result.migrated} items migrated${
result.failed > 0 ? `, ${result.failed} failed` : ''
}`
)
await loadStats()
} catch (error) {
console.error('Migration failed:', error)
toast.error('Migration failed. Check console for details.')
} finally {
setIsMigrating(false)
}
}
const handleSync = async () => {
setIsSyncing(true)
try {
const result = await storage.syncToSparkKV()
toast.success(
`Sync complete! ${result.synced} items synced${
result.failed > 0 ? `, ${result.failed} failed` : ''
}`
)
await loadStats()
} catch (error) {
console.error('Sync failed:', error)
toast.error('Sync failed. Check console for details.')
} finally {
setIsSyncing(false)
}
}
const handleClearIndexedDB = async () => {
if (!confirm('Are you sure you want to clear all IndexedDB data? This cannot be undone.')) {
return
}
try {
await db.clear('settings')
await db.clear('files')
await db.clear('models')
await db.clear('components')
await db.clear('workflows')
await db.clear('projects')
toast.success('IndexedDB cleared successfully')
await loadStats()
} catch (error) {
console.error('Failed to clear IndexedDB:', error)
toast.error('Failed to clear IndexedDB')
}
}
return (
<div className="space-y-6 p-6">
<div>
<h1 className="text-3xl font-bold mb-2">Storage Management</h1>
<p className="text-muted-foreground">
Manage your local database and sync with cloud storage
</p>
</div>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Info size={20} />
Storage Information
</CardTitle>
<CardDescription>
This application uses IndexedDB as the primary local database, with Spark KV as a
fallback/sync option
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<Button onClick={loadStats} variant="outline" size="sm">
Refresh Stats
</Button>
</div>
{stats && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium flex items-center gap-2">
<HardDrive size={16} />
IndexedDB (Primary)
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-baseline gap-2">
<span className="text-3xl font-bold">{stats.indexedDBCount}</span>
<span className="text-sm text-muted-foreground">items</span>
</div>
<Badge variant="default" className="mt-2">
Active
</Badge>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium flex items-center gap-2">
<Database size={16} />
Spark KV (Fallback)
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-baseline gap-2">
<span className="text-3xl font-bold">{stats.sparkKVCount}</span>
<span className="text-sm text-muted-foreground">items</span>
</div>
<Badge variant="secondary" className="mt-2">
Backup
</Badge>
</CardContent>
</Card>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<CloudArrowDown size={20} />
Data Migration
</CardTitle>
<CardDescription>
Migrate existing data from Spark KV to IndexedDB for improved performance
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{isMigrating && (
<div className="space-y-2">
<Progress value={migrationProgress} />
<p className="text-sm text-muted-foreground text-center">
Migrating data... {migrationProgress}%
</p>
</div>
)}
<Button
onClick={handleMigrate}
disabled={isMigrating}
className="w-full"
size="lg"
>
<CloudArrowDown size={20} className="mr-2" />
{isMigrating ? 'Migrating...' : 'Migrate from Spark KV to IndexedDB'}
</Button>
<p className="text-xs text-muted-foreground">
This will copy all data from Spark KV into IndexedDB. Your Spark KV data will remain
unchanged.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<CloudArrowUp size={20} />
Backup & Sync
</CardTitle>
<CardDescription>Sync IndexedDB data back to Spark KV as a backup</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Button
onClick={handleSync}
disabled={isSyncing}
variant="outline"
className="w-full"
size="lg"
>
<CloudArrowUp size={20} className="mr-2" />
{isSyncing ? 'Syncing...' : 'Sync to Spark KV'}
</Button>
<p className="text-xs text-muted-foreground">
This will update Spark KV with your current IndexedDB data. Useful for creating backups
or syncing across devices.
</p>
</CardContent>
</Card>
<Card className="border-destructive">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-destructive">
<Trash size={20} />
Danger Zone
</CardTitle>
<CardDescription>Irreversible actions that affect your data</CardDescription>
</CardHeader>
<CardContent>
<Button onClick={handleClearIndexedDB} variant="destructive" className="w-full">
<Trash size={20} className="mr-2" />
Clear All IndexedDB Data
</Button>
</CardContent>
</Card>
</div>
)
}

View File

@@ -1,3 +1,4 @@
export * from './atoms'
export * from './molecules'
export * from './organisms'
export { StorageSettings } from './StorageSettings'

101
src/hooks/use-indexed-db.ts Normal file
View File

@@ -0,0 +1,101 @@
import { useState, useEffect, useCallback } from 'react'
import { db, type DBSchema } from '@/lib/db'
type StoreName = keyof DBSchema
export function useIndexedDB<T extends StoreName, V = DBSchema[T]['value']>(
storeName: T,
key?: string,
defaultValue?: V
): [V | undefined, (value: V) => Promise<void>, () => Promise<void>, boolean] {
const [value, setValue] = useState<V | undefined>(defaultValue)
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!key) {
setLoading(false)
return
}
let mounted = true
db.get(storeName, key)
.then((result) => {
if (mounted) {
setValue((result as V) || defaultValue)
setLoading(false)
}
})
.catch((error) => {
console.error(`Error loading ${storeName}/${key}:`, error)
if (mounted) {
setValue(defaultValue)
setLoading(false)
}
})
return () => {
mounted = false
}
}, [storeName, key, defaultValue])
const updateValue = useCallback(
async (newValue: V) => {
if (!key) {
throw new Error('Cannot update value without a key')
}
setValue(newValue)
try {
await db.put(storeName, newValue as any)
} catch (error) {
console.error(`Error saving ${storeName}/${key}:`, error)
throw error
}
},
[storeName, key]
)
const deleteValue = useCallback(async () => {
if (!key) {
throw new Error('Cannot delete value without a key')
}
setValue(undefined)
try {
await db.delete(storeName, key)
} catch (error) {
console.error(`Error deleting ${storeName}/${key}:`, error)
throw error
}
}, [storeName, key])
return [value, updateValue, deleteValue, loading]
}
export function useIndexedDBCollection<T extends StoreName>(
storeName: T
): [DBSchema[T]['value'][], () => Promise<void>, boolean] {
const [items, setItems] = useState<DBSchema[T]['value'][]>([])
const [loading, setLoading] = useState(true)
const refresh = useCallback(async () => {
setLoading(true)
try {
const result = await db.getAll(storeName)
setItems(result)
} catch (error) {
console.error(`Error loading ${storeName} collection:`, error)
} finally {
setLoading(false)
}
}, [storeName])
useEffect(() => {
refresh()
}, [refresh])
return [items, refresh, loading]
}

67
src/hooks/use-storage.ts Normal file
View File

@@ -0,0 +1,67 @@
import { useState, useEffect, useCallback } from 'react'
import { storage } from '@/lib/storage'
export function useStorage<T>(
key: string,
defaultValue: T
): [T, (value: T | ((prev: T) => T)) => Promise<void>, () => Promise<void>] {
const [value, setValue] = useState<T>(defaultValue)
const [isInitialized, setIsInitialized] = useState(false)
useEffect(() => {
let mounted = true
storage
.get<T>(key)
.then((storedValue) => {
if (mounted) {
if (storedValue !== undefined) {
setValue(storedValue)
}
setIsInitialized(true)
}
})
.catch((error) => {
console.error(`Error loading ${key}:`, error)
if (mounted) {
setIsInitialized(true)
}
})
return () => {
mounted = false
}
}, [key])
const updateValue = useCallback(
async (newValueOrUpdater: T | ((prev: T) => T)) => {
const newValue =
typeof newValueOrUpdater === 'function'
? (newValueOrUpdater as (prev: T) => T)(value)
: newValueOrUpdater
setValue(newValue)
try {
await storage.set(key, newValue)
} catch (error) {
console.error(`Error saving ${key}:`, error)
throw error
}
},
[key, value]
)
const deleteValue = useCallback(async () => {
setValue(defaultValue)
try {
await storage.delete(key)
} catch (error) {
console.error(`Error deleting ${key}:`, error)
throw error
}
}, [key, defaultValue])
return [isInitialized ? value : defaultValue, updateValue, deleteValue]
}

241
src/lib/db.ts Normal file
View File

@@ -0,0 +1,241 @@
const DB_NAME = 'CodeForgeDB'
const DB_VERSION = 1
export interface DBSchema {
projects: {
key: string
value: {
id: string
name: string
files: any[]
models: any[]
components: any[]
componentTrees: any[]
workflows: any[]
lambdas: any[]
theme: any
playwrightTests: any[]
storybookStories: any[]
unitTests: any[]
flaskConfig: any
nextjsConfig: any
npmSettings: any
featureToggles: any
createdAt: number
updatedAt: number
}
}
files: {
key: string
value: {
id: string
name: string
content: string
language: string
path: string
updatedAt: number
}
}
models: {
key: string
value: {
id: string
name: string
fields: any[]
updatedAt: number
}
}
components: {
key: string
value: {
id: string
name: string
code: string
updatedAt: number
}
}
workflows: {
key: string
value: {
id: string
name: string
nodes: any[]
edges: any[]
updatedAt: number
}
}
settings: {
key: string
value: any
}
}
type StoreName = keyof DBSchema
class Database {
private db: IDBDatabase | null = null
private initPromise: Promise<void> | null = null
async init(): Promise<void> {
if (this.db) return
if (this.initPromise) return this.initPromise
this.initPromise = new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION)
request.onerror = () => reject(request.error)
request.onsuccess = () => {
this.db = request.result
resolve()
}
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result
if (!db.objectStoreNames.contains('projects')) {
const projectStore = db.createObjectStore('projects', { keyPath: 'id' })
projectStore.createIndex('name', 'name', { unique: false })
projectStore.createIndex('updatedAt', 'updatedAt', { unique: false })
}
if (!db.objectStoreNames.contains('files')) {
const fileStore = db.createObjectStore('files', { keyPath: 'id' })
fileStore.createIndex('name', 'name', { unique: false })
fileStore.createIndex('path', 'path', { unique: false })
}
if (!db.objectStoreNames.contains('models')) {
const modelStore = db.createObjectStore('models', { keyPath: 'id' })
modelStore.createIndex('name', 'name', { unique: false })
}
if (!db.objectStoreNames.contains('components')) {
const componentStore = db.createObjectStore('components', { keyPath: 'id' })
componentStore.createIndex('name', 'name', { unique: false })
}
if (!db.objectStoreNames.contains('workflows')) {
const workflowStore = db.createObjectStore('workflows', { keyPath: 'id' })
workflowStore.createIndex('name', 'name', { unique: false })
}
if (!db.objectStoreNames.contains('settings')) {
db.createObjectStore('settings', { keyPath: 'key' })
}
}
})
return this.initPromise
}
async get<T extends StoreName>(
storeName: T,
key: string
): Promise<DBSchema[T]['value'] | undefined> {
await this.init()
if (!this.db) throw new Error('Database not initialized')
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(storeName, 'readonly')
const store = transaction.objectStore(storeName)
const request = store.get(key)
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve(request.result)
})
}
async getAll<T extends StoreName>(storeName: T): Promise<DBSchema[T]['value'][]> {
await this.init()
if (!this.db) throw new Error('Database not initialized')
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(storeName, 'readonly')
const store = transaction.objectStore(storeName)
const request = store.getAll()
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve(request.result)
})
}
async put<T extends StoreName>(
storeName: T,
value: DBSchema[T]['value']
): Promise<void> {
await this.init()
if (!this.db) throw new Error('Database not initialized')
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(storeName, 'readwrite')
const store = transaction.objectStore(storeName)
const request = store.put(value)
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve()
})
}
async delete<T extends StoreName>(storeName: T, key: string): Promise<void> {
await this.init()
if (!this.db) throw new Error('Database not initialized')
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(storeName, 'readwrite')
const store = transaction.objectStore(storeName)
const request = store.delete(key)
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve()
})
}
async clear<T extends StoreName>(storeName: T): Promise<void> {
await this.init()
if (!this.db) throw new Error('Database not initialized')
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(storeName, 'readwrite')
const store = transaction.objectStore(storeName)
const request = store.clear()
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve()
})
}
async query<T extends StoreName>(
storeName: T,
indexName: string,
query: IDBValidKey | IDBKeyRange
): Promise<DBSchema[T]['value'][]> {
await this.init()
if (!this.db) throw new Error('Database not initialized')
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(storeName, 'readonly')
const store = transaction.objectStore(storeName)
const index = store.index(indexName)
const request = index.getAll(query)
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve(request.result)
})
}
async count<T extends StoreName>(storeName: T): Promise<number> {
await this.init()
if (!this.db) throw new Error('Database not initialized')
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(storeName, 'readonly')
const store = transaction.objectStore(storeName)
const request = store.count()
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve(request.result)
})
}
}
export const db = new Database()

210
src/lib/storage.ts Normal file
View File

@@ -0,0 +1,210 @@
import { db } from './db'
export interface StorageOptions {
useIndexedDB?: boolean
useSparkKV?: boolean
preferIndexedDB?: boolean
}
const defaultOptions: StorageOptions = {
useIndexedDB: true,
useSparkKV: true,
preferIndexedDB: true,
}
class HybridStorage {
private options: StorageOptions
constructor(options: Partial<StorageOptions> = {}) {
this.options = { ...defaultOptions, ...options }
}
async get<T>(key: string): Promise<T | undefined> {
if (this.options.preferIndexedDB && this.options.useIndexedDB) {
try {
const value = await db.get('settings', key)
if (value !== undefined) {
return value.value as T
}
} catch (error) {
console.warn('IndexedDB get failed, trying Spark KV:', error)
}
}
if (this.options.useSparkKV && typeof window !== 'undefined' && window.spark) {
try {
return await window.spark.kv.get<T>(key)
} catch (error) {
console.warn('Spark KV get failed:', error)
}
}
if (!this.options.preferIndexedDB && this.options.useIndexedDB) {
try {
const value = await db.get('settings', key)
if (value !== undefined) {
return value.value as T
}
} catch (error) {
console.warn('IndexedDB get failed:', error)
}
}
return undefined
}
async set<T>(key: string, value: T): Promise<void> {
const errors: Error[] = []
if (this.options.useIndexedDB) {
try {
await db.put('settings', { key, value })
} catch (error) {
console.warn('IndexedDB set failed:', error)
errors.push(error as Error)
}
}
if (this.options.useSparkKV && typeof window !== 'undefined' && window.spark) {
try {
await window.spark.kv.set(key, value)
} catch (error) {
console.warn('Spark KV set failed:', error)
errors.push(error as Error)
}
}
if (errors.length === 2) {
throw new Error('Both storage methods failed')
}
}
async delete(key: string): Promise<void> {
const errors: Error[] = []
if (this.options.useIndexedDB) {
try {
await db.delete('settings', key)
} catch (error) {
console.warn('IndexedDB delete failed:', error)
errors.push(error as Error)
}
}
if (this.options.useSparkKV && typeof window !== 'undefined' && window.spark) {
try {
await window.spark.kv.delete(key)
} catch (error) {
console.warn('Spark KV delete failed:', error)
errors.push(error as Error)
}
}
if (errors.length === 2) {
throw new Error('Both storage methods failed')
}
}
async keys(): Promise<string[]> {
const allKeys = new Set<string>()
if (this.options.useIndexedDB) {
try {
const settings = await db.getAll('settings')
settings.forEach((setting) => allKeys.add(setting.key))
} catch (error) {
console.warn('IndexedDB keys failed:', error)
}
}
if (this.options.useSparkKV && typeof window !== 'undefined' && window.spark) {
try {
const sparkKeys = await window.spark.kv.keys()
sparkKeys.forEach((key) => allKeys.add(key))
} catch (error) {
console.warn('Spark KV keys failed:', error)
}
}
return Array.from(allKeys)
}
async migrateFromSparkKV(): Promise<{ migrated: number; failed: number }> {
if (!this.options.useIndexedDB) {
throw new Error('IndexedDB is not enabled')
}
if (!window.spark) {
throw new Error('Spark KV is not available')
}
let migrated = 0
let failed = 0
try {
const keys = await window.spark.kv.keys()
for (const key of keys) {
try {
const value = await window.spark.kv.get(key)
if (value !== undefined) {
await db.put('settings', { key, value })
migrated++
}
} catch (error) {
console.error(`Failed to migrate key ${key}:`, error)
failed++
}
}
} catch (error) {
console.error('Migration failed:', error)
throw error
}
return { migrated, failed }
}
async syncToSparkKV(): Promise<{ synced: number; failed: number }> {
if (!this.options.useSparkKV) {
throw new Error('Spark KV is not enabled')
}
if (!window.spark) {
throw new Error('Spark KV is not available')
}
let synced = 0
let failed = 0
try {
const settings = await db.getAll('settings')
for (const setting of settings) {
try {
await window.spark.kv.set(setting.key, setting.value)
synced++
} catch (error) {
console.error(`Failed to sync key ${setting.key}:`, error)
failed++
}
}
} catch (error) {
console.error('Sync failed:', error)
throw error
}
return { synced, failed }
}
}
export const storage = new HybridStorage()
export const indexedDBOnlyStorage = new HybridStorage({
useIndexedDB: true,
useSparkKV: false,
})
export const sparkKVOnlyStorage = new HybridStorage({
useIndexedDB: false,
useSparkKV: true,
})