total restructure: isolate functionality to core so web works

This commit is contained in:
nicwands
2026-03-19 17:25:43 -04:00
parent f9e7fe1208
commit eea1cccf16
20 changed files with 635 additions and 247 deletions

148
src/core/Config.js Normal file
View File

@@ -0,0 +1,148 @@
const DB_NAME = 'takerofnotes'
const DB_VERSION = 1
const STORE_NAME = 'config'
const CONFIG_KEY = 'app_config'
let db = null
function openDB() {
return new Promise((resolve, reject) => {
if (db) {
resolve(db)
return
}
const request = indexedDB.open(DB_NAME, DB_VERSION)
request.onerror = () => reject(request.error)
request.onsuccess = () => {
db = request.result
resolve(db)
}
request.onupgradeneeded = (event) => {
const database = event.target.result
if (!database.objectStoreNames.contains(STORE_NAME)) {
database.createObjectStore(STORE_NAME, { keyPath: 'id' })
}
}
})
}
async function getFromDB() {
const database = await openDB()
return new Promise((resolve, reject) => {
const transaction = database.transaction(STORE_NAME, 'readonly')
const store = transaction.objectStore(STORE_NAME)
const request = store.get(CONFIG_KEY)
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve(request.result?.data || null)
})
}
async function saveToDB(data) {
const database = await openDB()
return new Promise((resolve, reject) => {
const transaction = database.transaction(STORE_NAME, 'readwrite')
const store = transaction.objectStore(STORE_NAME)
const request = store.put({ id: CONFIG_KEY, data })
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve()
})
}
function createIndexedDBStorage() {
return {
async load() {
const stored = await getFromDB()
return stored || null
},
async save(data) {
await saveToDB(data)
},
}
}
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

25
src/core/IpcAdapter.js Normal file
View File

@@ -0,0 +1,25 @@
export default class IpcAdapter {
constructor() {
this._methods = ['init', 'getAll', 'create', 'update', 'delete']
}
async init() {
return await window.adapter.call('init')
}
async getAll() {
return await window.adapter.call('getAll')
}
async create(note) {
return await window.adapter.call('create', note)
}
async update(note) {
return await window.adapter.call('update', note)
}
async delete(id) {
return await window.adapter.call('delete', id)
}
}

275
src/core/NotesAPI.js Normal file
View File

@@ -0,0 +1,275 @@
import sodium from 'libsodium-wrappers'
import { v4 as uuidv4 } from 'uuid'
import { Index } from 'flexsearch'
export default class NotesAPI {
constructor(adapter, encryptionKey = null) {
if (!adapter) {
throw new Error('NotesAPI requires a storage adapter')
}
this.adapter = adapter
this.notesCache = new Map()
this.encryptionKey = encryptionKey
this._sodiumReady = false
this.index = new Index({
tokenize: 'forward',
})
}
async _initSodium() {
if (!this._sodiumReady) {
await sodium.ready
this._sodiumReady = true
}
}
_hexToUint8Array(hex) {
const bytes = new Uint8Array(hex.length / 2)
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(hex.substr(i * 2, 2), 16)
}
return bytes
}
_concatUint8Arrays(a, b) {
const result = new Uint8Array(a.length + b.length)
result.set(a, 0)
result.set(b, a.length)
return result
}
_uint8ArrayToBase64(bytes) {
let binary = ''
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i])
}
return btoa(binary)
}
_base64ToUint8Array(base64) {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes
}
_encrypt(note) {
if (!this.encryptionKey) {
throw new Error('Encryption key not set')
}
const key = this._hexToUint8Array(this.encryptionKey)
if (key.length !== 32) {
throw new Error(
'Encryption key must be 64 hex characters (32 bytes)',
)
}
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES)
const message = JSON.stringify(note)
const ciphertext = sodium.crypto_secretbox_easy(
new TextEncoder().encode(message),
nonce,
key,
)
const combined = this._concatUint8Arrays(nonce, ciphertext)
return this._uint8ArrayToBase64(combined)
}
_decrypt(encryptedData) {
if (!this.encryptionKey) {
throw new Error('Encryption key not set')
}
const key = this._hexToUint8Array(this.encryptionKey)
if (key.length !== 32) {
throw new Error(
'Encryption key must be 64 hex characters (32 bytes)',
)
}
let combined
try {
combined = this._base64ToUint8Array(encryptedData)
} catch (e) {
throw new Error('Invalid encrypted data: not valid base64')
}
if (
combined.length <
sodium.crypto_secretbox_NONCEBYTES +
sodium.crypto_secretbox_MACBYTES
) {
throw new Error('Invalid encrypted data: too short')
}
const nonce = combined.slice(0, sodium.crypto_secretbox_NONCEBYTES)
const ciphertext = combined.slice(sodium.crypto_secretbox_NONCEBYTES)
let decrypted
try {
decrypted = sodium.crypto_secretbox_open_easy(
ciphertext,
nonce,
key,
)
} catch (e) {
throw new Error('Decryption failed: wrong key or corrupted data')
}
if (!decrypted) {
throw new Error('Decryption failed: no data returned')
}
const decryptedStr = new TextDecoder().decode(decrypted)
try {
return JSON.parse(decryptedStr)
} catch (e) {
throw new Error(
`Decryption succeeded but invalid JSON: ${decryptedStr}`,
)
}
}
async init() {
await this._initSodium()
await this.adapter.init()
this.notesCache.clear()
const encryptedNotes = await this.adapter.getAll()
for (const encryptedNote of encryptedNotes) {
try {
const note = this._decrypt(encryptedNote.data || encryptedNote)
this.notesCache.set(note.id, note)
const searchText =
note.plainText || this._extractPlainText(note.content)
this.index.add(note.id, note.title + '\n' + searchText)
} catch (error) {
console.error('Failed to decrypt note:', error)
}
}
}
_extractPlainText(content) {
if (!content) return ''
if (typeof content === 'string') return content
const extractText = (node) => {
if (typeof node === 'string') return node
if (!node || !node.content) return ''
return node.content.map(extractText).join(' ')
}
return extractText(content)
}
getCategories() {
const categories = new Set()
for (const note of this.notesCache.values()) {
if (note.category) {
categories.add(note.category)
}
}
return Array.from(categories).sort()
}
getCategoryNotes(categoryName = null) {
return Array.from(this.notesCache.values())
.filter((n) => n.category === categoryName)
.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
.map((n) => ({ ...n }))
}
getNote(id) {
const note = this.notesCache.get(id)
return note ? { ...note } : null
}
async createNote(metadata = {}, content = '', plainText = '') {
const id = uuidv4()
const now = new Date().toISOString()
const note = {
id,
title: metadata.title || 'Untitled',
category: metadata.category || null,
createdAt: now,
updatedAt: now,
content,
plainText,
}
const encryptedNote = {
id: note.id,
data: this._encrypt(note),
}
this.notesCache.set(id, note)
this.index.add(id, note.title + '\n' + plainText)
await this.adapter.create(encryptedNote)
return note
}
async deleteNote(id) {
await this.adapter.delete(id)
this.notesCache.delete(id)
this.index.remove(id)
}
async updateNote(id, updates = {}) {
const note = this.notesCache.get(id)
if (!note) throw new Error('Note not found')
const allowedFields = ['title', 'category', 'content', 'plainText']
for (const key of Object.keys(updates)) {
if (!allowedFields.includes(key)) {
throw new Error(`Invalid update field: ${key}`)
}
}
const updatedNote = {
...note,
...updates,
updatedAt: new Date().toISOString(),
}
const encryptedNote = {
id: updatedNote.id,
data: this._encrypt(updatedNote),
}
this.notesCache.set(id, updatedNote)
const searchText =
updatedNote.plainText || this._extractPlainText(updatedNote.content)
this.index.update(id, updatedNote.title + '\n' + searchText)
await this.adapter.update(encryptedNote)
return updatedNote
}
search(query) {
const ids = this.index.search(query, {
limit: 50,
suggest: true,
})
return ids.map((id) => this.notesCache.get(id))
}
}

