Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(standalone): remove legacy OPFS handling
Elian Doranec48508b2900
diff --git a/apps/standalone/src/lightweight/in_app_help_provider.spec.ts b/apps/standalone/src/lightweight/in_app_help_provider.spec.tsindex 7329a370b5..bbae4093bf 100644--- a/apps/standalone/src/lightweight/in_app_help_provider.spec.ts+++ b/apps/standalone/src/lightweight/in_app_help_provider.spec.ts@@ -5,7 +5,27 @@ import StandaloneInAppHelpProvider from "./in_app_help_provider.js";describe("StandaloneInAppHelpProvider", () => {it("returns help data from the imported meta", () => {const provider = new StandaloneInAppHelpProvider();- // The placeholder help_meta.json is an empty array- expect(provider.getHelpHiddenSubtreeData()).toEqual([]);+ const data = provider.getHelpHiddenSubtreeData();+ expect(Array.isArray(data)).toBe(true);+ expect(data.length).toBeGreaterThan(0);+ });++ it("all entries use webView or book type (no doc type with docName)", () => {+ const provider = new StandaloneInAppHelpProvider();+ const data = provider.getHelpHiddenSubtreeData();++ function assertNoDocWithContent(items: typeof data) {+ for (const item of items) {+ if (item.type === "doc") {+ const hasDocName = item.attributes?.some(a => a.name === "docName");+ expect(hasDocName, `${item.title} should not have docName`).toBe(false);+ }+ if (item.children) {+ assertNoDocWithContent(item.children);+ }+ }+ }++ assertNoDocWithContent(data);});});diff --git a/apps/standalone/src/lightweight/sql_provider.ts b/apps/standalone/src/lightweight/sql_provider.tsindex 576784b5ab..5fbda8b4a6 100644--- a/apps/standalone/src/lightweight/sql_provider.ts+++ b/apps/standalone/src/lightweight/sql_provider.ts@@ -224,9 +224,6 @@ export default class BrowserSqlProvider implements DatabaseProvider {private initError?: Error;private statementCache: Map<string, WasmStatement> = new Map();- // OPFS state tracking- private opfsDbPath?: string;-// SAHPool state trackingprivate sahPoolUtil?: SAHPoolUtil;private sahPoolDbName?: string;@@ -296,15 +293,15 @@ export default class BrowserSqlProvider implements DatabaseProvider {/*** Install the OPFS SAHPool VFS. This pre-allocates a pool of OPFS* SyncAccessHandle objects, enabling WAL mode and significantly faster- * writes compared to the legacy OPFS VFS.+ * writes compared to in-memory databases.** Must be called after `initWasm()` and before `loadFromSahPool()`.* This is async because it acquires OPFS file handles.*- * Unlike the legacy OPFS VFS, SAHPool does **not** require SharedArrayBuffer- * or COOP/COEP headers — it only needs OPFS itself (a Worker context with- * `navigator.storage.getDirectory`). This makes it usable in Capacitor's- * Android WebView, which doesn't support cross-origin isolation.+ * SAHPool does **not** require SharedArrayBuffer or COOP/COEP headers — it+ * only needs OPFS itself (a Worker context with `navigator.storage.getDirectory`).+ * This makes it usable in Capacitor's Android WebView, which doesn't support+ * cross-origin isolation.** @param options.directory - OPFS directory for the pool (default: auto-derived from VFS name)* @param options.initialCapacity - Minimum number of file slots (default: 6)@@ -349,7 +346,7 @@ export default class BrowserSqlProvider implements DatabaseProvider {/*** Load or create a database using the SAHPool VFS.* This is the preferred method for persistent storage — it supports WAL mode- * and is significantly faster than the legacy OPFS VFS.+ * and is significantly faster than alternatives.** @param dbName - Virtual filename within the pool (e.g., "/trilium.db").* Must start with a slash.@@ -369,9 +366,8 @@ export default class BrowserSqlProvider implements DatabaseProvider {try {this.db = new this.sahPoolUtil.OpfsSAHPoolDb(dbName);this.sahPoolDbName = dbName;- this.opfsDbPath = undefined;- // SAHPool supports WAL mode — the key advantage over legacy OPFS VFS+ // SAHPool supports WAL modethis.db.exec("PRAGMA journal_mode = WAL");this.db.exec("PRAGMA synchronous = NORMAL");@@ -391,97 +387,11 @@ export default class BrowserSqlProvider implements DatabaseProvider {return this.sahPoolDbName !== undefined;}- // ==================== Legacy OPFS Support ====================-- /**- * Check if the legacy OPFS VFS is available.- * This requires:- * - Running in a Worker context- * - Browser support for OPFS APIs- * - COOP/COEP headers sent by the server (for SharedArrayBuffer)- *- * @returns true if legacy OPFS VFS is available for use- */- isOpfsAvailable(): boolean {- this.ensureSqlite3();- // SQLite WASM automatically installs the OPFS VFS if the environment supports it- // We can check for its presence via sqlite3_vfs_find or the OpfsDb class- return this.sqlite3!.oo1.OpfsDb !== undefined;- }-- /**- * Load or create a database stored in OPFS for persistent storage.- *- * **Prefer `loadFromSahPool()` over this method** — it supports WAL mode- * and is significantly faster. This method is kept for migration purposes.- * The database will persist across browser sessions.- *- * Requires COOP/COEP headers to be set by the server:- * - Cross-Origin-Opener-Policy: same-origin- * - Cross-Origin-Embedder-Policy: require-corp- *- * @param path - The path for the database file in OPFS (e.g., "/trilium.db")- * Paths without a leading slash are treated as relative to OPFS root.- * Leading directories are created automatically.- * @param options - Additional options- * @throws Error if OPFS VFS is not available- *- * @example- * ```typescript- * const provider = new BrowserSqlProvider();- * await provider.initWasm();- * if (provider.isOpfsAvailable()) {- * provider.loadFromOpfs("/my-database.db");- * } else {- * console.warn("OPFS not available, using in-memory database");- * provider.loadFromMemory();- * }- * ```- */- loadFromOpfs(path: string, options: { createIfNotExists?: boolean } = {}): void {- this.ensureSqlite3();-- if (!this.isOpfsAvailable()) {- throw new Error(- "OPFS VFS is not available. This requires:\n" +- "1. Running in a Worker context\n" +- "2. Browser support for OPFS (Chrome 102+, Firefox 111+, Safari 17+)\n" +- "3. COOP/COEP headers from the server:\n" +- " Cross-Origin-Opener-Policy: same-origin\n" +- " Cross-Origin-Embedder-Policy: require-corp"- );- }-- console.log(`[BrowserSqlProvider] Loading database from OPFS: ${path}`);- const startTime = performance.now();-- try {- // OpfsDb automatically creates directories in the path- // Mode 'c' = create if not exists- const mode = options.createIfNotExists !== false ? 'c' : '';- this.db = new this.sqlite3!.oo1.OpfsDb(path, mode);- this.opfsDbPath = path;- this.sahPoolDbName = undefined;-- // Configure the database for legacy OPFS- // Note: WAL mode is not supported by the legacy OPFS VFS- this.db.exec("PRAGMA journal_mode = DELETE");- this.db.exec("PRAGMA synchronous = NORMAL");-- const loadTime = performance.now() - startTime;- console.log(`[BrowserSqlProvider] OPFS database loaded in ${loadTime.toFixed(2)}ms`);- } catch (e) {- const error = e instanceof Error ? e : new Error(String(e));- console.error(`[BrowserSqlProvider] Failed to load OPFS database: ${error.message}`);- throw error;- }- }-/**- * Check if the currently open database is stored in OPFS (legacy or SAHPool).+ * Check if the currently open database is stored in OPFS (via SAHPool).*/get isUsingOpfs(): boolean {- return this.opfsDbPath !== undefined || this.sahPoolDbName !== undefined;+ return this.sahPoolDbName !== undefined;}/**@@ -489,7 +399,7 @@ export default class BrowserSqlProvider implements DatabaseProvider {* Returns undefined if not using OPFS.*/get currentOpfsPath(): string | undefined {- return this.opfsDbPath ?? this.sahPoolDbName;+ return this.sahPoolDbName;}/**@@ -509,15 +419,13 @@ export default class BrowserSqlProvider implements DatabaseProvider {return tableExists !== undefined;}- // ==================== End OPFS Support ====================-loadFromFile(_path: string, _isReadOnly: boolean): void {// Browser environment doesn't have direct file system access.// Use SAHPool or OPFS for persistent storage.throw new Error("loadFromFile is not supported in browser environment. " +"Use loadFromMemory() for temporary databases, loadFromBuffer() to load from data, " +- "loadFromSahPool() (preferred) or loadFromOpfs() for persistent storage."+ "or loadFromSahPool() for persistent storage.");}@@ -525,8 +433,7 @@ export default class BrowserSqlProvider implements DatabaseProvider {* Create an empty in-memory database.* Data will be lost when the page is closed.*- * For persistent storage, use loadFromOpfs() instead.- * To load demo data, call initializeDemoDatabase() after this.+ * For persistent storage, use loadFromSahPool() instead.*/loadFromMemory(): void {this.ensureSqlite3();@@ -534,7 +441,6 @@ export default class BrowserSqlProvider implements DatabaseProvider {const startTime = performance.now();this.db = new this.sqlite3!.oo1.DB(":memory:", "c");- this.opfsDbPath = undefined;this.sahPoolDbName = undefined;this.db.exec("PRAGMA journal_mode = WAL");@@ -557,7 +463,6 @@ export default class BrowserSqlProvider implements DatabaseProvider {// once we swap connections. Drop them so callers re-prepare.this.clearStatementCache();this.db = new this.sqlite3!.oo1.DB({ filename: ":memory:", flags: "c" });- this.opfsDbPath = undefined;this.sahPoolDbName = undefined;const rc = this.sqlite3!.capi.sqlite3_deserialize(@@ -702,8 +607,6 @@ export default class BrowserSqlProvider implements DatabaseProvider {this.db = undefined;}- // Reset OPFS / SAHPool state- this.opfsDbPath = undefined;this.sahPoolDbName = undefined;}@@ -735,7 +638,7 @@ export default class BrowserSqlProvider implements DatabaseProvider {if (!this.db) {throw new Error("Database not opened. Call loadFromMemory(), loadFromBuffer(), " +- "loadFromSahPool(), or loadFromOpfs() first."+ "loadFromSahPool() first.");}}diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex 0bc8a731ce..57d96ae0a9 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -80,71 +80,6 @@ let initError: Error | null = null;let queryString = "";let useNativeHttp = false;-/**- * Check whether a file exists at the OPFS root. Used to decide whether the- * test fixture needs to be seeded or whether we should reuse the existing- * DB (preserving changes made earlier in the same test — e.g. options set- * before a page reload).- */-async function opfsFileExists(fileName: string): Promise<boolean> {- if (typeof navigator === "undefined" || !navigator.storage?.getDirectory) {- return false;- }- const root = await navigator.storage.getDirectory();- try {- await root.getFileHandle(fileName);- return true;- } catch {- return false;- }-}--/**- * Write a raw byte buffer to an OPFS file. Used to drop the test fixture DB- * into OPFS as a regular file so SQLite's OPFS VFS can then open it. Requires- * a Worker context (`createSyncAccessHandle` isn't available on the main thread- * in some browsers).- */-async function writeOpfsFile(fileName: string, buffer: Uint8Array): Promise<void> {- const root = await navigator.storage.getDirectory();- const fileHandle = await root.getFileHandle(fileName, { create: true });- const accessHandle = await (fileHandle as unknown as {- createSyncAccessHandle(): Promise<{- truncate(size: number): void;- write(buffer: Uint8Array, opts: { at: number }): number;- flush(): void;- close(): void;- }>;- }).createSyncAccessHandle();- try {- accessHandle.truncate(0);- accessHandle.write(buffer, { at: 0 });- accessHandle.flush();- } finally {- accessHandle.close();- }-}--/**- * Read a file from the OPFS root into a Uint8Array.- * Used during migration from legacy OPFS VFS to SAHPool.- */-async function readOpfsFile(fileName: string): Promise<Uint8Array> {- const root = await navigator.storage.getDirectory();- const fileHandle = await root.getFileHandle(fileName);- const file = await fileHandle.getFile();- return new Uint8Array(await file.arrayBuffer());-}--/**- * Delete a file from the OPFS root.- * Used to clean up the legacy OPFS database after migration to SAHPool.- */-async function deleteOpfsFile(fileName: string): Promise<void> {- const root = await navigator.storage.getDirectory();- await root.removeEntry(fileName);-}-/*** Verify that a buffer contains a valid SQLite database by checking the* 16-byte magic string "SQLite format 3\0".@@ -161,76 +96,23 @@ function assertSqliteMagic(buffer: Uint8Array, source: string): void {}/**- * Migrate database from legacy OPFS VFS to SAHPool VFS.- * Checks if a legacy `/trilium.db` file exists in the OPFS root, and if the- * SAHPool doesn't already have it. If migration is needed, the legacy file is- * read, imported into the pool, and then deleted.+ * Load the test fixture database for integration tests.+ * Seeds from the fixture if not already present.*/-async function migrateFromLegacyOpfs(dbName: string): Promise<void> {- const legacyFileName = dbName.replace(/^\//, ""); // strip leading slash- const legacyExists = await opfsFileExists(legacyFileName);-- if (!legacyExists) {- return; // Nothing to migrate+async function loadTestDatabase(sahPoolAvailable: boolean, dbName: string): Promise<void> {+ if (!sahPoolAvailable) {+ throw new Error("SAHPool is required for integration tests.");}- // Check if SAHPool already has this DB (e.g. migration already happened)const poolFiles = sqlProvider!.sahPool!.getFileNames();- if (poolFiles.includes(dbName)) {- console.log("[Worker] SAHPool already contains the database, deleting legacy OPFS file...");- await deleteOpfsFile(legacyFileName);- return;- }-- console.log("[Worker] Migrating database from legacy OPFS to SAHPool VFS...");- const startTime = performance.now();-- const buffer = await readOpfsFile(legacyFileName);- assertSqliteMagic(buffer, "Legacy OPFS database");-- await sqlProvider!.sahPool!.importDb(dbName, buffer);- await deleteOpfsFile(legacyFileName);-- // Also clean up legacy journal/WAL files if they exist- for (const suffix of ["-journal", "-wal", "-shm"]) {- try {- await deleteOpfsFile(legacyFileName + suffix);- } catch {- // Ignore — file may not exist- }- }-- const elapsed = performance.now() - startTime;- console.log(`[Worker] Migration complete in ${elapsed.toFixed(2)}ms (${buffer.byteLength} bytes)`);-}--/**- * Load the test fixture database for integration tests.- * Seeds from the fixture if not already present, using SAHPool when available.- */-async function loadTestDatabase(sahPoolAvailable: boolean, dbName: string): Promise<void> {- if (sahPoolAvailable) {- const poolFiles = sqlProvider!.sahPool!.getFileNames();- if (!poolFiles.includes(dbName)) {- console.log("[Worker] Integration test mode: seeding fixture database into SAHPool...");- const buffer = await fetchTestFixture();- await sqlProvider!.sahPool!.importDb(dbName, buffer);- } else {- console.log("[Worker] Integration test mode: reusing existing SAHPool DB from earlier in this test");- }- sqlProvider!.loadFromSahPool(dbName);+ if (!poolFiles.includes(dbName)) {+ console.log("[Worker] Integration test mode: seeding fixture database into SAHPool...");+ const buffer = await fetchTestFixture();+ await sqlProvider!.sahPool!.importDb(dbName, buffer);} else {- // Fallback to legacy OPFS for tests when SAHPool isn't available- const legacyFileName = dbName.replace(/^\//, "");- if (!(await opfsFileExists(legacyFileName))) {- console.log("[Worker] Integration test mode: seeding fixture database into OPFS...");- const buffer = await fetchTestFixture();- await writeOpfsFile(legacyFileName, buffer);- } else {- console.log("[Worker] Integration test mode: reusing existing OPFS DB from earlier in this test");- }- sqlProvider!.loadFromOpfs(dbName);+ console.log("[Worker] Integration test mode: reusing existing SAHPool DB from earlier in this test");}+ sqlProvider!.loadFromSahPool(dbName);}/**@@ -333,7 +215,7 @@ async function initialize(): Promise<void> {await sqlProvider!.installSahPool();sahPoolAvailable = true;} catch (e) {- logService.info(`[Worker] SAHPool VFS not available, will fall back to legacy OPFS or in-memory: ${e}`);+ logService.info(`[Worker] SAHPool VFS not available, will fall back to in-memory: ${e}`);}// Integration test mode is baked in at build time via the@@ -350,18 +232,9 @@ async function initialize(): Promise<void> {// the fixture, and subsequent inits in the same test reuse it.await loadTestDatabase(sahPoolAvailable, dbName);} else if (sahPoolAvailable) {- // SAHPool available — migrate from legacy OPFS if needed, then open- await migrateFromLegacyOpfs(dbName);logService.info("[Worker] SAHPool available, loading persistent database (WAL mode)...");sqlProvider!.loadFromSahPool(dbName);- } else if (sqlProvider!.isOpfsAvailable()) {- // Fall back to legacy OPFS VFS (no WAL, slower writes).- // This only kicks in if SAHPool installation failed for some- // reason but SharedArrayBuffer + legacy OPFS are both available.- logService.info("[Worker] SAHPool unavailable; using legacy OPFS VFS (no WAL mode).");- sqlProvider!.loadFromOpfs(dbName);} else {- // Fall back to in-memory database (non-persistent).// SAHPool only needs a Worker + OPFS API, so reaching this// branch means the environment lacks OPFS entirely.logService.info("[Worker] OPFS not available, using in-memory database (data will not persist)");