;(function (global) { 'use strict' const result = global.IWBStorageResult const unwrap = (value) => value && value.ok === true && Object.prototype.hasOwnProperty.call(value, 'value') ? value.value : value const create = (options) => { const config = options || {} const local = config.local const indexed = config.indexedDb const localGroupsKey = config.groupsKey || 'iwb_web_groups' const localGroupGroupsKey = config.groupGroupsKey || 'iwb_web_groupgroups' const indexedKey = config.indexedKey || 'groups' const migrations = config.migrations || global.IWBStorageMigrations const migrate = (value) => migrations && migrations.migrateGroups ? migrations.migrateGroups(value) : { ok: true, changed: false, value } const normalize = (value) => ({ schemaVersion: config.schemaVersion || 1, groups: Array.isArray(value && value.groups) ? value.groups : [], groupGroups: Array.isArray(value && value.groupGroups) ? value.groupGroups : [] }) const readSource = async () => { if (indexed && typeof indexed.kvGet === 'function') { const stored = await indexed.kvGet(indexedKey) const value = unwrap(stored) if (stored && stored.ok !== false && value) return { value, source: 'indexeddb' } } const groups = unwrap(local.get(localGroupsKey, [])) || [] const groupGroups = unwrap(local.get(localGroupGroupsKey, [])) || [] return { value: { groups, groupGroups }, source: 'local' } } return { async read() { try { const source = await readSource() const migrated = migrate(source.value) if (!migrated.ok) return result.fail(result.error(migrated.code === 'unsupported-schema' ? 'unsupported' : 'validation', migrated.code || 'invalid-groups', migrated.error || '节点组数据格式无效', false)) if (migrated.changed && indexed && typeof indexed.kvPut === 'function') await indexed.kvPut(indexedKey, migrated.value) return result.ok(migrated.value, { source: source.source, changed: !!migrated.changed }) } catch (e) { return result.fail(result.from(e, 'unavailable'), { degraded: true }) } }, async write(groups, groupGroups) { const data = normalize({ groups, groupGroups }) try { let indexedOk = false if (indexed && typeof indexed.kvPut === 'function') { const stored = await indexed.kvPut(indexedKey, data) indexedOk = !!(stored && (stored.ok === undefined ? stored : stored.ok)) } const ls1 = local.set(localGroupsKey, data.groups) const ls2 = local.set(localGroupGroupsKey, data.groupGroups) const localOk = !!(ls1 && (ls1.ok === undefined ? ls1 : ls1.ok)) && !!(ls2 && (ls2.ok === undefined ? ls2 : ls2.ok)) if (indexedOk || localOk) return result.ok(true, { degraded: !indexedOk && localOk, source: indexedOk ? 'indexeddb' : 'local' }) return result.fail(result.error('unavailable', 'groups-write-failed', '节点组保存失败:浏览器本地存储不可用', false), { degraded: true }) } catch (e) { return result.fail(result.from(e, 'unavailable'), { degraded: true }) } }, } } global.IWBStorageGroups = { create } })(typeof window !== 'undefined' ? window : globalThis)