core refactor for runtime support

This commit is contained in:
nicwands
2026-03-23 16:30:38 -04:00
parent eea1cccf16
commit 4d64bc995f
32 changed files with 634 additions and 486 deletions

55
src/core/ConfigManager.js Normal file
View File

@@ -0,0 +1,55 @@
const getDefaultConfig = () => {
return {
activeAdapter: 'supabase',
theme: 'dark',
}
}
export const createConfigManager = (storage) => {
let config = null
return {
async loadConfig() {
if (config) return config
const stored = await storage.load()
config = stored || getDefaultConfig()
if (!stored) {
await storage.save(config)
}
return config
},
getConfig() {
return config
},
async setConfig(newConfig) {
config = newConfig
await storage.save(newConfig)
},
async refreshConfig() {
config = await storage.load()
},
}
}
export const createConfigManagerClient = () => {
return {
async loadConfig() {
return await window.api.configManagerCall('loadConfig')
},
async getConfig() {
return await window.api.configManagerCall('getConfig')
},
async setConfig(newConfig) {
return await window.api.configManagerCall('setConfig', newConfig)
},
async refreshConfig() {
return await window.api.configManagerCall('refreshConfig')
},
}
}

View File

@@ -4,22 +4,22 @@ export default class IpcAdapter {
}
async init() {
return await window.adapter.call('init')
return await window.api.adapterCall('init')
}
async getAll() {
return await window.adapter.call('getAll')
return await window.api.adapterCall('getAll')
}
async create(note) {
return await window.adapter.call('create', note)
return await window.api.adapterCall('create', note)
}
async update(note) {
return await window.adapter.call('update', note)
return await window.api.adapterCall('update', note)
}
async delete(id) {
return await window.adapter.call('delete', id)
return await window.api.adapterCall('delete', id)
}
}

View File

