Skip to content

Build your personal knowledge base with Trilium Notes

e2e(standalone): use different seeding mechanism

Elian Doran1e4c6eb12c49
diff --git a/apps/client-standalone/src/local-server-worker.ts b/apps/client-standalone/src/local-server-worker.ts
index 3418beea02..77092cff65 100644
--- a/apps/client-standalone/src/local-server-worker.ts
+++ b/apps/client-standalone/src/local-server-worker.ts
@@ -78,26 +78,47 @@ let initError: Error | null = null;
let queryString = "";
/**
- * Remove every entry from the OPFS root. Used by integration tests to
- * guarantee a clean slate — the previous run's DB, logs, and backups would
- * otherwise survive and cross-contaminate the next run.
+ * 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 clearOpfs(): Promise<void> {
+async function opfsFileExists(fileName: string): Promise<boolean> {
if (typeof navigator === "undefined" || !navigator.storage?.getDirectory) {
- return;
+ return false;
}
- console.log("[Worker] Clearing OPFS...");
const root = await navigator.storage.getDirectory();
- const names: string[] = [];
- for await (const name of (root as unknown as { keys(): AsyncIterableIterator<string> }).keys()) {
- names.push(name);
+ try {
+ await root.getFileHandle(fileName);
+ return true;
+ } catch {
+ return false;
}
- for (const name of names) {
- try {
- await root.removeEntry(name, { recursive: true });
- } catch (err) {
- console.warn(`[Worker] Failed to remove OPFS entry "${name}":`, err);
- }
+}
+
+/**
+ * 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();
}
}
@@ -178,29 +199,35 @@ async function initialize(): Promise<void> {
const integrationTestMode = __TRILIUM_INTEGRATION_TEST__;
if (integrationTestMode === "memory") {
- // Wipe OPFS so e2e runs start from a clean slate (stale DB, logs,
- // backups from previous sessions would otherwise leak across runs).
- await clearOpfs();
-
- // Load the pre-built test fixture database for e2e tests
- console.log("[Worker] Integration test mode: loading fixture database...");
- const response = await fetch("/test-fixtures/document.db");
- if (!response.ok) {
- throw new Error(`Failed to fetch test fixture: ${response.status} ${response.statusText}`);
- }
- const buffer = new Uint8Array(await response.arrayBuffer());
- // Verify we actually got a SQLite database, not an SPA-fallback
- // index.html served for a missing file. SQLite databases start
- // with the 16-byte magic string "SQLite format 3\0".
- const magic = new TextDecoder().decode(buffer.subarray(0, 15));
- if (magic !== "SQLite format 3") {
- throw new Error(
- `Test fixture at /test-fixtures/document.db is not a SQLite database ` +
- `(got ${buffer.byteLength} bytes starting with "${magic}"). ` +
- `The file is likely missing and the SPA fallback is returning index.html.`
- );
+ // Use OPFS for the DB in integration test mode so option changes
+ // (and any other writes) survive page reloads within a single test.
+ // Playwright gives each test a fresh BrowserContext, which means a
+ // fresh OPFS — so on the first worker init of a test we seed from
+ // the fixture, and subsequent inits in the same test reuse it.
+ const opfsDbName = "trilium.db";
+ if (!(await opfsFileExists(opfsDbName))) {
+ console.log("[Worker] Integration test mode: seeding fixture database into OPFS...");
+ const response = await fetch("/test-fixtures/document.db");
+ if (!response.ok) {
+ throw new Error(`Failed to fetch test fixture: ${response.status} ${response.statusText}`);
+ }
+ const buffer = new Uint8Array(await response.arrayBuffer());
+ // Verify we actually got a SQLite database, not an SPA-fallback
+ // index.html served for a missing file. SQLite databases start
+ // with the 16-byte magic string "SQLite format 3\0".
+ const magic = new TextDecoder().decode(buffer.subarray(0, 15));
+ if (magic !== "SQLite format 3") {
+ throw new Error(
+ `Test fixture at /test-fixtures/document.db is not a SQLite database ` +
+ `(got ${buffer.byteLength} bytes starting with "${magic}"). ` +
+ `The file is likely missing and the SPA fallback is returning index.html.`
+ );
+ }
+ await writeOpfsFile(opfsDbName, buffer);
+ } else {
+ console.log("[Worker] Integration test mode: reusing existing OPFS DB from earlier in this test");
}
- sqlProvider!.loadFromBuffer(buffer);
+ sqlProvider!.loadFromOpfs(`/${opfsDbName}`);
} else if (sqlProvider!.isOpfsAvailable()) {
// Try to use OPFS for persistent storage
console.log("[Worker] OPFS available, loading persistent database...");