Implement TASK-015 metadata-driven exercise logging

This commit is contained in:
rob
2026-11-04 22:22:26 +00:00
parent 669bfc3910
commit 9c0e82037f
31 changed files with 1537 additions and 416 deletions
+65
View File
@@ -0,0 +1,65 @@
// Versioned adapter only; TASK-009 owns the user-facing import/export workflow.
import { initialRoutine, exerciseDefinitions } from './data/index.js'
import { openLocalDatabase } from './localDatabase.js'
import { performanceError } from './performanceModel.js'
import { performanceKey } from './performanceStorage.js'
import { validEntry } from './strengthStorage.js'
const stores = ['routineOverrides', 'strengthEntries', 'performanceEntries']
function validJSON(value) {
if (value === null || typeof value === 'string' || typeof value === 'boolean') return true
if (typeof value === 'number') return Number.isFinite(value)
return typeof value === 'object' && Object.values(value).every(validJSON)
}
export function parseBackup(input) {
let backup
try { backup = typeof input === 'string' ? JSON.parse(input) : structuredClone(input) }
catch { throw new Error('Invalid backup JSON.') }
if (backup?.format !== 'workout-tracker' || ![1, 2].includes(backup.version) || !backup.stores || typeof backup.stores !== 'object' || Array.isArray(backup.stores)) throw new Error('Unsupported backup schema.')
if (Object.keys(backup.stores).some((store) => !stores.includes(store))) throw new Error('Unsupported backup store.')
// Version 1 is the legacy adapter envelope with the two original stores.
for (const store of stores) {
if (backup.version === 1 && store === 'performanceEntries' && backup.stores[store] == null) backup.stores[store] = []
if (!Array.isArray(backup.stores[store])) throw new Error(`Missing backup store: ${store}.`)
const keys = new Set()
for (const entry of backup.stores[store]) {
if (!entry || typeof entry.key !== 'string' || keys.has(entry.key) || !validJSON(entry.value)) throw new Error('Invalid or duplicate backup entry.')
keys.add(entry.key)
if (store === 'strengthEntries' && (!/^\d{4}-\d{2}-\d{2}:.+/.test(entry.key) || !validEntry(entry.value))) throw new Error('Invalid legacy strength entry.')
if (store === 'performanceEntries' && (performanceError(entry.value) || entry.key !== performanceKey(entry.value.date, entry.value.period, entry.value.exerciseId))) throw new Error('Invalid detailed performance entry.')
if (store === 'routineOverrides' && entry.key === 'dailyHangGoalSec' && (!Number.isSafeInteger(entry.value) || entry.value <= 0)) throw new Error('Invalid hanging goal.')
}
}
return backup
}
export async function exportBackup() {
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const tx = db.transaction(stores, 'readonly')
const data = Object.fromEntries(stores.map((store) => [store, []]))
for (const name of stores) {
const cursor = tx.objectStore(name).openCursor()
cursor.onsuccess = () => {
if (cursor.result) { data[name].push({ key: cursor.result.key, value: cursor.result.value }); cursor.result.continue() }
}
}
tx.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 2, reference: { exerciseDefinitions, initialRoutine }, stores: data })) }
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) }
})
}
export async function importBackup(input, { replace = false } = {}) {
const backup = parseBackup(input) // Validate everything before opening a write transaction.
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const tx = db.transaction(stores, 'readwrite')
try {
for (const name of stores) {
const store = tx.objectStore(name)
if (replace) store.clear()
for (const { key, value } of backup.stores[name]) store.add(value, key)
}
} catch { tx.abort() }
tx.oncomplete = () => { db.close(); resolve() }
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Import failed; existing data was left unchanged. Duplicate keys require an explicit replacement.')) }
})
}