Skip to content

Build your personal knowledge base with Trilium Notes

core/backup import: enable backup imports in standalone mode

Adorian Doran73a61ba1cc14
diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsx
index 24fce7b3ba..aab1fa416a 100644
--- a/apps/client/src/setup.tsx
+++ b/apps/client/src/setup.tsx
@@ -145,9 +145,6 @@ function SetupOptions({ setState }: { setState: (state: State) => void }) {
icon="bx bx-archive-in"
title={t("setup.restore-from-backup")}
description={t("setup.restore-from-backup-description")}
- // The backup has to be unwrapped and opened by a real database engine, which the
- // standalone build does not have: its database lives in the browser's own storage.
- disabled={glob.isStandalone}
onClick={() => setState("restoreFromBackup")}
/>
diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsx
index 4ee8b9529f..d57100826f 100644
--- a/apps/client/src/setup_restore.tsx
+++ b/apps/client/src/setup_restore.tsx
@@ -56,6 +56,13 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
const [ wrongPassphrase, setWrongPassphrase ] = useState(false);
/** Stops the upload in flight, for the one thing that can interrupt it: the user going back. */
const uploadCancellation = useRef<AbortController | null>(null);
+ /**
+ * The file a standalone restore is working from, kept so a wrong passphrase can be answered
+ * without picking it again. It is a reference to bytes the browser already has, not a copy.
+ */
+ const localBackup = useRef<File | null>(null);
+ /** Where a standalone restore has got to, which it reports rather than being polled for. */
+ const [ localProgress, setLocalProgress ] = useState<RestoreStatus | null>(null);
/**
* Fetched here rather than by the step that lists them, which is mounted afresh every time it is
* returned to: asking again would show "looking for backups" for the length of each slide back.
@@ -96,7 +103,38 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
}
}, [ raiseError ]);
+ /**
+ * Restores a picked file through the standalone build's own way to the worker that owns the
+ * database, which is already on this device: there is nothing to upload, and the request path
+ * would serialise the whole database and give up on it besides.
+ */
+ async function restoreLocally(file: File, passphrase?: string) {
+ setSelection({ source: "pending", fileName: file.name });
+ localBackup.current = file;
+ setStep("restoring");
+
+ const result = await window.standaloneApi?.restore.importBackup({
+ backup: file,
+ passphrase,
+ onProgress: ({ stage, fraction }) => setLocalProgress({ stage, fraction })
+ });
+
+ if (result?.status === "restored") {
+ onRestored();
+ } else if (result?.status === "needs-passphrase") {
+ setStep("passphrase");
+ } else {
+ setStep("picking");
+ raiseError(headlineFor(result?.reason), result?.message);
+ }
+ }
+
async function uploadAndRestore(file: File) {
+ if (window.standaloneApi) {
+ await restoreLocally(file);
+ return;
+ }
+
const cancellation = new AbortController();
uploadCancellation.current = cancellation;
@@ -183,12 +221,20 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
wrong={wrongPassphrase}
onSubmit={(passphrase) => {
setWrongPassphrase(false);
- void restore(selection, passphrase);
+
+ // Standalone still has the file it was given, so answering the
+ // prompt starts again from it rather than from a server's copy.
+ const backup = localBackup.current;
+ void (backup ? restoreLocally(backup, passphrase) : restore(selection, passphrase));
}}
/>
)}
{shown === "restoring" && (
- <RestoreProgress onRestored={onRestored} onFailed={onRestoreFailed} />
+ <RestoreProgress
+ reported={localProgress}
+ onRestored={onRestored}
+ onFailed={onRestoreFailed}
+ />
)}
</>
)}
@@ -450,11 +496,23 @@ interface RestoreStatus {
reason?: string;
}
-function RestoreProgress({ onRestored, onFailed }: { onRestored: () => void; onFailed: (failure: { error?: string; reason?: string }) => void }) {
+function RestoreProgress({ reported, onRestored, onFailed }: {
+ /** Where the restore has got to, where it says so itself; polled when it does not. */
+ reported?: RestoreStatus | null;
+ onRestored: () => void;
+ onFailed: (failure: { error?: string; reason?: string }) => void;
+}) {
const [ stage, setStage ] = useState<string>("staging");
const [ fraction, setFraction ] = useState<number | null>(null);
+ const polled = !reported;
useEffect(() => {
+ // A restore that reports itself is already telling this component everything it knows, and
+ // there is nothing on the other end to ask besides.
+ if (!polled) {
+ return;
+ }
+
const interval = setInterval(async () => {
let restore;
try {
@@ -484,21 +542,24 @@ function RestoreProgress({ onRestored, onFailed }: { onRestored: () => void; onF
}, 1000);
return () => clearInterval(interval);
- }, [ onRestored, onFailed ]);
+ }, [ polled, onRestored, onFailed ]);
+
+ const shownStage = reported?.stage ?? stage;
+ const shownFraction = (reported ? reported.fraction : fraction) ?? null;
// Only what is happening now, rather than the four steps as a list. Preparing the backup is the
// one that takes any time; the rest go by too quickly to be read, so a list of them mostly shows
// the user three things they will never see happen.
return (
<div class="restore-current-step">
- <div class="restore-step-name">{t(`setup.restore-stage-${stage}`)}</div>
+ <div class="restore-step-name">{t(`setup.restore-stage-${shownStage}`)}</div>
{/* Only where the step can say how far it has got. The ones that cannot show nothing,
rather than an empty bar that never moves. */}
- {fraction !== null && (
+ {shownFraction !== null && (
<div class="restore-stage-progress">
- <progress value={fraction} max={1} />
- <span>{Math.floor(fraction * 100)}%</span>
+ <progress value={shownFraction} max={1} />
+ <span>{Math.floor(shownFraction * 100)}%</span>
</div>
)}
diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.ts
index 971443a2ec..f2145f60cc 100644
--- a/apps/client/src/types.d.ts
+++ b/apps/client/src/types.d.ts
@@ -1,4 +1,4 @@
-import { BootstrapDefinition, ElectronApi, ElectronContextMenuParams } from "@triliumnext/commons";
+import { BootstrapDefinition, ElectronApi, ElectronContextMenuParams, StandaloneApi } from "@triliumnext/commons";
import appContext, { AppContext } from "./components/app_context";
import type FNote from "./entities/fnote";
@@ -58,6 +58,8 @@ declare global {
};
electronApi?: ElectronApi;
+ /** Present only in the standalone build, where the stack runs in this browser. */
+ standaloneApi?: StandaloneApi;
}
diff --git a/apps/standalone/package.json b/apps/standalone/package.json
index d62e61a2bc..3f1d023921 100644
--- a/apps/standalone/package.json
+++ b/apps/standalone/package.json
@@ -19,6 +19,7 @@
"@popperjs/core": "2.11.8",
"@preact/signals": "2.10.1",
"@sqlite.org/sqlite-wasm": "3.51.1-build2",
+ "@triliumnext/backup-container": "workspace:*",
"@triliumnext/ckeditor5": "workspace:*",
"@triliumnext/codemirror": "workspace:*",
"@triliumnext/commons": "workspace:*",
diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.ts
new file mode 100644
index 0000000000..d76d2cff26
--- /dev/null
+++ b/apps/standalone/src/lightweight/database_restore.ts
@@ -0,0 +1,292 @@
+import {
+ FIXED_HEADER_BYTES,
+ isBackupContainerError,
+ peekBackupContainer,
+ type ProgressCallback,
+ readBackupContainer
+} from "@triliumnext/backup-container/web";
+import {
+ type CandidateDatabase,
+ type DatabaseValidation,
+ looksLikeSqlite,
+ validateDatabase
+} from "@triliumnext/core";
+import type { SAHPoolUtil } from "@sqlite.org/sqlite-wasm";
+
+/**
+ * Puts a backup in place of this instance's database, in the browser.
+ *
+ * The server exchanges two files on a disk. Here the databases live as entries in the SAH pool,
+ * which has no rename, so a restore is done by writing the new database in beside the old one and
+ * then changing which name the next start opens. That single small write is the whole of the swap:
+ * before it the old database is live, after it the new one is, and there is no moment in between
+ * where neither is.
+ *
+ * Nothing is ever held whole. The backup arrives as a stream and is fed to `importDb` chunk by
+ * chunk, and the checks read the imported database page by page through the VFS, so a restore costs
+ * the size of the backup on disk and almost nothing in memory. That matters more here than on a
+ * server: this database engine is compiled to WebAssembly, whose address space is a fraction of what
+ * a native process has.
+ *
+ * @module
+ */
+
+/** Where the pointer to the live database is kept, in the origin's private filesystem. */
+const POINTER_FILE = "trilium-current-database";
+
+/** The database opened when nothing has ever been restored. */
+export const DEFAULT_DATABASE_NAME = "/trilium.db";
+
+/** Where a backup is written while it is being checked, before it is anything to anyone. */
+const CANDIDATE_NAME = "/trilium.candidate.db";
+
+/** What the restore is doing, in the order it does it. Mirrors the server's own steps. */
+export type RestoreStage = "staging" | "validating" | "swapping" | "done" | "failed";
+
+export interface RestoreProgress {
+ stage: RestoreStage;
+ /** How far through the current step, from 0 to 1, for the step that can say. */
+ fraction?: number;
+ error?: string;
+ reason?: string;
+}
+
+/** The database the restore acts on, reduced to what it needs and no more. */
+export interface RestoreTarget {
+ pool: SAHPoolUtil;
+ /** Closes whatever is open. */
+ close(): void;
+ /** Opens the named pool entry as the live database. */
+ open(dbName: string): void;
+}
+
+/**
+ * Reads which pool entry holds the live database.
+ *
+ * Falls back to the original name, which is what every instance that has never restored anything is
+ * still using, and what a browser that has lost the pointer should reach for.
+ */
+export async function readCurrentDatabaseName(): Promise<string> {
+ try {
+ const root = await navigator.storage.getDirectory();
+ const handle = await root.getFileHandle(POINTER_FILE);
+ const name = (await (await handle.getFile()).text()).trim();
+
+ return name || DEFAULT_DATABASE_NAME;
+ } catch {
+ return DEFAULT_DATABASE_NAME;
+ }
+}
+
+/**
+ * Restores `backup` over the live database, reporting each step through `report`.
+ *
+ * @param backup the file the user chose, read where it lies rather than copied anywhere first.
+ * @throws Error carrying a `reason` the setup screen maps to something the user can act on.
+ */
+export async function restoreDatabase(
+ target: RestoreTarget,
+ backup: Blob,
+ options: { passphrase?: string; report?: (progress: RestoreProgress) => void } = {}
+): Promise<void> {
+ const report = options.report ?? (() => {});
+
+ try {
+ report({ stage: "staging" });
+ await stageCandidate(target.pool, backup, options.passphrase, (fraction) =>
+ report({ stage: "staging", fraction }));
+
+ report({ stage: "validating" });
+ const validation = validate(target.pool);
+ if (!validation.valid) {
+ throw new RestoreFailure(validation.rejection, validation.message);
+ }
+
+ report({ stage: "swapping" });
+ await swapIn(target);
+
+ report({ stage: "done" });
+ } catch (e) {
+ const failure = asFailure(e);
+ // The candidate is no use to anyone now, and the pool's slots are finite.
+ await removeQuietly(target.pool, CANDIDATE_NAME);
+ report({ stage: "failed", error: failure.message, reason: failure.reason });
+
+ throw failure;
+ }
+}
+
+/** A failure with a reason attached, so the setup screen can tell the cases apart. */
+export class RestoreFailure extends Error {
+ constructor(readonly reason: string, message: string) {
+ super(message);
+ this.name = "RestoreFailure";
+ }
+}
+
+/**
+ * Writes the backup into the pool as the candidate, unwrapping it on the way where it is a
+ * container.
+ *
+ * The unwrap writes into one end of a pipe while the import pulls from the other, so the database
+ * passes through in chunks and the pipe's own backpressure keeps the two in step. Neither end ever
+ * holds more than a chunk.
+ */
+async function stageCandidate(
+ pool: SAHPoolUtil,
+ backup: Blob,
+ passphrase: string | undefined,
+ onProgress: ProgressCallback
+): Promise<void> {
+ await makeRoomFor(pool);
+ await removeQuietly(pool, CANDIDATE_NAME);
+
+ const format = await readBackupFormat(backup);
+ if (!format) {
+ throw new RestoreFailure("not-a-database", "The backup could not be read.");
+ }
+
+ if (!format.container) {
+ await pool.importDb(CANDIDATE_NAME, pullFrom(backup.stream()));
+ onProgress(1);
+ return;
+ }
+
+ // Asked before the file is read rather than after: an encrypted container without a passphrase
+ // fails the same way either way, but only one of them takes minutes to get there.
+ if (format.encrypted && !passphrase) {
+ throw new RestoreFailure("passphrase-required", "The backup is encrypted.");
+ }
+
+ const relay = new TransformStream<Uint8Array, Uint8Array>();
+ const unwrapped = readBackupContainer(backup.stream(), relay.writable, { passphrase, onProgress });
+ const imported = pool.importDb(CANDIDATE_NAME, pullFrom(relay.readable));
+
+ // Awaited together: either failing has to stop the other, which is what a rejected pipe does.
+ await Promise.all([ unwrapped, imported ]);
+}
+
+/** Opens the candidate and puts it through the checks every platform shares. */
+function validate(pool: SAHPoolUtil): DatabaseValidation {
+ const db = new pool.OpfsSAHPoolDb(CANDIDATE_NAME);
+
+ try {
+ return validateDatabase(candidateOf(db));
+ } catch (e) {
+ // What a database too damaged to query throws is this driver's business, not the checks'.
+ return {
+ valid: false,
+ rejection: "damaged-database",
+ message: `The database could not be read: ${messageOf(e)}`
+ };
+ } finally {
+ db.close();
+ }
+}
+
+/** The three questions the checks ask, answered by a database opened from the pool. */
+function candidateOf(db: InstanceType<SAHPoolUtil["OpfsSAHPoolDb"]>): CandidateDatabase {
+ return {
+ integrityCheck: () => String(db.selectValue("PRAGMA quick_check")),
+ tableNames: () => db.selectValues("SELECT name FROM sqlite_master WHERE type = 'table'") as string[],
+ option: (name) => db.selectValue("SELECT value FROM options WHERE name = ?", [ name ]) as string | undefined
+ };
+}
+
+/**
+ * Makes the candidate the live database.
+ *
+ * The pointer is written last, and is the only thing that decides which database is opened: until it
+ * changes, an interrupted restore leaves the old one live with an unused entry beside it, which the
+ * next attempt overwrites.
+ */
+async function swapIn(target: RestoreTarget): Promise<void> {
+ const previous = await readCurrentDatabaseName();
+
+ target.close();
+ await writeCurrentDatabaseName(CANDIDATE_NAME);
+
+ try {
+ target.open(CANDIDATE_NAME);
+ } catch (e) {
+ // Put back what was live, so a candidate that will not open costs nothing.
+ await writeCurrentDatabaseName(previous);
+ target.open(previous);
+
+ throw new RestoreFailure("swap-failed", messageOf(e));
+ }
+
+ // Only once the restored database is open: until then the old one is what a restart needs.
+ if (previous !== CANDIDATE_NAME) {
+ await removeQuietly(target.pool, previous);
+ }
+}
+
+async function writeCurrentDatabaseName(dbName: string): Promise<void> {
+ const root = await navigator.storage.getDirectory();
+ const handle = await root.getFileHandle(POINTER_FILE, { create: true });
+ const writable = await handle.createWritable();
+
+ try {
+ await writable.write(dbName);
+ } finally {
+ await writable.close();
+ }
+}
+
+/**
+ * Identifies a backup from its first bytes: a container states what it is in the clear, and anything
+ * else has to be a database already.
+ */
+async function readBackupFormat(backup: Blob): Promise<{ container: boolean; encrypted: boolean } | null> {
+ const head = new Uint8Array(await backup.slice(0, FIXED_HEADER_BYTES).arrayBuffer());
+ const container = peekBackupContainer(head);
+
+ if (container) {
+ return { container: true, encrypted: container.encrypted };
+ }
+
+ return looksLikeSqlite(head) ? { container: false, encrypted: false } : null;
+}
+
+/** Turns a stream into the pull `importDb` asks for: a chunk each call, nothing at the end. */
+function pullFrom(stream: ReadableStream<Uint8Array>): () => Promise<Uint8Array | undefined> {
+ const reader = stream.getReader();
+
+ return async () => {
+ const { done, value } = await reader.read();
+
+ return done ? undefined : value;
+ };
+}
+
+/** Adds a slot if every one the pool has is spoken for, since a restore needs one for the candidate. */
+async function makeRoomFor(pool: SAHPoolUtil): Promise<void> {
+ if (pool.getFileCount() >= pool.getCapacity()) {
+ await pool.addCapacity(1);
+ }
+}
+
+/** Removes a pool entry, if it is there at all. Never the reason a restore fails. */
+async function removeQuietly(pool: SAHPoolUtil, dbName: string): Promise<void> {
+ try {
+ pool.unlink(dbName);
+ } catch {
+ // A leftover entry costs a slot, which is not worth losing the answer over.
+ }
+}
+
+function asFailure(e: unknown): RestoreFailure {
+ if (e instanceof RestoreFailure) {
+ return e;
+ }
+ if (isBackupContainerError(e)) {
+ return new RestoreFailure(e.reason, e.message);
+ }
+
+ return new RestoreFailure("swap-failed", messageOf(e));
+}
+
+function messageOf(e: unknown): string {
+ return e instanceof Error ? e.message : String(e);
+}
diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.ts
index 1c039b1a68..56cde72555 100644
--- a/apps/standalone/src/local-bridge.ts
+++ b/apps/standalone/src/local-bridge.ts
@@ -1,9 +1,46 @@
+import type { StandaloneRestoreProgress, StandaloneRestoreResult } from "@triliumnext/commons";
+
import LocalServerWorker from "./local-server-worker?worker";
let localWorker: Worker | null = null;
const pending = new Map();
+/** Restores in flight, by id, each with the progress callback that stays on this side. */
+const restores = new Map<string, {
+ resolve: (result: StandaloneRestoreResult) => void;
+ reject: (reason: unknown) => void;
+ onProgress?: (progress: StandaloneRestoreProgress) => void;
+}>();
const LOCAL_API_PREFIXES = ["/bootstrap", "/api/", "/sync/", "/search/"];
+/**
+ * Restores the database from a backup, on the worker that owns it.
+ *
+ * The file goes across as a `File`, which structured cloning passes by reference, so nothing is
+ * copied and nothing is read into memory here. It deliberately avoids the request path: that
+ * serialises bodies whole and gives up after thirty seconds, neither of which a database survives.
+ *
+ * Progress is relayed from the worker to `onProgress`, which stays on this side of the boundary.
+ */
+export function restoreBackup(opts: {
+ backup: File;
+ passphrase?: string;
+ onProgress?: (progress: StandaloneRestoreProgress) => void;
+}): Promise<StandaloneRestoreResult> {
+ startLocalServerWorker();
+
+ const id = Math.random().toString(36).slice(2);
+
+ return new Promise((resolve, reject) => {
+ restores.set(id, { resolve, reject, onProgress: opts.onProgress });
+ localWorker!.postMessage({
+ type: "RESTORE_BACKUP",
+ id,
+ backup: opts.backup,
+ passphrase: opts.passphrase
+ });
+ });
+}
+
export function isLocalApiRequest(url: URL): boolean {
return LOCAL_API_PREFIXES.some(p => url.pathname.startsWith(p));
}
@@ -99,6 +136,18 @@ export function startLocalServerWorker() {
localWorker.onmessage = (event) => {
const msg = event.data;
+ // Restore progress and outcome, which travel on their own channel rather than as a response
+ // to a request: the backup that started them never went through one.
+ if (msg?.type === "RESTORE_PROGRESS") {
+ restores.get(msg.id)?.onProgress?.(msg.progress);
+ return;
+ }
+ if (msg?.type === "RESTORE_RESULT") {
+ restores.get(msg.id)?.resolve(msg.result);
+ restores.delete(msg.id);
+ return;
+ }
+
// Handle fatal platform crashes (shown as a dialog to the user)
if (msg?.type === "FATAL_ERROR") {
console.error("[LocalBridge] Fatal error:", msg.message);
diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.ts
index 6f4dc8f23e..24538852b6 100644
--- a/apps/standalone/src/local-server-worker.ts
+++ b/apps/standalone/src/local-server-worker.ts
@@ -47,6 +47,9 @@ console.log("[Worker] Error handlers installed, loading modules...");
// TYPE-ONLY IMPORTS (erased at runtime, safe as static imports)
// =============================================================================
import type { BrowserRouter } from './lightweight/browser_router';
+import type { StandaloneRestoreProgress, StandaloneRestoreResult } from "@triliumnext/commons";
+
+import { readCurrentDatabaseName, RestoreFailure, restoreDatabase } from './lightweight/database_restore';
// Build-time constant injected by Vite (see `define` in vite.config.mts).
declare const __TRILIUM_INTEGRATION_TEST__: string;
@@ -222,7 +225,10 @@ async function initialize(): Promise<void> {
// __TRILIUM_INTEGRATION_TEST__ Vite define (derived from the
// TRILIUM_INTEGRATION_TEST env var when the bundle was built).
const integrationTestMode = __TRILIUM_INTEGRATION_TEST__;
- const dbName = "/trilium.db";
+ // Which pool entry holds the database is a stored answer rather than a constant: a
+ // restore cannot rename an entry, so it writes the new database in beside the old one
+ // and changes this. Unrestored instances read the name they have always used.
+ const dbName = await readCurrentDatabaseName();
if (integrationTestMode === "memory") {
// Use OPFS for the DB in integration test mode so option changes
@@ -358,6 +364,46 @@ async function dispatch(request: LocalRequest) {
return appRouter.dispatch(request.method, request.url, request.body, request.headers);
}
+/**
+ * Restores the database from a backup handed straight to this worker.
+ *
+ * Answers rather than throws: the caller is a page waiting on a message, and every way this can end
+ * is something the setup screen has to say to the user. A missing passphrase is not a failure but a
+ * question, so it is reported as one and the same file can be offered again with an answer.
+ */
+async function handleRestoreBackup(id: string, backup: File, passphrase?: string): Promise<void> {
+ const report = (progress: StandaloneRestoreProgress) =>
+ (self as unknown as Worker).postMessage({ type: "RESTORE_PROGRESS", id, progress });
+ const answer = (result: StandaloneRestoreResult) =>
+ (self as unknown as Worker).postMessage({ type: "RESTORE_RESULT", id, result });
+
+ try {
+ await restoreDatabase(
+ {
+ pool: sqlProvider!.sahPool!,
+ close: () => sqlProvider!.close(),
+ open: (dbName) => sqlProvider!.loadFromSahPool(dbName)
+ },
+ backup,
+ { passphrase, report: ({ stage, fraction }) => report({ stage, fraction }) }
+ );
+
+ // What the "create new document" path announces for the same reason: everything that waits
+ // on a database being there starts from here.
+ await coreModule!.sql_init.initDbConnection();
+ coreModule!.events.emit(coreModule!.events.DB_INITIALIZED);
+
+ answer({ status: "restored" });
+ } catch (e) {
+ const reason = e instanceof RestoreFailure ? e.reason : "swap-failed";
+ const message = e instanceof Error ? e.message : String(e);
+
+ answer(reason === "passphrase-required"
+ ? { status: "needs-passphrase" }
+ : { status: "error", reason, message });
+ }
+}
+
// Wait for the INIT message before initializing so that queryString
// (which may contain ?integrationTest=memory for e2e) is available.
let initReceived = false;
@@ -386,6 +432,11 @@ self.onmessage = async (event) => {
return;
}
+ if (msg.type === "RESTORE_BACKUP") {
+ await handleRestoreBackup(msg.id, msg.backup, msg.passphrase);
+ return;
+ }
+
if (msg.type !== "LOCAL_REQUEST") return;
const { id, request } = msg;
diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.ts
index 3c6c3c0253..892624921a 100644
--- a/apps/standalone/src/main.ts
+++ b/apps/standalone/src/main.ts
@@ -1,5 +1,5 @@
import { installIosInterceptors } from "./ios-interceptors.js";
-import { attachServiceWorkerBridge, registerNativeHttpHandler, startLocalServerWorker } from "./local-bridge.js";
+import { attachServiceWorkerBridge, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";
async function waitForServiceWorkerControl(): Promise<void> {
if (!("serviceWorker" in navigator) || !navigator.serviceWorker) {
@@ -44,6 +44,10 @@ async function bootstrap() {
/* fixes https://github.com/webpack/webpack/issues/10035 */
window.global = globalThis;
+ // The client's way to the worker for the few things that carry a file, which the request path
+ // would serialise whole and time out on. The desktop's `window.electronApi` is the same idea.
+ window.standaloneApi = { restore: { importBackup: restoreBackup } };
+
try {
// When running inside a Capacitor WebView, register the native HTTP
// handler so outbound sync requests bypass CORS and cookie restrictions.
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts
index 42e5976739..98e0a3ac55 100644
--- a/packages/commons/src/index.ts
+++ b/packages/commons/src/index.ts
@@ -28,6 +28,7 @@ export { default as BUILTIN_ATTRIBUTES } from "./lib/builtin_attributes.js";
// barrel is imported by virtually every client module. Import them via their subpath instead,
// e.g. "@triliumnext/commons/src/lib/spreadsheet/render_to_html".
export * from "./lib/electron_api_interface.js";
+export * from "./lib/standalone_api_interface.js";
export * from "./lib/favicon_contrast.js";
export * from "./lib/link_embed.js";
export * from "./lib/llm_api.js";
diff --git a/packages/commons/src/lib/standalone_api_interface.ts b/packages/commons/src/lib/standalone_api_interface.ts
new file mode 100644
index 0000000000..f25c77ea3f
--- /dev/null
+++ b/packages/commons/src/lib/standalone_api_interface.ts
@@ -0,0 +1,48 @@
+/**
+ * What the standalone build exposes to the client as `window.standaloneApi`.
+ *
+ * Standalone runs the whole stack in the browser: the database lives in a worker's private
+ * filesystem, and the client talks to it over an intercepted `fetch`. That path serialises every
+ * request body twice on its way through, and gives up after thirty seconds, which is fine for the
+ * JSON everything else exchanges and impossible for a database.
+ *
+ * So the few things that carry a file get their own way through, the same way the desktop's
+ * `window.electronApi` does. A `File` handed across is a reference to bytes the browser already has;
+ * nothing is copied, nothing is uploaded, and the worker reads it as a stream.
+ */
+
+/** How far a restore has got, reported as it goes. */
+export interface StandaloneRestoreProgress {
+ /** Which step is running: preparing the backup, checking it, or putting it in place. */
+ stage: "staging" | "validating" | "swapping" | "done" | "failed";
+ /** How far through that step, from 0 to 1, for the step that can say. */
+ fraction?: number;
+}
+
+/** How a restore ended. */
+export interface StandaloneRestoreResult {
+ status: "restored" | "needs-passphrase" | "error";
+ /** Machine-readable cause when `status` is `error`, which the screen turns into a sentence. */
+ reason?: string;
+ /** The technical detail behind that cause. */
+ message?: string;
+}
+
+export interface StandaloneRestoreApi {
+ /**
+ * Restores the database from a backup the user picked, reading it where it lies.
+ *
+ * Answers `needs-passphrase` for an encrypted backup given none, which is an invitation to ask
+ * for one and call again with the same file rather than a failure.
+ */
+ importBackup(opts: {
+ backup: File;
+ passphrase?: string;
+ onProgress?: (progress: StandaloneRestoreProgress) => void;
+ }): Promise<StandaloneRestoreResult>;
+}
+
+/** The complete surface the standalone build exposes to the client. */
+export interface StandaloneApi {
+ restore: StandaloneRestoreApi;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b42aa1b34e..6b5818a04b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -825,6 +825,9 @@ importers:
'@sqlite.org/sqlite-wasm':
specifier: 3.51.1-build2
version: 3.51.1-build2
+ '@triliumnext/backup-container':
+ specifier: workspace:*
+ version: link:../../packages/trilium-backup-container
'@triliumnext/ckeditor5':
specifier: workspace:*
version: link:../../packages/ckeditor5