343 lines
13 KiB
JavaScript
343 lines
13 KiB
JavaScript
// Rôle : encapsule les opérations IndexedDB génériques utilisées par les toolboxes.
|
|
const DB_NAME = "sokkog";
|
|
const DB_VERSION = 1;
|
|
const KV_STORE = "kv";
|
|
const MODULE_STORE = "modules";
|
|
|
|
let dbPromise;
|
|
|
|
export class StorageConflictError extends Error {
|
|
constructor(conflicts) {
|
|
super("Ces données ont été modifiées dans un autre onglet. La version enregistrée a été rechargée.");
|
|
this.name = "StorageConflictError";
|
|
this.conflicts = conflicts;
|
|
}
|
|
}
|
|
|
|
function openDatabase() {
|
|
if (dbPromise) return dbPromise;
|
|
dbPromise = new Promise((resolve, reject) => {
|
|
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
|
|
|
request.onupgradeneeded = () => {
|
|
const db = request.result;
|
|
if (!db.objectStoreNames.contains(KV_STORE)) db.createObjectStore(KV_STORE);
|
|
if (!db.objectStoreNames.contains(MODULE_STORE)) db.createObjectStore(MODULE_STORE, { keyPath: "key" });
|
|
};
|
|
|
|
request.onsuccess = () => resolve(request.result);
|
|
request.onerror = () => reject(request.error);
|
|
}).catch((error) => {
|
|
dbPromise = undefined;
|
|
throw error;
|
|
});
|
|
return dbPromise;
|
|
}
|
|
|
|
async function storeRequest(storeName, mode, callback) {
|
|
const db = await openDatabase();
|
|
const transaction = db.transaction(storeName, mode);
|
|
const store = transaction.objectStore(storeName);
|
|
let result;
|
|
await new Promise((resolve, reject) => {
|
|
transaction.oncomplete = () => resolve();
|
|
transaction.onerror = () => reject(transaction.error);
|
|
transaction.onabort = () => reject(transaction.error);
|
|
try {
|
|
const request = callback(store);
|
|
request.onsuccess = () => { result = request.result; };
|
|
request.onerror = () => reject(request.error);
|
|
} catch (error) {
|
|
transaction.abort();
|
|
reject(error);
|
|
}
|
|
});
|
|
return result;
|
|
}
|
|
|
|
export async function getValue(key, fallback) {
|
|
const value = await storeRequest(KV_STORE, "readonly", (store) => store.get(key));
|
|
return value == null ? fallback : value;
|
|
}
|
|
|
|
export async function setValue(key, value) {
|
|
await storeRequest(KV_STORE, "readwrite", (store) => store.put(value, key));
|
|
}
|
|
|
|
export async function getToolboxes() {
|
|
return getValue("toolboxes", []);
|
|
}
|
|
|
|
export async function setToolboxes(toolboxes) {
|
|
await setValue("toolboxes", toolboxes);
|
|
}
|
|
|
|
export async function getLinks() {
|
|
return getValue("links", {});
|
|
}
|
|
|
|
export async function setLinks(links) {
|
|
await setValue("links", links);
|
|
}
|
|
|
|
export async function getSetting(key, fallback) {
|
|
return getValue(`setting:${key}`, fallback);
|
|
}
|
|
|
|
export async function setSetting(key, value) {
|
|
await setValue(`setting:${key}`, value);
|
|
}
|
|
|
|
export async function getAllModuleData(excludedKeys = []) {
|
|
if (!excludedKeys.length) return storeRequest(MODULE_STORE, "readonly", (store) => store.getAll());
|
|
const excluded = new Set(excludedKeys);
|
|
const keys = await storeRequest(MODULE_STORE, "readonly", (store) => store.getAllKeys());
|
|
return getModuleDataEntries(keys.filter((key) => !excluded.has(key)));
|
|
}
|
|
|
|
export async function getModuleDataEntries(keys) {
|
|
if (!keys.length) return [];
|
|
const db = await openDatabase();
|
|
return new Promise((resolve, reject) => {
|
|
const transaction = db.transaction(MODULE_STORE, "readonly");
|
|
const entries = [];
|
|
transaction.oncomplete = () => resolve(entries);
|
|
transaction.onerror = () => reject(transaction.error);
|
|
transaction.onabort = () => reject(transaction.error);
|
|
for (const key of keys) {
|
|
const request = transaction.objectStore(MODULE_STORE).get(key);
|
|
request.onsuccess = () => { if (request.result) entries.push(request.result); };
|
|
}
|
|
});
|
|
}
|
|
|
|
export async function setModuleData(key, data) {
|
|
await storeRequest(MODULE_STORE, "readwrite", (store) => store.put({ key, data }));
|
|
}
|
|
|
|
export async function removeModuleData(key) {
|
|
await storeRequest(MODULE_STORE, "readwrite", (store) => store.delete(key));
|
|
}
|
|
|
|
export async function removeModuleDataKeys(keys) {
|
|
if (!keys.length) return;
|
|
const db = await openDatabase();
|
|
await new Promise((resolve, reject) => {
|
|
const transaction = db.transaction(MODULE_STORE, "readwrite");
|
|
const store = transaction.objectStore(MODULE_STORE);
|
|
keys.forEach((key) => store.delete(key));
|
|
transaction.oncomplete = () => resolve();
|
|
transaction.onerror = () => reject(transaction.error);
|
|
transaction.onabort = () => reject(transaction.error);
|
|
});
|
|
}
|
|
|
|
export async function setToolboxSnapshot(toolboxes, links, moduleData, preservedKeys = []) {
|
|
const db = await openDatabase();
|
|
await new Promise((resolve, reject) => {
|
|
const transaction = db.transaction([KV_STORE, MODULE_STORE], "readwrite");
|
|
const kv = transaction.objectStore(KV_STORE);
|
|
const modules = transaction.objectStore(MODULE_STORE);
|
|
transaction.oncomplete = () => resolve();
|
|
transaction.onerror = () => reject(transaction.error);
|
|
transaction.onabort = () => reject(transaction.error);
|
|
try {
|
|
kv.put(toolboxes, "toolboxes");
|
|
kv.put(links, "links");
|
|
if (!preservedKeys.length) modules.clear();
|
|
else {
|
|
// Parcourir uniquement les clés évite de décoder les médias conservés sur disque.
|
|
const kept = new Set([...preservedKeys, ...Object.keys(moduleData || {})]);
|
|
const request = modules.openKeyCursor();
|
|
request.onsuccess = () => {
|
|
try {
|
|
const cursor = request.result;
|
|
if (!cursor) return;
|
|
if (!kept.has(cursor.key)) modules.delete(cursor.key);
|
|
cursor.continue();
|
|
} catch (error) {
|
|
transaction.abort();
|
|
reject(error);
|
|
}
|
|
};
|
|
}
|
|
Object.entries(moduleData || {}).forEach(([key, data]) => modules.put({ key, data }));
|
|
} catch (error) {
|
|
transaction.abort();
|
|
reject(error);
|
|
}
|
|
});
|
|
}
|
|
|
|
function changeMatches(change, exists, value) {
|
|
if (change.expected === "any") return true;
|
|
if (change.expected === "missing") return !exists;
|
|
return exists && storageValuesEqual(value, change.expectedValue);
|
|
}
|
|
|
|
export function storageValuesEqual(left, right) {
|
|
if (Object.is(left, right)) return true;
|
|
if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
|
|
if (Array.isArray(left) !== Array.isArray(right)) return false;
|
|
const leftKeys = Object.keys(left);
|
|
const rightKeys = Object.keys(right);
|
|
if (leftKeys.length !== rightKeys.length) return false;
|
|
return leftKeys.every((key) => Object.hasOwn(right, key) && storageValuesEqual(left[key], right[key]));
|
|
}
|
|
|
|
function applyRecordChanges(current, changes, resource, conflicts) {
|
|
const next = { ...(current || {}) };
|
|
for (const change of changes) {
|
|
const exists = Object.hasOwn(current || {}, change.key);
|
|
if (!changeMatches(change, exists, current?.[change.key])) {
|
|
conflicts.push(`${resource}:${change.key}`);
|
|
continue;
|
|
}
|
|
if (change.nextExists) next[change.key] = change.nextValue;
|
|
else delete next[change.key];
|
|
}
|
|
return next;
|
|
}
|
|
|
|
function applyToolboxChanges(current, mutation, conflicts) {
|
|
const currentById = Object.fromEntries(current.map((toolbox) => [toolbox.id, toolbox]));
|
|
const changedById = new Map(mutation.changes.map((change) => [change.key, change]));
|
|
for (const change of mutation.changes) {
|
|
const exists = Object.hasOwn(currentById, change.key);
|
|
if (!changeMatches(change, exists, currentById[change.key])) conflicts.push(`toolbox:${change.key}`);
|
|
}
|
|
if (mutation.order) {
|
|
const expected = new Set(mutation.order.expectedIds);
|
|
const actualKnownOrder = current.map((toolbox) => toolbox.id).filter((id) => expected.has(id));
|
|
if (!storageValuesEqual(actualKnownOrder, mutation.order.expectedIds)) conflicts.push("toolboxes:order");
|
|
}
|
|
if (conflicts.length) return current;
|
|
|
|
const retained = current.flatMap((toolbox) => {
|
|
const change = changedById.get(toolbox.id);
|
|
if (!change) return [toolbox];
|
|
return change.nextExists ? [change.nextValue] : [];
|
|
});
|
|
const retainedIds = new Set(retained.map((toolbox) => toolbox.id));
|
|
const additions = mutation.nextIds
|
|
.filter((id) => !retainedIds.has(id) && changedById.get(id)?.nextExists)
|
|
.map((id) => changedById.get(id).nextValue);
|
|
const combined = [...additions, ...retained];
|
|
if (!mutation.order) return combined;
|
|
|
|
const expectedIds = new Set(mutation.expectedIds);
|
|
const remote = combined.filter((toolbox) => !expectedIds.has(toolbox.id) && !changedById.has(toolbox.id));
|
|
const combinedById = new Map(combined.map((toolbox) => [toolbox.id, toolbox]));
|
|
const ordered = mutation.nextIds.map((id) => combinedById.get(id)).filter(Boolean);
|
|
return [...remote, ...ordered];
|
|
}
|
|
|
|
export async function mutateToolboxStorage(mutation, { normalizeToolboxes = (value) => value } = {}) {
|
|
if (!mutation?.changed) return;
|
|
const db = await openDatabase();
|
|
await new Promise((resolve, reject) => {
|
|
const transaction = db.transaction([KV_STORE, MODULE_STORE], "readwrite");
|
|
const kv = transaction.objectStore(KV_STORE);
|
|
const modules = transaction.objectStore(MODULE_STORE);
|
|
const toolboxRequest = kv.get("toolboxes");
|
|
const linksRequest = kv.get("links");
|
|
const moduleRequests = new Map(mutation.modules.flatMap((change) => {
|
|
if (change.expected === "any") return [];
|
|
return [[change.key, {
|
|
kind: change.expected === "missing" ? "count" : "value",
|
|
request: change.expected === "missing" ? modules.count(change.key) : modules.get(change.key)
|
|
}]];
|
|
}));
|
|
let remaining = 2 + moduleRequests.size;
|
|
let failure;
|
|
|
|
transaction.oncomplete = () => resolve();
|
|
transaction.onerror = () => reject(failure || transaction.error);
|
|
transaction.onabort = () => reject(failure || transaction.error);
|
|
|
|
function applyWhenReady() {
|
|
remaining -= 1;
|
|
if (remaining) return;
|
|
try {
|
|
const currentToolboxes = normalizeToolboxes(Array.isArray(toolboxRequest.result) ? toolboxRequest.result : []);
|
|
const currentLinks = linksRequest.result && typeof linksRequest.result === "object" ? linksRequest.result : {};
|
|
const currentModules = {};
|
|
for (const [key, entry] of moduleRequests) {
|
|
if (entry.kind === "count" && entry.request.result > 0) currentModules[key] = true;
|
|
if (entry.kind === "value" && entry.request.result) currentModules[key] = entry.request.result.data;
|
|
}
|
|
const conflicts = [];
|
|
const nextToolboxes = applyToolboxChanges(currentToolboxes, mutation.toolboxes, conflicts);
|
|
const nextLinks = applyRecordChanges(currentLinks, mutation.links, "link", conflicts);
|
|
applyRecordChanges(currentModules, mutation.modules, "module", conflicts);
|
|
|
|
const validModuleKeys = new Set(nextToolboxes.flatMap((toolbox) => (toolbox.modules || [])
|
|
.map((module) => `${toolbox.id}:${module.id}`)));
|
|
for (const change of mutation.modules) {
|
|
if (change.nextExists && change.key.includes(":") && !validModuleKeys.has(change.key)) {
|
|
conflicts.push(`module-target:${change.key}`);
|
|
}
|
|
}
|
|
const validToolboxIds = new Set(nextToolboxes.map((toolbox) => toolbox.id));
|
|
for (const change of mutation.links) {
|
|
if (change.nextExists && change.nextValue && !validToolboxIds.has(change.nextValue)) {
|
|
conflicts.push(`link-target:${change.key}`);
|
|
}
|
|
}
|
|
if (conflicts.length) {
|
|
failure = new StorageConflictError([...new Set(conflicts)]);
|
|
transaction.abort();
|
|
return;
|
|
}
|
|
|
|
if (mutation.toolboxes.changes.length || mutation.toolboxes.order) kv.put(nextToolboxes, "toolboxes");
|
|
if (mutation.links.length) kv.put(nextLinks, "links");
|
|
for (const change of mutation.modules) {
|
|
if (change.nextExists) modules.put({ key: change.key, data: change.nextValue });
|
|
else modules.delete(change.key);
|
|
}
|
|
} catch (error) {
|
|
failure = error;
|
|
transaction.abort();
|
|
}
|
|
}
|
|
|
|
toolboxRequest.onsuccess = applyWhenReady;
|
|
linksRequest.onsuccess = applyWhenReady;
|
|
for (const { request } of moduleRequests.values()) request.onsuccess = applyWhenReady;
|
|
});
|
|
}
|
|
|
|
export async function getToolboxSnapshot(toolboxId = "") {
|
|
const db = await openDatabase();
|
|
return new Promise((resolve, reject) => {
|
|
const transaction = db.transaction([KV_STORE, MODULE_STORE], "readonly");
|
|
const kv = transaction.objectStore(KV_STORE);
|
|
const modules = transaction.objectStore(MODULE_STORE);
|
|
const toolboxes = kv.get("toolboxes");
|
|
const links = kv.get("links");
|
|
const moduleEntries = [];
|
|
toolboxes.onsuccess = () => {
|
|
const storedToolboxes = Array.isArray(toolboxes.result) ? toolboxes.result : [];
|
|
const selected = toolboxId ? storedToolboxes.filter((item) => item?.id === toolboxId) : storedToolboxes;
|
|
for (const toolbox of selected) {
|
|
for (const module of toolbox?.modules || []) {
|
|
const request = modules.get(`${toolbox.id}:${module.id}`);
|
|
request.onsuccess = () => { if (request.result) moduleEntries.push(request.result); };
|
|
}
|
|
}
|
|
};
|
|
transaction.oncomplete = () => resolve({
|
|
toolboxes: Array.isArray(toolboxes.result) ? toolboxes.result : [],
|
|
links: links.result && typeof links.result === "object" ? links.result : {},
|
|
moduleData: Object.fromEntries(moduleEntries.map((entry) => [entry.key, entry.data]))
|
|
});
|
|
transaction.onerror = () => reject(transaction.error);
|
|
transaction.onabort = () => reject(transaction.error);
|
|
});
|
|
}
|
|
|
|
export async function getStorageEstimate() {
|
|
if (!navigator.storage?.estimate) return { usage: 0, quota: 0 };
|
|
return navigator.storage.estimate();
|
|
}
|