@@ -1,16 +1,8 @@
import PluginRegistry from './PluginRegistry.js'
import IpcAdapter from './IpcAdapter.js'
import IpcAdapter from './IpcAdapter'
let registry = null
let activePluginId = null
let adapter = null
export default function createPluginManager(environment, plugins = []) {
registry = new PluginRegistry(environment)
for (const plugin of plugins) {
registry.register(plugin)
}
export const createPluginManager = (registry) => {
let activePluginId = null
let adapter = null
return {
listPlugins() {
@@ -24,10 +16,6 @@ export default function createPluginManager(environment, plugins = []) {
getAdapter(pluginId, adapterConfig = {}) {
const plugin = registry.get(pluginId)
if (environment === 'electron') {
return new IpcAdapter()
}
if (!plugin) {
throw new Error(`Plugin not found: ${pluginId}`)
}
@@ -41,6 +29,19 @@ export default function createPluginManager(environment, plugins = []) {
return adapter
},
async testPlugin(pluginId, adapterConfig = {}) {
const plugin = registry.get(pluginId)
if (!plugin) {
throw new Error(`Plugin not found: ${pluginId}`)
}
const adapter = this.getAdapter(pluginId, adapterConfig)
await adapter.init()
return await adapter.testConnection()
},
getActiveAdapter() {
return adapter
},
@@ -48,9 +49,30 @@ export default function createPluginManager(environment, plugins = []) {
getActivePluginId() {
return activePluginId
},
}
}
getEnvironment() {
return environment
// Client for calling manager through IPC
export const createPluginManagerClient = () => {
return {
listPlugins() {
return window.api.pluginManagerCall('listPlugins')
},
getAdapter(pluginId, config) {
return new IpcAdapter(pluginId, config)
},
setActivePlugin(pluginId, adapterConfig) {
return window.api.pluginManagerCall(
'setActivePlugin',
pluginId,
adapterConfig,
)
},
async testPlugin(id, config) {
return window.api.pluginManagerCall('testPlugin', { id, config })
},
}
}

View File

@@ -1,7 +1,6 @@
export default class PluginRegistry {
constructor(environment = 'web') {
constructor() {
this.plugins = new Map()
this.environment = environment
}
register(plugin) {
@@ -9,11 +8,6 @@ export default class PluginRegistry {
throw new Error('Plugin must have an id')
}
const environments = plugin.environments || ['electron', 'web']
if (!environments.includes(this.environment)) {
return
}
this.plugins.set(plugin.id, plugin)
}

View File

@@ -1,3 +1,4 @@
const USER_DATA_STRING = '__DEFAULT_USER_DATA__'
const DB_NAME = 'takerofnotes'
const DB_VERSION = 1
const STORE_NAME = 'config'
@@ -53,7 +54,7 @@ async function saveToDB(data) {
})
}
function createIndexedDBStorage() {
export function createWebStorage() {
return {
async load() {
const stored = await getFromDB()
@@ -65,84 +66,4 @@ function createIndexedDBStorage() {
}
}
function createIpcStorage() {
return {
async load() {
return await window.api.getConfig()
},
async save(data) {
await window.api.setConfig(data)
},
}
}
function getDefaultConfig() {
return {
activeAdapter: 'supabase',
theme: 'dark',
}
}
let config = null
let configResolve = null
const configPromise = new Promise((resolve) => {
configResolve = resolve
})
export function createConfigManager(environment, customStorage = null) {
let storage
if (customStorage) {
storage = customStorage
} else if (environment === 'electron') {
storage = createIpcStorage()
} else {
storage = createIndexedDBStorage()
}
const loadConfig = async () => {
if (config !== null) {
return config
}
const stored = await storage.load()
config = stored || getDefaultConfig()
if (!stored) {
await storage.save(config)
}
configResolve(config)
return config
}
const writeConfig = async (newConfig) => {
await storage.save(newConfig)
config = newConfig
}
const getConfig = () => {
if (config !== null) {
return config
}
return configPromise
}
const setConfig = async (newConfig) => {
config = newConfig
await writeConfig(newConfig)
}
const refreshConfig = async () => {
config = await storage.load()
configResolve(config)
}
return {
loadConfig,
getConfig,
setConfig,
refreshConfig,
}
}
export default createConfigManager
export default createWebStorage

View File

@@ -1,5 +1,14 @@
import createPluginManager from './PluginManager.js'
import createConfigManager from './Config.js'
import filesystemPlugin from '@takerofnotes/plugin-filesystem'
import {
createPluginManager,
createPluginManagerClient,
} from './PluginManager.js'
import { createWebStorage } from './WebStorage.js'
import PluginRegistry from './PluginRegistry.js'
import {
createConfigManager,
createConfigManagerClient,
} from './ConfigManager.js'
import NotesAPI from './NotesAPI.js'
const generateEncryptionKey = () => {
@@ -10,12 +19,46 @@ const generateEncryptionKey = () => {
.join('')
}
let coreInstance = null
const initPluginManager = (runtime, plugins, config) => {
if (runtime === 'electron-renderer') return createPluginManagerClient()
export function initializeCore(environment, plugins = []) {
const pluginManager = createPluginManager(environment, plugins)
const configManager = createConfigManager(environment)
const registry = new PluginRegistry()
for (const plugin of plugins) {
registry.register(plugin)
}
const manager = createPluginManager(registry)
manager.setActivePlugin(
config.activeAdapter,
config.adapters[config.activeAdapter],
)
return manager
}
const initConfigManager = async (runtime) => {
if (runtime === 'electron-renderer') return createConfigManagerClient()
let storage
if (runtime === 'electron-main') {
const { createNodeStorage } = await import('./NodeStorage.js')
storage = createNodeStorage(filesystemPlugin)
} else if (runtime === 'web') {
storage = createWebStorage()
}
return createConfigManager(storage)
}
export const initializeCore = async (runtime, { plugins }) => {
const configManager = await initConfigManager(runtime)
const config = await configManager.loadConfig()
const pluginManager = initPluginManager(runtime, plugins, config)
// -------------------------
// NotesAPI bootstrap
// -------------------------
let notesAPI = null
let initPromise = null
@@ -30,12 +73,15 @@ export function initializeCore(environment, plugins = []) {
if (!encryptionKey) {
encryptionKey = generateEncryptionKey()
await configManager.setConfig({ ...config, encryptionKey })
await configManager.setConfig({
...config,
encryptionKey,
})
}
const pluginId = config?.activeAdapter || 'filesystem'
const adapterConfig =
config.adapters?.[config.activeAdapter] || {}
const adapterConfig = config?.adapters?.[pluginId] || {}
const adapter = pluginManager.getAdapter(
pluginId,
adapterConfig,
@@ -51,27 +97,10 @@ export function initializeCore(environment, plugins = []) {
return initPromise
}
coreInstance = {
environment,
return {
runtime,
pluginManager,
configManager,
getNotesAPI,
}
return coreInstance
}
export function getCore() {
if (!coreInstance) {
throw new Error('Core not initialized. Call initializeCore() first.')
}
return coreInstance
}
export { default as PluginRegistry } from './PluginRegistry.js'
export { default as IpcAdapter } from './IpcAdapter.js'
export { default as NotesAPI } from './NotesAPI.js'
export {
default as createConfigManager,
createConfigManager as createConfig,
} from './Config.js'

View File

@@ -1,4 +0,0 @@
export enum ENVIRONMENTS {
ELECTRON = 'electron',
WEB = 'web',
}

View File

@@ -3,8 +3,7 @@ import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { app, shell, BrowserWindow, ipcMain } from 'electron'
import filesystemPlugin from '@takerofnotes/plugin-filesystem'
import supabasePlugin from '@takerofnotes/plugin-supabase'
import { PluginRegistry, createConfigManager } from '../core/index.js'
import { createNodeStorage } from './NodeStorage.js'
import { initializeCore } from '../core/index.js'
import { join } from 'path'
const DEFAULT_WINDOW_SIZE = { width: 354, height: 549 }
@@ -13,8 +12,6 @@ const DEFAULT_MOVE_WINDOW_SIZE = { width: 708, height: 549 }
const preloadPath = join(__dirname, '../preload/index.mjs')
const rendererPath = join(__dirname, '../renderer/index.html')
let activeAdapter = null
function createWindow() {
const mainWindow = new BrowserWindow({
width: DEFAULT_WINDOW_SIZE.width,
@@ -78,55 +75,32 @@ app.whenReady().then(async () => {
})
}
const registry = new PluginRegistry('electron')
registry.register(filesystemPlugin)
registry.register(supabasePlugin)
const { pluginManager, configManager } = await initializeCore(
'electron-main',
{
plugins: [filesystemPlugin, supabasePlugin],
},
)
const nodeStorage = createNodeStorage(filesystemPlugin)
const configManager = createConfigManager('electron', nodeStorage)
const initialConfig = await configManager.loadConfig()
ipcMain.handle('pluginManager:call', async (_, method, ...args) => {
const methodCall = await pluginManager[method](...args)
const setActivePlugin = async (pluginId) => {
const currentConfig = await configManager.loadConfig()
await configManager.setConfig({
...currentConfig,
activeAdapter: pluginId,
})
if (method === 'setActivePlugin') {
broadcastNoteChange('plugin-changed')
}
const plugin = registry.get(pluginId)
const adapterConfig = currentConfig.adapters[pluginId] || {}
activeAdapter = plugin.createAdapter(adapterConfig)
await activeAdapter.init()
ipcMain.removeHandler('adapter:call')
ipcMain.handle('adapter:call', async (_, method, args) => {
if (!activeAdapter[method]) {
throw new Error(`Invalid adapter method: ${method}`)
}
return await activeAdapter[method](...args)
})
broadcastNoteChange('plugin-changed', pluginId)
return true
}
await setActivePlugin(initialConfig.activeAdapter)
ipcMain.handle('getConfig', async () => {
return await configManager.loadConfig()
return methodCall
})
ipcMain.handle('setConfig', async (_, newConfig) => {
await configManager.setConfig(newConfig)
ipcMain.handle('configManager:call', async (_, method, ...args) => {
return await configManager[method](...args)
})
ipcMain.handle('adapter:call', async (_, method, ...args) => {
const adapter = pluginManager.getActiveAdapter()
if (!adapter[method]) {
throw new Error(`Invalid adapter method: ${method}`)
}
ipcMain.handle('listPlugins', async () => {
return registry.list()
})
ipcMain.handle('setActivePlugin', async (_, pluginId) => {
return await setActivePlugin(pluginId)
return await adapter[method](...args)
})
ipcMain.on('note-changed', (_, event, data) => {

View File

@@ -2,11 +2,24 @@ import { contextBridge, ipcRenderer } from 'electron'
// Custom APIs for renderer
const api = {
getConfig: () => ipcRenderer.invoke('getConfig'),
setConfig: (config) => ipcRenderer.invoke('setConfig', config),
listPlugins: () => ipcRenderer.invoke('listPlugins'),
setActivePlugin: (pluginId) =>
ipcRenderer.invoke('setActivePlugin', pluginId),
pluginManagerCall: (method, ...args) =>
ipcRenderer.invoke(
'pluginManager:call',
method,
...(args.length ? args : []),
),
configManagerCall: (method, ...args) =>
ipcRenderer.invoke(
'configManager:call',
method,
...(args.length ? args : []),
),
adapterCall: (method, ...args) =>
ipcRenderer.invoke(
'adapter:call',
method,
...(args.length ? args : []),
),
openNoteWindow: (noteId) => {
ipcRenderer.send('open-note-window', noteId)
},
@@ -33,19 +46,12 @@ const api = {
},
}
// Implement adapter API - communicates with plugin adapter in main process
const adapter = {
call: (method, ...args) => ipcRenderer.invoke('adapter:call', method, args),
}
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('api', api)
contextBridge.exposeInMainWorld('adapter', adapter)
} catch (error) {
console.error(error)
}
} else {
window.api = api
window.adapter = adapter
}

View File

@@ -2,12 +2,12 @@
<html>
<head>
<meta charset="UTF-8" />
<title>Electron</title>
<title>Taker of Notes</title>
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta
<!--<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:"
/>
/>-->
</head>
<body>

View File

@@ -43,7 +43,6 @@ const onMoveOpened = async () => {
move: props.note.id,
},
})
console.log(route.query)
}
const moveActive = computed(() => route.query.move === props.note.id)
</script>

View File

@@ -1,5 +1,5 @@
import { ref, watch, toRaw, onMounted } from 'vue'
import { getCore } from '@core/index.js'
import useCore from '@/composables/useCore'
const config = ref()
let configResolve = null
@@ -8,8 +8,7 @@ const configPromise = new Promise((resolve) => {
})
export default () => {
const core = getCore()
const { configManager } = core
const { configManager } = useCore()
onMounted(async () => {
if (config.value) {
@@ -17,8 +16,7 @@ export default () => {
return
}
const loadedConfig = await configManager.loadConfig()
config.value = loadedConfig
config.value = await configManager.loadConfig()
configResolve()
})

View File

@@ -0,0 +1,11 @@
import { inject } from 'vue'
let core
export default () => {
if (!core) {
core = inject('core')
}
return core
}

View File

@@ -41,7 +41,9 @@ const setupListeners = () => {
}
const broadcastChange = (event, data) => {
window.api.notifyNoteChanged(event, data)
if (environment === 'electron') {
window.api.notifyNoteChanged(event, data)
}
}
if (environment === 'electron') {

View File

@@ -1,20 +1,27 @@
import { ref } from 'vue'
import useCore from '@/composables/useCore'
import useConfig from './useConfig'
import { ref } from 'vue'
export default async () => {
const { refreshConfig } = useConfig()
const { config } = useConfig()
const { pluginManager } = useCore()
const plugins = ref([])
plugins.value = await window.api.listPlugins()
plugins.value = await pluginManager.listPlugins()
const setActivePlugin = async (pluginId) => {
await window.api.setActivePlugin(pluginId)
await refreshConfig()
const setActivePlugin = async (pluginId, activeConfig = {}) => {
await pluginManager.setActivePlugin(pluginId, { ...activeConfig })
config.value.activeAdapter = pluginId
}
const testPlugin = async (pluginId, config = {}) => {
await pluginManager.testPlugin(pluginId, { ...config })
}
return {
plugins,
setActivePlugin,
testPlugin,
}
}

View File

@@ -1,4 +1,4 @@
import { getCore } from '@core/index.js'
import useCore from '@/composables/useCore'
let notesAPI = null
let initPromise = null
@@ -8,8 +8,8 @@ export const getNotesAPI = async () => {
if (!initPromise) {
initPromise = (async () => {
const core = getCore()
notesAPI = await core.getNotesAPI()
const { getNotesAPI } = useCore()
notesAPI = await getNotesAPI()
return notesAPI
})()
}

View File

@@ -6,7 +6,7 @@ import { router } from './plugins/router'
const app = createApp(App)
app.use(initCore)
await initCore(app)
app.use(router)
app.mount('#app')

View File

@@ -2,11 +2,18 @@ import { useEnvironment } from '@/composables/useEnvironment'
import { initializeCore } from '@core/index.js'
import supabasePlugin from '@takerofnotes/plugin-supabase'
export const initCore = () => {
export const initCore = async (app) => {
const environment = useEnvironment()
// Set runtime
const runtime = environment === 'electron' ? 'electron-renderer' : 'web'
// Plugins that are valid for web (electron uses IPC)
const plugins = [supabasePlugin]
initializeCore(environment, plugins)
const core = await initializeCore(runtime, {
plugins,
})
app.provide('core', core)
}

View File

@@ -19,8 +19,6 @@
<script setup>
import useNotes from '@/composables/useNotes'
import usePlugins from '@/composables/usePlugins'
import useConfig from '@/composables/useConfig'
import { onMounted, ref, watch } from 'vue'
import CategoryRow from '@/components/CategoryRow.vue'
import NoteRow from '@/components/NoteRow.vue'
@@ -29,8 +27,6 @@ import PageLoading from '@/components/PageLoading.vue'
const { categories, loadCategories, loadCategoryNotes, notesChangeCount } =
useNotes()
const { config } = useConfig()
const notes = ref()
const loaded = ref(false)

View File

@@ -51,7 +51,7 @@ import usePlugins from '@/composables/usePlugins'
import useConfig from '@/composables/useConfig'
import { ref, computed } from 'vue'
const { plugins, setActivePlugin } = await usePlugins()
const { plugins, setActivePlugin, testPlugin } = await usePlugins()
const { config, ensureConfig } = useConfig()
await ensureConfig()
@@ -89,17 +89,26 @@ const save = async () => {
validationError.value = ''
const plugin = selectedPlugin.value
const adapterConfig = config.value.adapters[plugin.id] || {}
if (plugin && plugin.configSchema.length) {
const adapterConfig = config.value.adapters[plugin.id] || {}
// Check required fields
for (const field of plugin.configSchema) {
if (field.required && !adapterConfig[field.key]) {
validationError.value = `Please fill in all required fields for ${plugin.name}`
return
}
}
// Test connection
// const testResult = await testPlugin(plugin.id, adapterConfig)
// console.log(testResult)
// if (!testResult) {
// validationError.value = `Failed to connect to ${plugin.name}`
// }
}
await setActivePlugin(selectedPluginId.value)
await setActivePlugin(selectedPluginId.value, adapterConfig)
saving.value = false
saved.value = true
setTimeout(() => {