56
src/core/PluginManager.js Normal file
View File

@@ -0,0 +1,56 @@
import PluginRegistry from './PluginRegistry.js'
import IpcAdapter from './IpcAdapter.js'
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)
}
return {
listPlugins() {
return registry.list()
},
getPlugin(pluginId) {
return registry.get(pluginId)
},
getAdapter(pluginId, adapterConfig = {}) {
const plugin = registry.get(pluginId)
if (environment === 'electron') {
return new IpcAdapter()
}
if (!plugin) {
throw new Error(`Plugin not found: ${pluginId}`)
}
return plugin.createAdapter(adapterConfig)
},
setActivePlugin(pluginId, adapterConfig = {}) {
activePluginId = pluginId
adapter = this.getAdapter(pluginId, adapterConfig)
return adapter
},
getActiveAdapter() {
return adapter
},
getActivePluginId() {
return activePluginId
},
getEnvironment() {
return environment
},
}
}

View File

@@ -0,0 +1,32 @@
export default class PluginRegistry {
constructor(environment = 'web') {
this.plugins = new Map()
this.environment = environment
}
register(plugin) {
if (!plugin.id) {
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)
}
get(id) {
return this.plugins.get(id)
}
list() {
return Array.from(this.plugins.values()).map((plugin) => ({
id: plugin.id,
name: plugin.name,
description: plugin.description,
configSchema: plugin.configSchema,
}))
}
}

77
src/core/index.js Normal file
View File

@@ -0,0 +1,77 @@
import createPluginManager from './PluginManager.js'
import createConfigManager from './Config.js'
import NotesAPI from './NotesAPI.js'
const generateEncryptionKey = () => {
const array = new Uint8Array(32)
crypto.getRandomValues(array)
return Array.from(array)
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}
let coreInstance = null
export function initializeCore(environment, plugins = []) {
const pluginManager = createPluginManager(environment, plugins)
const configManager = createConfigManager(environment)
let notesAPI = null
let initPromise = null
const getNotesAPI = async () => {
if (notesAPI) return notesAPI
if (!initPromise) {
initPromise = (async () => {
const config = await configManager.loadConfig()
let encryptionKey = config?.encryptionKey
if (!encryptionKey) {
encryptionKey = generateEncryptionKey()
await configManager.setConfig({ ...config, encryptionKey })
}
const pluginId = config?.activeAdapter || 'filesystem'
const adapterConfig =
config.adapters?.[config.activeAdapter] || {}
const adapter = pluginManager.getAdapter(
pluginId,
adapterConfig,
)
notesAPI = new NotesAPI(adapter, encryptionKey)
await notesAPI.init()
return notesAPI
})()
}
return initPromise
}
coreInstance = {
environment,
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'

4
src/core/types.ts Normal file
View File

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