40 lines
2.1 KiB
JavaScript
40 lines
2.1 KiB
JavaScript
;(function (global) {
|
|
'use strict'
|
|
const result = global.IWBStorageResult
|
|
const create = (options) => {
|
|
const config = options || {}
|
|
const migrations = config.migrations || global.IWBStorageMigrations
|
|
const checksum = config.checksum
|
|
const payload = (data) => {
|
|
const copy = JSON.parse(JSON.stringify(data || {}))
|
|
delete copy.checksum
|
|
delete copy.imagesData
|
|
return copy
|
|
}
|
|
return {
|
|
async validate(data) {
|
|
if (!data || typeof data !== 'object' || Array.isArray(data) || data.kind !== 'backup' || !data.items || typeof data.items !== 'object' || Array.isArray(data.items)) return result.fail(result.error('validation', 'invalid-backup', '不是有效的备份文件', false))
|
|
const migrate = migrations && migrations.migrateBackup ? migrations.migrateBackup(data) : { ok: true, value: data }
|
|
if (!migrate.ok) return result.fail(result.error(migrate.code === 'unsupported-schema' ? 'unsupported' : 'validation', migrate.code || 'invalid-backup', migrate.error || '备份数据格式无效', false))
|
|
if (data.checksum && typeof checksum === 'function') {
|
|
const actual = await checksum(JSON.stringify(payload(data)))
|
|
if (actual !== data.checksum) return result.fail(result.error('validation', 'checksum-mismatch', '备份校验和不匹配', false))
|
|
}
|
|
return result.ok(migrate.value)
|
|
},
|
|
async parse(input) {
|
|
try {
|
|
const data = typeof input === 'string' ? JSON.parse(input) : input
|
|
return this.validate(data)
|
|
} catch (e) { return result.fail(result.error('validation', 'invalid-backup-json', '备份文件解析失败', false)) }
|
|
},
|
|
async export(items, options) {
|
|
const core = { app: 'image-workbench', kind: 'backup', backupVersion: 3, schemaVersion: config.schemaVersion || 2, at: Date.now(), items: items || {} }
|
|
if (typeof checksum === 'function') core.checksum = await checksum(JSON.stringify(payload(core)))
|
|
return result.ok(core)
|
|
},
|
|
}
|
|
}
|
|
global.IWBStorageBackup = { create }
|
|
})(typeof window !== 'undefined' ? window : globalThis)
|