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(mobile): answer iOS local API requests through a native scheme-handler bridge
Elian Doran2f03eed08c00
diff --git a/.claude/skills/developing-capacitor-mobile/SKILL.md b/.claude/skills/developing-capacitor-mobile/SKILL.mdindex f3a9c11fb2..40f5d0c8db 100644--- a/.claude/skills/developing-capacitor-mobile/SKILL.md+++ b/.claude/skills/developing-capacitor-mobile/SKILL.md@@ -1,6 +1,6 @@---name: developing-capacitor-mobile-description: Use when working on the Trilium mobile app (`apps/mobile`, Capacitor for Android/iOS) or on the standalone code paths that only run inside it — request routing on `capacitor://` vs `https://localhost`, the iOS fetch/XHR/image/stylesheet interceptors, the Android request bridge (`TriliumRequestBridge`, which replaces the service worker there), the Android native streaming HTTP proxy (`TriliumWebViewClient`), the `NativeHttpHandler` sync transport, downloads and exports (the WebView saves none itself — `capacitor_download.ts` writes them and opens the share sheet), `MainActivity`/`ViewController` WebView tweaks (edge-to-edge, keyboard), `isMobileApp()` gating in the client, adding a Capacitor plugin, or the mobile CI/nightly builds. Also load it when reviewing a diff that touches these files, so working iOS-only code is not flagged as dead.+description: Use when working on the Trilium mobile app (`apps/mobile`, Capacitor for Android/iOS) or on the standalone code paths that only run inside it — request routing on `capacitor://` vs `https://localhost`, the native request bridges on both platforms (`TriliumRequestBridge` in Java and Swift, `native-request-bridge.ts`, which replace the service worker there; the iOS one re-types Capacitor's `capacitor://` scheme handler), the Android native streaming HTTP proxy (`TriliumWebViewClient`), the `NativeHttpHandler` sync transport, downloads and exports (the WebView saves none itself — `capacitor_download.ts` writes them and opens the share sheet), `MainActivity`/`ViewController` WebView tweaks (edge-to-edge, keyboard), `isMobileApp()` gating in the client, adding a Capacitor plugin, or the mobile CI/nightly builds. Also load it when reviewing a diff that touches these files, so working iOS-only code is not flagged as dead.---# Developing the Capacitor mobile app@@ -19,10 +19,10 @@ apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/InterceptedResponse.java # Android-free form of WebResourceResponse, returned by bothTriliumWebViewClient.java # routes requests to TriliumRequestBridge and NativeHttpProxy, builds the WebResourceResponseTriliumFileSink.java # binary file-write channel (WebMessageListener + ArrayBuffer, Android only)-apps/mobile/ios/App/App/ViewController.swift # keyboard handling: pins outer scroll, drives --tn-keyboard-gap-apps/standalone/src/main.ts # boot: registers native HTTP handler if `Capacitor` in window; iOS interceptors or Android request bridge-apps/standalone/src/android-request-bridge.ts # page side of TriliumRequestBridge: localFetch() → head + chunk frames-apps/standalone/src/ios-interceptors.ts # fetch / XHR / <img> / stylesheet interceptors, iOS only+apps/mobile/ios/App/App/ViewController.swift # re-types the capacitor:// scheme handler; keyboard handling, --tn-keyboard-gap+apps/mobile/ios/App/App/TriliumRequestBridge.swift # TriliumAssetHandler + TriliumRequestBridge: local API requests answered by the page+apps/standalone/src/main.ts # boot: native HTTP handler and native request bridge if `Capacitor` in window, else the SW+apps/standalone/src/native-request-bridge.ts # page side of both TriliumRequestBridges: localFetch() → head + chunksapps/standalone/src/services/capacitor_http_handler.ts # NativeHttpHandler: Android proxy probe + CapacitorHttp fallbackapps/standalone/src/services/capacitor_download.ts # saveUrlToDevice(): fetch → Filesystem cache → share sheetapps/standalone/src/local-bridge.ts # LOCAL_API_PREFIXES, localFetch(), registerNativeHttpHandler()@@ -37,21 +37,20 @@ The client's `/api`, `/sync`, `/bootstrap`, `/search` requests (`LOCAL_API_PREFI**Most of them never leave the page.** The shell is a single WebView, so its one tab always wins the database lock, and a tab that owns the worker publishes `localFetch` on `window.standaloneApi`; the client's `ajax()` and `setupGlob()`'s `/bootstrap` call it directly rather than issuing a request (see the standalone skill, "Request flow" step 3). That covers everything routed through `apps/client/src/services/server.ts`, on both platforms alike.-What still leaves the page — engine-initiated loads (`<img src="api/images/…">`, `@font-face`, themes), `upload()`/`chunked_upload.ts`, the LLM stream — is where the platforms diverge, because their WebViews resolve `*Scheme: "https"` differently:+What still leaves the page — engine-initiated loads (`<img src="api/images/…">`, `@font-face`, themes, media, iframes such as the PDF viewer), uploads, the LLM stream — goes to a **native request bridge** on both platforms; neither registers a service worker. The native side sees every request the engine issues, whichever subsystem issued it, and hands local API paths to the page: it calls `window.__triliumNativeRequest()`, `native-request-bridge.ts` answers from `localFetch()`, and the reply comes back as JSON strings: a `head`, the body in chunks, then `end`/`error`. Where the platforms differ is how the request is caught and how the body travels:-- **Android** — the app runs at `https://localhost` and registers **no service worker**. `TriliumWebViewClient.shouldInterceptRequest` sees every request the engine issues, whichever subsystem issued it, and hands local API paths to **`TriliumRequestBridge`**. That bridge calls `window.__triliumNativeRequest()`, `android-request-bridge.ts` answers from `localFetch()`, and the reply comes back over the injected `window.triliumRequestBridge` WebMessageListener: a JSON `head`, then the body as ArrayBuffer frames (4-byte request id + bytes; base64 `chunk` messages on a WebView without ArrayBuffer messages), then `end`/`error`. The IO thread blocks until the head arrives (270 s cap, as in `sw.ts`), then the body streams through a queue-backed `InputStream`. `main.ts` takes this path when `triliumRequestBridge` is on `window`; a WebView without `WEB_MESSAGE_LISTENER` never gets it, so it falls back to the service worker.-- **iOS** — the app runs at **`capacitor://localhost`**, and WebKit refuses to register a service worker on a non-HTTP(S) origin. `main.ts` therefore installs **in-page interceptors** (`installIosInterceptors()`, gated on `location.protocol === "capacitor:"`), one per way a request can leave the page: `window.fetch`, `XMLHttpRequest` (jQuery `$.ajax` never touches fetch), `<img src="api/images/…">` (the image loader issues its own requests) and CSS-initiated loads (`@font-face url()` in injected styles, custom themes via `<link href="api/…">`). Each rewrites a local-API request into `localFetch()`.+- **Android** (`https://localhost`) — `TriliumWebViewClient.shouldInterceptRequest` hands local paths to **`TriliumRequestBridge.java`** (logic in `LocalRequestBroker`). Replies come over the injected `window.triliumRequestBridge` WebMessageListener, the body as ArrayBuffer frames (4-byte request id + bytes; base64 `chunk` messages on a WebView without ArrayBuffer messages). The IO thread blocks until the head arrives (270 s cap, as in `sw.ts`), then the body streams through a queue-backed `InputStream`. A WebView without `WEB_MESSAGE_LISTENER` never gets the object, so `installNativeRequestBridge()` returns false and the page falls back to the service worker.+- **iOS** (`capacitor://localhost`, where WebKit refuses a service worker) — `ViewController.webView(with:configuration:)` re-types Capacitor's registered `WebViewAssetHandler` to **`TriliumAssetHandler`** with `object_setClass` (WebKit raises on registering a second handler for a scheme, and Capacitor's `loadView()` is not overridable), which hands local paths to **`TriliumRequestBridge.swift`**. Replies come over the `window.webkit.messageHandlers.triliumRequestBridge` script message handler, the body always in base64 chunks (script messages cannot carry ArrayBuffers). Nothing blocks: the `WKURLSchemeTask` is completed by `didReceive(response)`, `didReceive(data)` per chunk and `didFinish()`. A main-document request through the handler counts as a page start and fails whatever the previous page left unanswered.Consequences that keep tripping people up:- **`iosScheme: "https"` is a no-op — do not re-add it.** Capacitor rejects it: `CAPInstanceDescriptor.normalize()` checks `WKWebView.handlesURLScheme(scheme) == false`, and WKWebView reserves `http`/`https`, so the scheme resets to `capacitor`. The config line only implies an https origin that never exists on iOS.-- **Do not delete the iOS interceptor path as "dead code"**, and do not gate anything on "there is always a service worker". A reviewer assuming `iosScheme: https` ⇒ https origin will wrongly flag it.-- A **new way for the page to issue a request** (a new element type loading `api/…`, a `new Worker` fetching, `EventSource`, `sendBeacon`) needs a fourth/fifth interceptor in `ios-interceptors.ts`, or it will silently 404 on iOS while working everywhere else. Test it in `ios-interceptors.spec.ts`.-- **The Android bridge answers GET and HEAD only.** `shouldInterceptRequest` exposes no request body, so any other method gets a 405 with `x-trilium-bridge-error`. A request with a body has to go through `standaloneApi.localFetch` (as `server.ts`'s `ajax()` does); a raw `fetch`/`$.ajax` POST to `api/` fails on Android.-- **`WebResourceResponse` rejects 3xx statuses**, so `android-request-bridge.ts` turns a redirect (the share pages issue them) into a 200 page with a `<meta http-equiv="refresh">`. The Java prefix list in `TriliumRequestBridge.handles()` must match `isLocalApiRequest()` in `local-bridge.ts`, including the `/share` rule.-- **A service worker registered by an older build still controls the page.** Its fetches never reach `shouldInterceptRequest`, and with no `attachServiceWorkerBridge()` nothing answers them. Clearing the app's data or reinstalling removes it.+- **`TriliumAssetHandler` must not declare stored properties.** The instance it takes over was allocated as a `WebViewAssetHandler`, so subclass storage would be uninitialized; state lives in `TriliumRequestBridge.shared`. A stopped `WKURLSchemeTask` must never be completed (it raises), which is why `stop` removes the task from the pending map at once.+- **Both bridges answer GET and HEAD only.** Android's `shouldInterceptRequest` exposes no request body, and iOS follows suit (its scheme task could read `httpBody`) so the platforms stay alike; any other method gets a 405 with `x-trilium-bridge-error`. A request with a body has to go through `standaloneApi.localFetch` (as `server.ts`'s `ajax()` does) or, for a multipart upload, `standaloneApi.localUpload` (as `uploadForm()` does for `upload()` and imports); a raw `fetch`/`$.ajax` POST to `api/` fails on both platforms.+- **Neither native response carries a 3xx** (`WebResourceResponse` rejects one, a scheme task cannot redirect), so `native-request-bridge.ts` turns a redirect (the share pages issue them) into a 200 page with a `<meta http-equiv="refresh">`. It also sets `content-length` to the exact body length (except for HEAD), which WebKit's media loader needs.+- **Three prefix lists must agree**: `isLocalApiRequest()` in `local-bridge.ts`, `LocalRequestBroker.isLocalPath()` in Java and `isLocalApiPath()` in Swift, including the `/share` rule.+- **A service worker registered by an older Android build still controls the page.** Its fetches never reach `shouldInterceptRequest`, and with no `attachServiceWorkerBridge()` nothing answers them. Clearing the app's data or reinstalling removes it.- `sw.ts` has a defensive `self.location.protocol === "capacitor:"` guard and must **let `/_trilium_native_http/` requests fall through** to the WebView (see below); keep both when editing its fetch handler.-- Image blob URLs created by the interceptor are revoked (`5332cee3fb`); if you add another `URL.createObjectURL`, revoke it.## Outbound: how the worker syncs with a remote server@@ -68,19 +67,17 @@ A navigation whose response carries `Content-Disposition: attachment` is handed`WebView.setDownloadListener` on Android, and **nothing registers one** — not Capacitor, not`MainActivity`. The response is dropped with no console output and no error, so an export "succeeds"(the task's websocket `taskSucceeded` still fires the toast) while no file ever appears. On iOS the-same `window.location.href` is worse: the interceptors patch `fetch`/XHR/`<img>`/stylesheets, never a-top-level navigation, so the URL reaches Capacitor's scheme handler and navigates the app out of the+same `window.location.href` is worse: it is a top-level navigation, so it takes the app out of theSPA.Registering a native `DownloadListener` does not fix it. The listener receives only a URL, and a-native re-request of `https://localhost/api/…` goes to the real network stack, which the service-worker never sees and where no server exists.+native re-request of `https://localhost/api/…` goes to the real network stack, which+`shouldInterceptRequest` never sees and where no server exists.So the page does the saving: `open.download()` (`apps/client/src/services/open.ts`) routes through`window.standaloneApi.save.saveUrl()` when that exists, which `main.ts` defines only inside the shell.-`capacitor_download.ts` fetches the URL — still routed to the worker by `TriliumRequestBridge` on Android-and the interceptors on iOS — writes it into `Directory.Cache` and hands the file to the system share-sheet.+`capacitor_download.ts` fetches the URL — still routed to the worker by the native request bridge —+writes it into `Directory.Cache` and hands the file to the system share sheet.- **On Android the bytes ride `TriliumFileSink`, not the plugin bridge.** Every plugin call crossesas base64 inside a JSON string that `MessageHandler` re-parses whole with `org.json` — ~13 MB/s no@@ -191,12 +188,11 @@ is happening.Everything JS-side is under the standalone Vitest suite (happy-dom + real sqlite-wasm):```bash-pnpm --filter standalone test ios-interceptors # iOS interceptorspnpm --filter standalone test capacitor_http_handler # Android proxy probe / plugin fallbackpnpm --filter standalone test capacitor_download # chunked base64 write, filename parsing, share sheetpnpm --filter standalone test sw # service-worker routing incl. capacitor:// guard-pnpm --filter standalone test android-request-bridge # Android request bridge: framing, base64 fallback, redirects-pnpm --filter standalone test main # boot wiring (native handler, iOS interceptors, Android bridge instead of the SW)+pnpm --filter standalone test native-request-bridge # both platforms' request bridge: channels, framing, base64, redirects+pnpm --filter standalone test main # boot wiring (native HTTP handler, native request bridge or the SW)```Simulate the platform in a spec by stubbing `location.protocol` / `window.Capacitor` (`getPlatform`, `isNativePlatform`, `Plugins.CapacitorHttp`) — see the existing specs for the fixtures.diff --git a/.claude/skills/developing-standalone/SKILL.md b/.claude/skills/developing-standalone/SKILL.mdindex 49742b3ddb..d0c8333939 100644--- a/.claude/skills/developing-standalone/SKILL.md+++ b/.claude/skills/developing-standalone/SKILL.md@@ -17,7 +17,7 @@ apps/standalone/src/leader_election.ts # Web Lock decides which tab owns the database workersrc/local-bridge.ts # page ⇄ worker protocol (LOCAL_REQUEST/RESPONSE, WS_MESSAGE, HTTP_REQUEST, backup/restore)src/local-server-worker.ts # the worker: opens SQLite, initializeCore(), routes requests- src/ios-interceptors.ts # iOS Capacitor only (see mobile skill)+ src/native-request-bridge.ts # mobile shells only: answers native-intercepted requests (see mobile skill)src/error-overlay.ts # full-screen surface for fatal startup failuressrc/lightweight/ # browser implementations of every core provider + standalone-only routessrc/services/ # image provider, Capacitor HTTP handlerdiff --git a/CLAUDE.md b/CLAUDE.mdindex b802237a8d..14fa49f469 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -148,7 +148,7 @@ Shared components live in `apps/client/src/widgets/react/` — **always** reuse`apps/standalone` runs the client on the page and `@triliumnext/core` — plain JS — in a dedicated Web Worker over `@sqlite.org/sqlite-wasm` persisted in OPFS; a Web Lock elects the one tab that owns the database, which answers its own API calls straight from the worker (`standaloneApi.localFetch`); the service worker forwards other tabs' calls to it and covers what the page still requests. Every core provider has a browser twin in `apps/standalone/src/lightweight/` — **a new provider or Node import in core breaks this build first.** Load the **`developing-standalone` skill** before touching `sw.ts`, `main.ts`, `local-server-worker.ts`, `lightweight/*` or `vite.config.mts`.### Mobile (Capacitor) app-`apps/mobile` wraps the standalone WASM build in a Capacitor WebView — no network backend. Its one tab always owns the worker, so the client answers most API calls in-page; what still leaves it (images, fonts, uploads) goes through `TriliumRequestBridge` on Android, at `https://localhost`, where `shouldInterceptRequest` replaces the service worker and answers GET/HEAD only, and through `apps/standalone/src/ios-interceptors.ts` on iOS, at `capacitor://localhost`, where no service worker can register. **`iosScheme: "https"` is a no-op and must not be re-added, and the iOS interceptor path is not dead code.** Load the **`developing-capacitor-mobile` skill** before touching `apps/mobile`, `ios-interceptors.ts`, `android-request-bridge.ts`, `capacitor_http_handler.ts` or the `capacitor:` branches of `sw.ts`/`main.ts`.+`apps/mobile` wraps the standalone WASM build in a Capacitor WebView — no network backend. Its one tab always owns the worker, so the client answers most API calls in-page; what still leaves it (images, fonts, media, iframes) goes to a native request bridge instead of a service worker: `TriliumRequestBridge.java` from `shouldInterceptRequest` on Android, at `https://localhost`, and `TriliumRequestBridge.swift` from Capacitor's `capacitor://` scheme handler (re-typed with `object_setClass`) on iOS, where no service worker can register. Both forward to `apps/standalone/src/native-request-bridge.ts` and answer GET/HEAD only. **`iosScheme: "https"` is a no-op and must not be re-added.** Load the **`developing-capacitor-mobile` skill** before touching `apps/mobile`, `native-request-bridge.ts`, `capacitor_http_handler.ts` or the `capacitor:` branches of `sw.ts`/`main.ts`.### PDF viewerPDF notes render in Mozilla's PDF.js viewer plus Trilium's code from `packages/pdfjs-viewer`, which every app serves from the built `dist` — **rebuild it (`pnpm --filter @triliumnext/pdfjs-viewer build`) after every viewer change**, since no `*:start` script does; load the **`developing-pdf-viewer` skill** before touching the viewer, `Pdf.tsx` or the PDF sidebar panels.diff --git a/apps/client/src/services/custom_fonts.ts b/apps/client/src/services/custom_fonts.tsindex 0b73649bd8..5910fce090 100644--- a/apps/client/src/services/custom_fonts.ts+++ b/apps/client/src/services/custom_fonts.ts@@ -119,10 +119,9 @@ export async function getCustomFonts() {* `document.fonts.delete()` once it is done with it.** The bytes are fetched and handed to `FontFace` rather than referenced by their API URL: a `url()`- * source is loaded by the engine itself, outside the host document's service worker and Capacitor- * request interceptors, which is where standalone and iOS answer an API request from (see- * `loadIconPackFont`). `version` — a blobId — keeps a replaced file from being served from the- * cache of the one it replaced.+ * source is loaded by the engine itself, outside the host document's service worker, which is where+ * standalone answers an API request from (see `loadIconPackFont`). `version` — a blobId — keeps a+ * replaced file from being served from the cache of the one it replaced.*/export async function registerFontNote(noteId: string, family: string, version: string) {// Resolved against the host document's base URL, which also covers Electron's `trilium-app://`.diff --git a/apps/client/src/widgets/react/IsolatedFrame.tsx b/apps/client/src/widgets/react/IsolatedFrame.tsxindex 4735f458e6..79adf4af82 100644--- a/apps/client/src/widgets/react/IsolatedFrame.tsx+++ b/apps/client/src/widgets/react/IsolatedFrame.tsx@@ -27,10 +27,9 @@ interface IsolatedFrameProps {* from that CSS must be absolute.** They must also not point at the backend: an `about:blank` document is not controlled by a service- * worker and inherits none of the host document's request interceptors, so in standalone (and on- * iOS/Capacitor) an `/api/...` subresource never reaches the local backend — it hits the network and- * comes back as the SPA fallback HTML. Fetch such content from the host document and reference it- * here as a `blob:` URL instead (see `loadIconPackFont`).+ * worker, so in standalone an `/api/...` subresource never reaches the local backend — it hits the+ * network and comes back as the SPA fallback HTML. Fetch such content from the host document and+ * reference it here as a `blob:` URL instead (see `loadIconPackFont`).*/export default function IsolatedFrame({ className, title, css, cssVars, bodyClassName, children }: IsolatedFrameProps) {const iframeRef = useRef<HTMLIFrameElement>(null);diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsx b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsxindex 2c9f529ea2..17316009ce 100644--- a/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsx+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsx@@ -179,12 +179,10 @@ function useIconPackFont(note: FNote): IconPackFont | null {** The bytes are fetched here, from the host document, rather than being referenced by their API URL* from the preview's `@font-face`: the preview lives in a `src`-less iframe, whose `about:blank`- * document is *not* controlled by a service worker and carries none of the host's request- * interceptors. In standalone that means such a request never reaches the SQLite worker — it goes- * to the real network, where the SPA fallback answers a font request with `index.html`, and the- * browser reports "Failed to decode downloaded font". The same holds on iOS/Capacitor, whose- * fetch/stylesheet interceptors are likewise installed on the host document only. A `blob:` URL- * needs no such routing, so it works on every platform.+ * document is *not* controlled by a service worker. In standalone that means such a request never+ * reaches the SQLite worker — it goes to the real network, where the SPA fallback answers a font+ * request with `index.html`, and the browser reports "Failed to decode downloaded font". A `blob:`+ * URL needs no such routing, so it works on every platform.*/export async function loadIconPackFont(note: FNote): Promise<IconPackFont | null> {const attachments = await note.getAttachmentsByRole("file");diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.javaindex 4ef676279b..1032576cda 100644--- a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java@@ -31,7 +31,7 @@ import java.util.function.Function;* {@code window.__triliumNativeRequest()} and blocks until the head of the reply arrives. The* body then streams through a {@link ChunkStream}. The page's messages arrive through* {@link #onMessage} and {@link #onFrame}; the protocol is described in- * {@code apps/standalone/src/android-request-bridge.ts}.+ * {@code apps/standalone/src/native-request-bridge.ts}.** <p>Requests that arrive before the page sends {@code ready} are queued, and* {@link #onPageStarted} fails whatever the previous page left unanswered.diff --git a/apps/mobile/ios/App/App.xcodeproj/project.pbxproj b/apps/mobile/ios/App/App.xcodeproj/project.pbxprojindex 144290b2f4..541d5b00cf 100644--- a/apps/mobile/ios/App/App.xcodeproj/project.pbxproj+++ b/apps/mobile/ios/App/App.xcodeproj/project.pbxproj@@ -16,6 +16,7 @@504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };6DB328362F98030500787D66 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DB328352F98030500787D66 /* ViewController.swift */; };+ 6DB328412F98050000787D66 /* TriliumRequestBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DB328402F98050000787D66 /* TriliumRequestBridge.swift */; };/* End PBXBuildFile section *//* Begin PBXFileReference section */@@ -29,6 +30,7 @@504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };6DB328352F98030500787D66 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; };+ 6DB328402F98050000787D66 /* TriliumRequestBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TriliumRequestBridge.swift; sourceTree = "<group>"; };958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; };/* End PBXFileReference section */@@ -65,6 +67,7 @@isa = PBXGroup;children = (6DB328352F98030500787D66 /* ViewController.swift */,+ 6DB328402F98050000787D66 /* TriliumRequestBridge.swift */,50379B222058CBB4000EE86E /* capacitor.config.json */,504EC3071FED79650016851F /* AppDelegate.swift */,504EC30B1FED79650016851F /* Main.storyboard */,@@ -159,6 +162,7 @@buildActionMask = 2147483647;files = (6DB328362F98030500787D66 /* ViewController.swift in Sources */,+ 6DB328412F98050000787D66 /* TriliumRequestBridge.swift in Sources */,504EC3081FED79650016851F /* AppDelegate.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;diff --git a/apps/mobile/ios/App/App/TriliumRequestBridge.swift b/apps/mobile/ios/App/App/TriliumRequestBridge.swiftnew file mode 100644index 0000000000..0476651de8--- /dev/null+++ b/apps/mobile/ios/App/App/TriliumRequestBridge.swift@@ -0,0 +1,251 @@+import Capacitor+import Foundation+import WebKit++/// Must match `isLocalApiRequest()` in apps/standalone/src/local-bridge.ts.+private let localApiPrefixes = ["/bootstrap", "/api/", "/sync/", "/search/", "/custom/"]++func isLocalApiPath(_ path: String) -> Bool {+ if path == "/share" || (path.hasPrefix("/share/") && !path.hasPrefix("/share/assets/")) {+ return true+ }+ return localApiPrefixes.contains { path.hasPrefix($0) }+}++/// Capacitor's `WebViewAssetHandler` for `capacitor://`, re-typed by+/// `ViewController.webView(with:configuration:)`. It sees every request on the scheme, whichever+/// part of the engine issued it (fetch, XHR, images, fonts, media, iframes), hands local API+/// paths to `TriliumRequestBridge`, and leaves the rest to Capacitor's asset serving.+///+/// It must not declare stored properties: the instance it takes over was allocated as a+/// `WebViewAssetHandler`, so the subclass's storage would be uninitialized.+final class TriliumAssetHandler: WebViewAssetHandler {+ override func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {+ let request = urlSchemeTask.request+ if let url = request.url, url == request.mainDocumentURL {+ TriliumRequestBridge.shared.pageStarted()+ }+ if let path = request.url?.path, isLocalApiPath(path) {+ TriliumRequestBridge.shared.start(urlSchemeTask, in: webView)+ return+ }+ super.webView(webView, start: urlSchemeTask)+ }++ override func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {+ if TriliumRequestBridge.shared.stop(urlSchemeTask) {+ return+ }+ super.webView(webView, stop: urlSchemeTask)+ }+}++/// Answers local API requests from the page's SQLite worker, in place of a service worker.+///+/// A request goes to the page through `window.__triliumNativeRequest()`, and the page replies+/// over the `triliumRequestBridge` script message handler; the protocol is described in+/// apps/standalone/src/native-request-bridge.ts. Bodies arrive as base64 chunks, since script+/// messages cannot carry ArrayBuffers. Requests that arrive before the page sends `ready` are+/// queued, and a new main document fails whatever the previous page left unanswered.+///+/// WebKit calls the scheme handler, the message handler and `evaluateJavaScript` completions on+/// the main thread, so all state stays there.+final class TriliumRequestBridge: NSObject, WKScriptMessageHandler {+ static let shared = TriliumRequestBridge()+ static let messageHandlerName = "triliumRequestBridge"++ /// Matches the service worker's limit in sw.ts: the worker can be inside a long synchronous+ /// stretch (a VACUUM of a large database) before it answers.+ private static let headTimeout: TimeInterval = 270+ private static let errorHeader = "x-trilium-bridge-error"++ private final class PendingRequest {+ let task: WKURLSchemeTask+ let script: String+ var headSent = false++ init(task: WKURLSchemeTask, script: String) {+ self.task = task+ self.script = script+ }+ }++ private var pending: [Int: PendingRequest] = [:]+ private var taskIds: [ObjectIdentifier: Int] = [:]+ private var queuedIds: [Int] = []+ private var pageReady = false+ private var nextId = 0+ private weak var webView: WKWebView?++ func start(_ task: WKURLSchemeTask, in webView: WKWebView) {+ self.webView = webView+ let request = task.request+ let method = (request.httpMethod ?? "GET").uppercased()+ guard method == "GET" || method == "HEAD" else {+ // Android's bridge cannot see request bodies, so neither platform forwards them; the+ // page sends these through standaloneApi.localFetch instead.+ respondWithError(task, status: 405,+ message: "\(method) cannot be answered natively: the request body is not available")+ return+ }++ nextId += 1+ let id = nextId+ let payload: [String: Any] = [+ "id": id,+ "method": method,+ "url": request.url?.absoluteString ?? "",+ "headers": request.allHTTPHeaderFields ?? [:],+ "binary": false+ ]+ guard let data = try? JSONSerialization.data(withJSONObject: payload),+ let json = String(data: data, encoding: .utf8) else {+ respondWithError(task, status: 500, message: "Cannot encode the request")+ return+ }+ // U+2028 and U+2029 are valid in JSON strings but end a line in JavaScript source.+ let literal = json+ .replacingOccurrences(of: "\u{2028}", with: "\\u2028")+ .replacingOccurrences(of: "\u{2029}", with: "\\u2029")++ pending[id] = PendingRequest(+ task: task,+ script: "window.__triliumNativeRequest ? (window.__triliumNativeRequest(\(literal)), true) : false")+ taskIds[ObjectIdentifier(task)] = id+ if pageReady {+ dispatch(id)+ } else {+ queuedIds.append(id)+ }++ DispatchQueue.main.asyncAfter(deadline: .now() + Self.headTimeout) { [weak self] in+ guard let self = self, let request = self.pending[id], !request.headSent else { return }+ self.fail(id, status: 504, message: "The local worker did not answer in time")+ }+ }++ /// Returns true when the task was one of ours. A stopped task must not be completed, so it+ /// leaves the pending map before WebKit returns from `stop`.+ func stop(_ task: WKURLSchemeTask) -> Bool {+ guard let id = taskIds.removeValue(forKey: ObjectIdentifier(task)) else {+ return false+ }+ pending.removeValue(forKey: id)+ return true+ }++ func pageStarted() {+ pageReady = false+ queuedIds.removeAll()+ for id in Array(pending.keys) {+ fail(id, message: "The page reloaded before answering")+ }+ }++ func userContentController(_ userContentController: WKUserContentController,+ didReceive message: WKScriptMessage) {+ guard message.frameInfo.isMainFrame,+ let text = message.body as? String,+ let data = text.data(using: .utf8),+ let body = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ let type = body["type"] as? String else {+ return+ }+ if type == "ready" {+ onPageReady()+ return+ }++ guard let id = body["id"] as? Int, let request = pending[id] else { return }+ switch type {+ case "head":+ receiveHead(id, request, status: body["status"] as? Int ?? 200,+ headers: body["headers"] as? [String: String] ?? [:])+ case "chunk":+ if request.headSent, let encoded = body["data"] as? String,+ let bytes = Data(base64Encoded: encoded) {+ request.task.didReceive(bytes)+ }+ case "end":+ if take(id) != nil, request.headSent {+ request.task.didFinish()+ }+ case "error":+ fail(id, message: body["message"] as? String ?? "The local request failed")+ default:+ break+ }+ }++ private func onPageReady() {+ pageReady = true+ let ids = queuedIds+ queuedIds.removeAll()+ for id in ids {+ dispatch(id)+ }+ }++ private func dispatch(_ id: Int) {+ guard let request = pending[id], let webView = webView else { return }+ webView.evaluateJavaScript(request.script) { [weak self] result, error in+ if error != nil || (result as? Bool) != true {+ self?.fail(id, message: "The page has no request handler")+ }+ }+ }++ private func receiveHead(_ id: Int, _ request: PendingRequest, status: Int, headers: [String: String]) {+ // WebKit does not follow a redirect from a scheme task; the page turns redirects into a+ // 200 already.+ guard (100...599).contains(status), !(300...399).contains(status),+ let url = request.task.request.url,+ let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1",+ headerFields: headers) else {+ fail(id, message: "The local worker answered with status \(status)")+ return+ }+ request.task.didReceive(response)+ request.headSent = true+ }++ /// Before the head, answers with an error response the page can read; after it, fails the+ /// load.+ private func fail(_ id: Int, status: Int = 502, message: String) {+ guard let request = take(id) else { return }+ NSLog("[TriliumRequestBridge] %@", message)+ if request.headSent {+ request.task.didFailWithError(NSError(+ domain: "TriliumRequestBridge", code: status,+ userInfo: [NSLocalizedDescriptionKey: message]))+ } else {+ respondWithError(request.task, status: status, message: message)+ }+ }++ private func take(_ id: Int) -> PendingRequest? {+ guard let request = pending.removeValue(forKey: id) else { return nil }+ taskIds.removeValue(forKey: ObjectIdentifier(request.task))+ return request+ }++ private func respondWithError(_ task: WKURLSchemeTask, status: Int, message: String) {+ let body = Data(message.utf8)+ let headerValue = String(message.unicodeScalars.map {+ (0x20...0x7e).contains($0.value) ? Character($0) : " "+ })+ guard let url = task.request.url,+ let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: [+ "Content-Type": "text/plain; charset=utf-8",+ "Content-Length": String(body.count),+ Self.errorHeader: headerValue+ ]) else {+ task.didFailWithError(NSError(domain: "TriliumRequestBridge", code: status,+ userInfo: [NSLocalizedDescriptionKey: message]))+ return+ }+ task.didReceive(response)+ task.didReceive(body)+ task.didFinish()+ }+}diff --git a/apps/mobile/ios/App/App/ViewController.swift b/apps/mobile/ios/App/App/ViewController.swiftindex 37d2835b65..d3a89b28b4 100644--- a/apps/mobile/ios/App/App/ViewController.swift+++ b/apps/mobile/ios/App/App/ViewController.swift@@ -29,6 +29,19 @@ class ViewController: CAPBridgeViewController {keyboardFrameTracker?.invalidate()}+ // Routes local API requests on capacitor:// to TriliumRequestBridge. Capacitor registers its+ // WebViewAssetHandler before this hook runs, and WebKit raises NSInvalidArgumentException on+ // a second handler for the same scheme, so the registered instance is re-typed to the+ // TriliumAssetHandler subclass instead (the same technique as hideKeyboardInputAccessoryView).+ override func webView(with frame: CGRect, configuration: WKWebViewConfiguration) -> WKWebView {+ if let assetHandler = configuration.urlSchemeHandler(forURLScheme: "capacitor") as? WebViewAssetHandler {+ object_setClass(assetHandler, TriliumAssetHandler.self)+ }+ configuration.userContentController.add(TriliumRequestBridge.shared,+ name: TriliumRequestBridge.messageHandlerName)+ return super.webView(with: frame, configuration: configuration)+ }+// When a page element receives focus and the keyboard animates in,// WKWebView reflexively scrolls its outer UIScrollView upward to keep// the focused element visible. Our layout is `body { position: fixed;diff --git a/apps/standalone/src/ios-interceptors.spec.ts b/apps/standalone/src/ios-interceptors.spec.tsdeleted file mode 100644index 33886189c1..0000000000--- a/apps/standalone/src/ios-interceptors.spec.ts+++ /dev/null@@ -1,672 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { installIosInterceptors, setupFetchInterceptor, setupImageInterceptor, setupStylesheetInterceptor, setupXhrInterceptor } from "./ios-interceptors.js";--const mocks = vi.hoisted(() => ({- localFetch: vi.fn(),- isLocalApiRequest: vi.fn()-}));--vi.mock("./local-bridge.js", () => ({- localFetch: (req: Request) => mocks.localFetch(req),- isLocalApiRequest: (url: URL) => mocks.isLocalApiRequest(url)-}));--/** Same-origin URL against the happy-dom base (http://localhost:3000 by default). */-function localUrl(path: string) {- return new URL(path, location.href).href;-}--function makeResponse(body: BodyInit | null, init: ResponseInit = {}) {- return new Response(body, { status: 200, statusText: "OK", ...init });-}--const originalFetch = window.fetch;-const OriginalXHR = window.XMLHttpRequest;--// setupImageInterceptor installs a permanent MutationObserver on-// document.documentElement. Across tests those observers would pile up and each-// react to the same DOM mutations, so capture every observer and disconnect it-// after the test that created it.-let observers: MutationObserver[] = [];-let RealMutationObserver: typeof MutationObserver;--beforeEach(() => {- mocks.localFetch.mockReset();- mocks.isLocalApiRequest.mockReset();- // By default, treat anything under /api/ as a local API request.- mocks.isLocalApiRequest.mockImplementation((url: URL) => url.pathname.startsWith("/api/"));- mocks.localFetch.mockResolvedValue(makeResponse("{}"));- document.body.innerHTML = "";- vi.spyOn(console, "warn").mockImplementation(() => {});-- observers = [];- RealMutationObserver = window.MutationObserver;- window.MutationObserver = class extends RealMutationObserver {- constructor(callback: MutationCallback) {- super(callback);- observers.push(this);- }- };-});--afterEach(() => {- observers.forEach((o) => o.disconnect());- window.MutationObserver = RealMutationObserver;- window.fetch = originalFetch;- window.XMLHttpRequest = OriginalXHR;- vi.restoreAllMocks();-});--describe("installIosInterceptors", () => {- it("installs the fetch, XHR, and image interceptors together", () => {- const original = window.fetch;- installIosInterceptors();- // fetch was replaced- expect(window.fetch).not.toBe(original);- // XHR was replaced with a subclass- expect(window.XMLHttpRequest).not.toBe(OriginalXHR);- });-});--describe("setupFetchInterceptor", () => {- let passthrough: ReturnType<typeof vi.fn>;-- beforeEach(() => {- passthrough = vi.fn().mockResolvedValue(makeResponse("passthrough"));- window.fetch = passthrough as unknown as typeof window.fetch;- setupFetchInterceptor();- });-- it("routes a local API string URL through localFetch", async () => {- const resp = makeResponse("local");- mocks.localFetch.mockResolvedValue(resp);- const result = await window.fetch("/api/notes");- expect(result).toBe(resp);- expect(passthrough).not.toHaveBeenCalled();- const [req] = mocks.localFetch.mock.calls[0];- expect(req).toBeInstanceOf(Request);- expect(req.url).toBe(localUrl("/api/notes"));- });-- it("routes a URL object input through localFetch", async () => {- await window.fetch(new URL(localUrl("/api/tree")));- expect(mocks.localFetch).toHaveBeenCalledOnce();- expect(passthrough).not.toHaveBeenCalled();- });-- it("routes a Request object input through localFetch", async () => {- await window.fetch(new Request(localUrl("/api/search")));- expect(mocks.localFetch).toHaveBeenCalledOnce();- });-- it("passes a same-origin non-API request straight to the original fetch", async () => {- const result = await window.fetch("/not-api/page");- expect(mocks.localFetch).not.toHaveBeenCalled();- expect(passthrough).toHaveBeenCalledOnce();- expect(await result.text()).toBe("passthrough");- });-- it("passes a cross-origin request straight to the original fetch", async () => {- await window.fetch("https://example.com/api/notes");- expect(mocks.localFetch).not.toHaveBeenCalled();- expect(passthrough).toHaveBeenCalledOnce();- });-});--describe("setupImageInterceptor", () => {- /** Wait until the image's src has been rewritten to a blob: URL. */- async function waitForBlobSrc(img: HTMLImageElement) {- await vi.waitFor(() => expect(img.getAttribute("src")).toMatch(/^blob:/));- }-- beforeEach(() => {- // Deterministic blob URL so assertions don't depend on the environment.- vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:fake-url");- });-- it("swaps an <img> already in the document pointing at a local API path", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("img-bytes"));- const img = document.createElement("img");- img.setAttribute("src", "/api/images/1");- document.body.appendChild(img);-- setupImageInterceptor();-- await waitForBlobSrc(img);- expect(mocks.localFetch).toHaveBeenCalledOnce();- });-- it("swaps an <img> appended after setup (childList observer)", async () => {- setupImageInterceptor();- const img = document.createElement("img");- img.setAttribute("src", "/api/images/2");- document.body.appendChild(img);- await waitForBlobSrc(img);- });-- it("swaps <img> nested inside an appended container (querySelectorAll path)", async () => {- setupImageInterceptor();- const container = document.createElement("div");- const img = document.createElement("img");- img.setAttribute("src", "/api/images/3");- container.appendChild(img);- document.body.appendChild(container);- await waitForBlobSrc(img);- });-- it("swaps when the src attribute of an existing image changes to a local API path", async () => {- const img = document.createElement("img");- img.setAttribute("src", "https://example.com/remote.png");- document.body.appendChild(img);- setupImageInterceptor();-- img.setAttribute("src", "/api/images/4");- await waitForBlobSrc(img);- });-- it("ignores blob:, data:, empty, and non-API sources", async () => {- for (const src of ["", "data:image/png;base64,AAAA", "blob:existing", "/other/x.png"]) {- const img = document.createElement("img");- if (src) img.setAttribute("src", src);- document.body.appendChild(img);- }- setupImageInterceptor();- // Give the async swap a chance to (not) run.- await new Promise((r) => setTimeout(r, 20));- expect(mocks.localFetch).not.toHaveBeenCalled();- });-- it("treats an unparseable src as non-matching without throwing", async () => {- const img = document.createElement("img");- img.setAttribute("src", "https://exa mple.com/api/x");- document.body.appendChild(img);- setupImageInterceptor();- await new Promise((r) => setTimeout(r, 20));- expect(mocks.localFetch).not.toHaveBeenCalled();- });-- it("leaves the src untouched and allows a retry when the fetch is not ok", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("nope", { status: 404, statusText: "Not Found" }));- const img = document.createElement("img");- img.setAttribute("src", "/api/images/5");- document.body.appendChild(img);- setupImageInterceptor();-- await vi.waitFor(() => expect(mocks.localFetch).toHaveBeenCalledOnce());- expect(img.getAttribute("src")).toBe("/api/images/5");-- // Because the dedup entry was cleared, the same src can be retried. Bounce- // through a non-API src so the attribute genuinely changes value (happy-dom- // only fires a mutation on a real change) before returning to the API path.- mocks.localFetch.mockResolvedValue(makeResponse("ok-now"));- img.setAttribute("src", "/not-api/placeholder.png");- img.setAttribute("src", "/api/images/5");- await vi.waitFor(() => expect(mocks.localFetch).toHaveBeenCalledTimes(2));- });-- it("logs a warning and clears dedup when the fetch throws", async () => {- mocks.localFetch.mockRejectedValue(new Error("boom"));- const img = document.createElement("img");- img.setAttribute("src", "/api/images/6");- document.body.appendChild(img);- setupImageInterceptor();-- await vi.waitFor(() => expect(console.warn).toHaveBeenCalled());- expect(img.getAttribute("src")).toBe("/api/images/6");- });-- it("does not re-fetch when the same src is processed twice (dedup)", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("bytes"));- const img = document.createElement("img");- img.setAttribute("src", "/api/images/7");- document.body.appendChild(img);- setupImageInterceptor();-- // First pass swaps to the (mocked) blob URL.- await waitForBlobSrc(img);- expect(mocks.localFetch).toHaveBeenCalledOnce();-- // Point the same element back at the already-processed API path. The- // attribute genuinely changes (blob: → /api/…), so the observer fires,- // but the dedup WeakMap short-circuits before a second fetch.- img.setAttribute("src", "/api/images/7");- await new Promise((r) => setTimeout(r, 20));- expect(mocks.localFetch).toHaveBeenCalledOnce();- });-- it("revokes the previous blob URL when an image is repointed to another API image", async () => {- let counter = 0;- vi.spyOn(URL, "createObjectURL").mockImplementation(() => `blob:url-${++counter}`);- const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});- // Fresh Response per call — a body can only be read once, and this image- // is swapped twice.- mocks.localFetch.mockImplementation(async () => makeResponse("bytes"));-- const img = document.createElement("img");- img.setAttribute("src", "/api/images/1");- document.body.appendChild(img);- setupImageInterceptor();- await vi.waitFor(() => expect(img.getAttribute("src")).toBe("blob:url-1"));-- // Repoint the same element at a different API image; the first blob URL is- // now orphaned and must be revoked, otherwise it leaks for the page's life.- img.setAttribute("src", "/api/images/2");- await vi.waitFor(() => expect(img.getAttribute("src")).toBe("blob:url-2"));-- expect(revoke).toHaveBeenCalledWith("blob:url-1");- });-- it("revokes the blob URL when an intercepted image is removed from the DOM", async () => {- vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:removed-url");- const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});- mocks.localFetch.mockResolvedValue(makeResponse("bytes"));-- const img = document.createElement("img");- img.setAttribute("src", "/api/images/1");- document.body.appendChild(img);- setupImageInterceptor();- await vi.waitFor(() => expect(img.getAttribute("src")).toBe("blob:removed-url"));-- // Navigating away removes the <img>; its blob URL must be revoked or it- // leaks — the dominant "every note you open adds memory" case.- img.remove();- await vi.waitFor(() => expect(revoke).toHaveBeenCalledWith("blob:removed-url"));- });-- it("revokes blob URLs of images inside a removed container subtree", async () => {- vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:subtree-url");- const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});- mocks.localFetch.mockResolvedValue(makeResponse("bytes"));-- const container = document.createElement("div");- const img = document.createElement("img");- img.setAttribute("src", "/api/images/1");- container.appendChild(img);- document.body.appendChild(container);- setupImageInterceptor();- await vi.waitFor(() => expect(img.getAttribute("src")).toBe("blob:subtree-url"));-- // Removing the wrapper detaches the nested <img> too; its URL must be freed.- container.remove();- await vi.waitFor(() => expect(revoke).toHaveBeenCalledWith("blob:subtree-url"));- });-- it("ignores removed non-element nodes", async () => {- const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});- const text = document.createTextNode("text");- document.body.appendChild(text);- setupImageInterceptor();-- text.remove(); // removedNodes contains a text node — neither <img> nor Element- await new Promise((r) => setTimeout(r, 20));- expect(revoke).not.toHaveBeenCalled();- });-- it("ignores src mutations on non-image elements", async () => {- const span = document.createElement("span");- span.setAttribute("src", "/api/images/a");- document.body.appendChild(span);- setupImageInterceptor();-- span.setAttribute("src", "/api/images/b"); // attributes record whose target is not an <img>- await new Promise((r) => setTimeout(r, 20));- expect(mocks.localFetch).not.toHaveBeenCalled();- });-- it("ignores appended non-element nodes", async () => {- setupImageInterceptor();- document.body.appendChild(document.createComment("comment"));- document.body.appendChild(document.createTextNode("text"));- await new Promise((r) => setTimeout(r, 20));- expect(mocks.localFetch).not.toHaveBeenCalled();- });-- it("defers observation until DOMContentLoaded when documentElement is not ready", async () => {- const realDocEl = document.documentElement;- let docEl: HTMLElement | null = null;- Object.defineProperty(document, "documentElement", { configurable: true, get: () => docEl });-- setupImageInterceptor(); // documentElement null → registers a DOMContentLoaded listener-- docEl = realDocEl; // restore before the deferred start() observes it- const img = document.createElement("img");- img.setAttribute("src", "/api/images/8");- document.body.appendChild(img);- document.dispatchEvent(new Event("DOMContentLoaded"));-- await vi.waitFor(() => expect(mocks.localFetch).toHaveBeenCalledOnce());- Object.defineProperty(document, "documentElement", { configurable: true, value: realDocEl });- });-});--describe("setupStylesheetInterceptor", () => {- function addStyle(css: string) {- const styleEl = document.createElement("style");- styleEl.textContent = css;- document.body.appendChild(styleEl);- return styleEl;- }-- it("rewrites local API url() refs in an existing <style> to blob URLs, fetching each unique URL once", async () => {- let counter = 0;- vi.spyOn(URL, "createObjectURL").mockImplementation(() => `blob:font-${++counter}`);- mocks.localFetch.mockImplementation(async () => makeResponse("font-bytes"));-- // Same URL referenced with two quoting styles + a second URL unquoted; the- // bundled relative ref and the data: URI must stay untouched.- const styleEl = addStyle(`- @font-face { src: url('api/attachments/download/f1') format('woff2'); }- .a { background: url("api/attachments/download/f1"); }- .b { background: url(api/attachments/download/f2); }- .c { background: url('./fonts/bundled.woff2'); }- .d { background: url(data:font/woff2;base64,AAAA); }- `);- setupStylesheetInterceptor();-- await vi.waitFor(() => expect(styleEl.textContent).toContain("blob:"));- const css = styleEl.textContent ?? "";- expect(css).not.toContain("api/attachments/download");- // Both f1 refs collapse to the same blob URL; f2 gets its own.- expect(css.match(/blob:font-1/g)).toHaveLength(2);- expect(css).toContain("blob:font-2");- expect(css).toContain("./fonts/bundled.woff2");- expect(css).toContain("data:font/woff2;base64,AAAA");- expect(mocks.localFetch).toHaveBeenCalledTimes(2);- const fetchedUrls = mocks.localFetch.mock.calls.map(([req]) => (req as Request).url);- expect(fetchedUrls).toEqual([- localUrl("/api/attachments/download/f1"),- localUrl("/api/attachments/download/f2")- ]);- });-- it("rewrites a <style> appended after setup without reprocessing its own rewrite", async () => {- vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:font-url");- mocks.localFetch.mockImplementation(async () => makeResponse("font-bytes"));- setupStylesheetInterceptor();-- const styleEl = addStyle(".x { src: url('api/attachments/download/f1'); }");- await vi.waitFor(() => expect(styleEl.textContent).toContain("blob:font-url"));-- // The rewrite itself mutates the style; the second pass must find nothing to do.- await new Promise((r) => setTimeout(r, 20));- expect(mocks.localFetch).toHaveBeenCalledOnce();- });-- it("rewrites when a style's text is replaced later and shares the asset cache across styles", async () => {- vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:shared-font");- mocks.localFetch.mockImplementation(async () => makeResponse("font-bytes"));- const plain = addStyle(".plain { color: red; }");- setupStylesheetInterceptor();-- plain.textContent = ".x { src: url('api/attachments/download/f1'); }";- await vi.waitFor(() => expect(plain.textContent).toContain("blob:shared-font"));-- // A second stylesheet referencing the same asset reuses the cached blob URL.- const second = addStyle(".y { src: url('api/attachments/download/f1'); }");- await vi.waitFor(() => expect(second.textContent).toContain("blob:shared-font"));- expect(mocks.localFetch).toHaveBeenCalledOnce();- });-- it("leaves the style unchanged when the asset fetch fails, then allows a retry", async () => {- mocks.localFetch.mockRejectedValue(new Error("worker down"));- const css = ".x { src: url('api/attachments/download/f1'); }";- const styleEl = addStyle(css);- setupStylesheetInterceptor();-- await vi.waitFor(() => expect(console.warn).toHaveBeenCalled());- expect(styleEl.textContent).toBe(css);-- // The failure is dropped from the cache, so the next stylesheet retries the fetch.- vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:retried");- mocks.localFetch.mockImplementation(async () => makeResponse("font-bytes"));- const second = addStyle(css);- await vi.waitFor(() => expect(second.textContent).toContain("blob:retried"));- });-- it("swaps a local API stylesheet <link> to a blob URL and rewrites the fetched CSS", async () => {- const themeCss = `- @font-face { src: url('api/attachments/download/themefont'); }- .bg { background: url(../../../fonts/asset.png); }- `;- mocks.localFetch.mockImplementation(async (req: Request) =>- makeResponse(req.url.includes("notes/download") ? themeCss : "font-bytes"));- const cssBlobs: Blob[] = [];- vi.spyOn(URL, "createObjectURL").mockImplementation((blob) => {- if ((blob as Blob).type === "text/css") {- cssBlobs.push(blob as Blob);- return `blob:css-${cssBlobs.length}`;- }- return "blob:theme-font";- });- setupStylesheetInterceptor();-- const link = document.createElement("link");- link.setAttribute("rel", "stylesheet");- link.setAttribute("href", "api/notes/download/theme1");- document.body.appendChild(link);-- await vi.waitFor(() => expect(link.getAttribute("href")).toBe("blob:css-1"));- const rewritten = await cssBlobs[0].text();- // The api font ref becomes a blob URL; the bundled relative ref is absolutized- // (relative paths would otherwise resolve against the blob: origin and break).- expect(rewritten).toContain('url("blob:theme-font")');- expect(rewritten).toContain(`url("${localUrl("/fonts/asset.png")}")`);- });-- it("ignores non-stylesheet links, cross-origin stylesheets, and styles without url() refs", async () => {- setupStylesheetInterceptor();-- const icon = document.createElement("link");- icon.setAttribute("rel", "icon");- icon.setAttribute("href", "api/notes/download/x");- document.body.appendChild(icon);-- const remote = document.createElement("link");- remote.setAttribute("rel", "stylesheet");- remote.setAttribute("href", "https://example.com/api/theme.css");- document.body.appendChild(remote);-- addStyle(".plain { color: red; }");-- await new Promise((r) => setTimeout(r, 20));- expect(mocks.localFetch).not.toHaveBeenCalled();- });-- it("revokes the CSS blob when the link is repointed or removed", async () => {- let counter = 0;- vi.spyOn(URL, "createObjectURL").mockImplementation(() => `blob:css-${++counter}`);- const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});- mocks.localFetch.mockImplementation(async () => makeResponse(".theme {}"));- setupStylesheetInterceptor();-- const link = document.createElement("link");- link.setAttribute("rel", "stylesheet");- link.setAttribute("href", "api/notes/download/theme1");- document.body.appendChild(link);- await vi.waitFor(() => expect(link.getAttribute("href")).toBe("blob:css-1"));-- // Repointing at another theme replaces the blob and frees the old one.- link.setAttribute("href", "api/notes/download/theme2");- await vi.waitFor(() => expect(link.getAttribute("href")).toBe("blob:css-2"));- expect(revoke).toHaveBeenCalledWith("blob:css-1");-- // Removing the link frees the current one.- link.remove();- await vi.waitFor(() => expect(revoke).toHaveBeenCalledWith("blob:css-2"));- });-});--describe("setupXhrInterceptor", () => {- function openXhr(method: string, url: string) {- setupXhrInterceptor();- const xhr = new window.XMLHttpRequest();- xhr.open(method, url);- return xhr;- }-- /** Resolve once the intercepted request finishes (load or error). */- function done(xhr: XMLHttpRequest) {- return new Promise<void>((resolve) => xhr.addEventListener("loadend", () => resolve()));- }-- it("routes an intercepted GET through localFetch and exposes the response", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("hello", { headers: { "content-type": "text/plain", "x-foo": "bar" } }));- const xhr = openXhr("GET", "/api/notes");- const finished = done(xhr);- xhr.send();- await finished;-- expect(xhr.readyState).toBe(4);- expect(xhr.status).toBe(200);- expect(xhr.statusText).toBe("OK");- expect(xhr.responseText).toBe("hello");- expect(xhr.response).toBe("hello");- expect(xhr.responseURL).toBe(localUrl("/api/notes"));- expect(xhr.getResponseHeader("x-foo")).toBe("bar");- expect(xhr.getAllResponseHeaders()).toContain("x-foo: bar");- });-- it("accepts a URL object as the open() target", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("ok"));- setupXhrInterceptor();- const xhr = new window.XMLHttpRequest();- xhr.open("GET", new URL(localUrl("/api/thing")));- const finished = done(xhr);- xhr.send();- await finished;- expect(xhr.responseURL).toBe(localUrl("/api/thing"));- });-- it("parses a JSON responseType", async () => {- mocks.localFetch.mockResolvedValue(makeResponse(JSON.stringify({ ok: true })));- const xhr = openXhr("GET", "/api/tree");- xhr.responseType = "json";- const finished = done(xhr);- xhr.send();- await finished;- expect(xhr.response).toEqual({ ok: true });- });-- it("yields null for an invalid JSON responseType body", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("not json"));- const xhr = openXhr("GET", "/api/tree");- xhr.responseType = "json";- const finished = done(xhr);- xhr.send();- await finished;- expect(xhr.response).toBeNull();- });-- it("returns an ArrayBuffer for the arraybuffer responseType", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("abc"));- const xhr = openXhr("GET", "/api/blob");- xhr.responseType = "arraybuffer";- const finished = done(xhr);- xhr.send();- await finished;- expect(xhr.response).toBeInstanceOf(ArrayBuffer);- expect(new TextDecoder().decode(xhr.response as ArrayBuffer)).toBe("abc");- });-- it("returns a typed Blob for the blob responseType", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("xyz", { headers: { "content-type": "image/png" } }));- const xhr = openXhr("GET", "/api/image");- xhr.responseType = "blob";- const finished = done(xhr);- xhr.send();- await finished;- expect(xhr.response).toBeInstanceOf(Blob);- expect((xhr.response as Blob).type).toBe("image/png");- });-- it("defaults the Blob type to empty when no content-type is present", async () => {- // A null body carries no content-type header (a string body would make- // happy-dom synthesize "text/plain"), exercising the `?? ""` fallback.- mocks.localFetch.mockResolvedValue(makeResponse(null));- const xhr = openXhr("GET", "/api/image");- xhr.responseType = "blob";- const finished = done(xhr);- xhr.send();- await finished;- expect((xhr.response as Blob).type).toBe("");- });-- it("throws when responseText is read for a non-text responseType", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("{}"));- const xhr = openXhr("GET", "/api/tree");- xhr.responseType = "json";- const finished = done(xhr);- xhr.send();- await finished;- expect(() => xhr.responseText).toThrow(/responseText is only available/);- });-- it("forwards a request body for a POST and reads the intercept responseType", async () => {- mocks.localFetch.mockResolvedValue(makeResponse("created", { status: 201, statusText: "Created" }));- const xhr = openXhr("POST", "/api/notes");- xhr.setRequestHeader("content-type", "application/json");- expect(xhr.responseType).toBe(""); // intercept getter returns the stored value- const finished = done(xhr);- xhr.send(JSON.stringify({ title: "n" }));- await finished;-- expect(xhr.status).toBe(201);- const [req] = mocks.localFetch.mock.calls[0];- expect(req.method).toBe("POST");- expect(await req.text()).toBe(JSON.stringify({ title: "n" }));- expect(req.headers.get("content-type")).toBe("application/json");- });-- it("dispatches an error when the local fetch fails", async () => {- mocks.localFetch.mockRejectedValue(new Error("worker down"));- const xhr = openXhr("GET", "/api/notes");- const onError = vi.fn();- xhr.addEventListener("error", onError);- const finished = done(xhr);- xhr.send();- await finished;-- expect(xhr.status).toBe(0);- expect(xhr.readyState).toBe(4);- expect(onError).toHaveBeenCalledOnce();- });-- it("does not intercept a non-local request and delegates to the native XHR", () => {- mocks.isLocalApiRequest.mockReturnValue(false);- const openSpy = vi.spyOn(OriginalXHR.prototype, "open").mockImplementation(() => {});- const headerSpy = vi.spyOn(OriginalXHR.prototype, "setRequestHeader").mockImplementation(() => {});- const sendSpy = vi.spyOn(OriginalXHR.prototype, "send").mockImplementation(() => {});-- setupXhrInterceptor();- const xhr = new window.XMLHttpRequest();- xhr.open("GET", "https://example.com/api/notes");- xhr.setRequestHeader("x-a", "b");- xhr.send();-- expect(openSpy).toHaveBeenCalledOnce();- expect(headerSpy).toHaveBeenCalledWith("x-a", "b");- expect(sendSpy).toHaveBeenCalledOnce();- expect(mocks.localFetch).not.toHaveBeenCalled();- });-- it("delegates responseType get/set to the native XHR when not intercepting", () => {- mocks.isLocalApiRequest.mockReturnValue(false);- vi.spyOn(OriginalXHR.prototype, "open").mockImplementation(() => {});- const setSpy = vi.fn();- const getSpy = vi.fn().mockReturnValue("text");- Object.defineProperty(OriginalXHR.prototype, "responseType", {- configurable: true,- get: getSpy,- set: setSpy- });-- setupXhrInterceptor();- const xhr = new window.XMLHttpRequest();- xhr.open("GET", "https://example.com/x");- xhr.responseType = "text";- expect(setSpy).toHaveBeenCalledWith("text");- expect(xhr.responseType).toBe("text");- expect(getSpy).toHaveBeenCalled();- });-});diff --git a/apps/standalone/src/ios-interceptors.ts b/apps/standalone/src/ios-interceptors.tsdeleted file mode 100644index 3b97d36569..0000000000--- a/apps/standalone/src/ios-interceptors.ts+++ /dev/null@@ -1,453 +0,0 @@-import { isLocalApiRequest, localFetch } from "./local-bridge.js";--/**- * iOS-only request interceptors.- *- * iOS Capacitor loads the app on the `capacitor://` scheme, and WebKit refuses- * to register a service worker for a non-HTTP(S) origin. The standalone stack- * normally routes the client's API/sync calls to the in-browser SQLite worker- * through that service worker (this is what Android — served on `https://` via- * `androidScheme` — and the web build both rely on). Since the SW can't exist- * under `capacitor://`, these three interceptors stand in for it, each catching- * a request path the SW would otherwise handle:- *- * - {@link setupFetchInterceptor} — `window.fetch` calls to the local API.- * - {@link setupXhrInterceptor} — `XMLHttpRequest` (jQuery `$.ajax`), which- * does not go through `window.fetch`.- * - {@link setupImageInterceptor} — `<img src="api/images/…">` loads, which- * the browser's internal image loader issues- * without touching fetch or XHR.- * - {@link setupStylesheetInterceptor} — CSS-initiated subresource loads: icon pack- * fonts referenced by `@font-face` `url()` in- * injected `<style>` tags and custom theme CSS- * loaded via `<link href="api/…">`.- *- * The caller gates this on `location.protocol === "capacitor:"`, so none of it- * runs on Android or the web build.- */-export function installIosInterceptors() {- setupFetchInterceptor();- setupXhrInterceptor();- setupImageInterceptor();- setupStylesheetInterceptor();-}--export function setupFetchInterceptor() {- const originalFetch = window.fetch.bind(window);- window.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {- const urlStr = typeof input === "string" ? input- : input instanceof URL ? input.href- : (input as Request).url;- const url = new URL(urlStr, location.href);- if (url.origin === location.origin && isLocalApiRequest(url)) {- return localFetch(new Request(input, init));- }- return originalFetch(input, init);- };-}--// <img src="api/images/..."> requests are issued by the browser's internal-// image loader — they don't go through window.fetch or XMLHttpRequest, so the-// other interceptors can't catch them. On the capacitor:// scheme there is-// also no Service Worker to fall back on (WebKit only registers SWs for-// http/https origins), so the request hits Capacitor's URL scheme handler,-// which has no idea about /api/images/... and silently 404s — that's the-// broken-image placeholder users see in the iOS app.-//-// Watch the DOM for <img> elements whose src points at a local API path and-// transparently swap the src to a blob: URL backed by the SQLite worker. This-// catches images added via HTML parsing (initial document, innerHTML), via-// setAttribute/attr (jQuery, content_renderer), and via the src property.-// Setting the same src again on the same element is deduplicated so we don't-// re-fetch on idempotent re-renders.-export function setupImageInterceptor() {- const lastProcessedSrc = new WeakMap<HTMLImageElement, string>();- // Object URLs are held by the browser until explicitly revoked (the SPA- // document never unloads), so track the one currently assigned to each <img>- // and revoke it whenever the image is repointed or removed — otherwise every- // image swap leaks memory, which matters most on the constrained iOS WebView.- const blobUrls = new WeakMap<HTMLImageElement, string>();-- function matchesLocalApi(value: string): URL | null {- if (!value || value.startsWith("blob:") || value.startsWith("data:")) return null;- let abs: URL;- try {- abs = new URL(value, location.href);- } catch {- return null;- }- return (abs.origin === location.origin && isLocalApiRequest(abs)) ? abs : null;- }-- function releaseBlobUrl(img: HTMLImageElement) {- const previous = blobUrls.get(img);- if (previous) {- URL.revokeObjectURL(previous);- blobUrls.delete(img);- }- }-- async function swapToBlob(img: HTMLImageElement, originalSrc: string, absUrl: URL) {- if (lastProcessedSrc.get(img) === originalSrc) return;- lastProcessedSrc.set(img, originalSrc);-- try {- const resp = await localFetch(new Request(absUrl.toString()));- if (!resp.ok) {- lastProcessedSrc.delete(img);- return;- }- const blob = await resp.blob();- // Free the URL from a prior swap on this same element before replacing it.- releaseBlobUrl(img);- const blobUrl = URL.createObjectURL(blob);- blobUrls.set(img, blobUrl);- img.setAttribute("src", blobUrl);- } catch (err) {- console.warn("[ImageInterceptor] Failed to load", absUrl.href, err);- lastProcessedSrc.delete(img);- }- }-- function checkImage(img: HTMLImageElement) {- const src = img.getAttribute("src");- if (!src) return;- const absUrl = matchesLocalApi(src);- if (absUrl) void swapToBlob(img, src, absUrl);- }-- const observer = new MutationObserver((records) => {- for (const record of records) {- if (record.type === "attributes" && record.attributeName === "src" && record.target instanceof HTMLImageElement) {- checkImage(record.target);- } else if (record.type === "childList") {- for (const node of record.addedNodes) {- if (node instanceof HTMLImageElement) {- checkImage(node);- } else if (node instanceof Element) {- node.querySelectorAll("img").forEach((img) => checkImage(img as HTMLImageElement));- }- }- for (const node of record.removedNodes) {- if (node instanceof HTMLImageElement) {- releaseBlobUrl(node);- } else if (node instanceof Element) {- node.querySelectorAll("img").forEach((img) => releaseBlobUrl(img as HTMLImageElement));- }- }- }- }- });-- function start() {- observer.observe(document.documentElement, {- subtree: true,- childList: true,- attributes: true,- attributeFilter: ["src"]- });- document.querySelectorAll("img").forEach((img) => checkImage(img as HTMLImageElement));- }-- if (document.documentElement) {- start();- } else {- document.addEventListener("DOMContentLoaded", start, { once: true });- }-}--// jQuery $.ajax uses XMLHttpRequest, which window.fetch interception does not-// catch. On the capacitor:// scheme there is no Service Worker to route-// requests, so XHR-bound API calls would hit the native bridge and return-// something other than the expected JSON. Route them through the local worker.-export function setupXhrInterceptor() {- const OriginalXHR = window.XMLHttpRequest;-- class PatchedXHR extends OriginalXHR {- private _ti_method = "GET";- private _ti_url = "";- private _ti_intercept = false;- private _ti_headers: Record<string, string> = {};- private _ti_responseType: XMLHttpRequestResponseType = "";-- open(method: string, url: string | URL, async?: boolean, user?: string | null, password?: string | null) {- const urlStr = typeof url === "string" ? url : url.href;- const abs = new URL(urlStr, location.href);- this._ti_method = method;- this._ti_url = abs.href;- this._ti_intercept = abs.origin === location.origin && isLocalApiRequest(abs);- this._ti_headers = {};- if (!this._ti_intercept) {- return super.open(method, url as string, async ?? true, user ?? null, password ?? null);- }- }-- setRequestHeader(name: string, value: string) {- if (!this._ti_intercept) return super.setRequestHeader(name, value);- this._ti_headers[name] = value;- }-- get responseType(): XMLHttpRequestResponseType {- if (this._ti_intercept) return this._ti_responseType;- return super.responseType;- }-- set responseType(value: XMLHttpRequestResponseType) {- if (this._ti_intercept) {- this._ti_responseType = value;- return;- }- super.responseType = value;- }-- send(body?: Document | XMLHttpRequestBodyInit | null) {- if (!this._ti_intercept) return super.send(body);-- const init: RequestInit = { method: this._ti_method, headers: this._ti_headers };- if (body != null && this._ti_method !== "GET" && this._ti_method !== "HEAD") {- init.body = body as BodyInit;- }-- void (async () => {- try {- const resp = await localFetch(new Request(this._ti_url, init));- const buffer = await resp.arrayBuffer();- const text = new TextDecoder().decode(buffer);-- let parsedResponse: unknown = text;- if (this._ti_responseType === "json") {- try { parsedResponse = JSON.parse(text); } catch { parsedResponse = null; }- } else if (this._ti_responseType === "arraybuffer") {- parsedResponse = buffer;- } else if (this._ti_responseType === "blob") {- parsedResponse = new Blob([buffer], { type: resp.headers.get("content-type") ?? "" });- }-- const headerLines = [...resp.headers.entries()]- .map(([k, v]) => `${k}: ${v}`).join("\r\n");-- Object.defineProperty(this, "readyState", { value: 4, configurable: true });- Object.defineProperty(this, "status", { value: resp.status, configurable: true });- Object.defineProperty(this, "statusText", { value: resp.statusText, configurable: true });- Object.defineProperty(this, "responseURL", { value: this._ti_url, configurable: true });- Object.defineProperty(this, "responseText", {- get: () => {- if (this._ti_responseType && this._ti_responseType !== "text") {- throw new DOMException(- "responseText is only available when responseType is '' or 'text'",- "InvalidStateError"- );- }- return text;- },- configurable: true,- });- Object.defineProperty(this, "response", { value: parsedResponse, configurable: true });- Object.defineProperty(this, "getAllResponseHeaders", {- value: () => headerLines,- configurable: true,- });- Object.defineProperty(this, "getResponseHeader", {- value: (name: string) => resp.headers.get(name),- configurable: true,- });-- this.dispatchEvent(new Event("readystatechange"));- this.dispatchEvent(new ProgressEvent("load"));- this.dispatchEvent(new ProgressEvent("loadend"));- } catch {- Object.defineProperty(this, "readyState", { value: 4, configurable: true });- Object.defineProperty(this, "status", { value: 0, configurable: true });- this.dispatchEvent(new Event("readystatechange"));- this.dispatchEvent(new ProgressEvent("error"));- this.dispatchEvent(new ProgressEvent("loadend"));- }- })();- }- }-- window.XMLHttpRequest = PatchedXHR as unknown as typeof XMLHttpRequest;-}--// CSS-initiated subresource loads — @font-face src, background-image, etc. — are-// issued by the style engine, so neither the fetch/XHR interceptors nor the image-// interceptor see them. On capacitor:// they hit the native scheme handler, which-// answers unknown paths with the SPA fallback (index.html), so the load fails.-// Two shapes exist in practice:-//-// - icon pack fonts: injected <style> tags containing-// `src: url('api/attachments/download/<id>')`-// - custom themes: <link rel="stylesheet" href="api/notes/download/<id>">-//-// Rewrite both to blob: URLs backed by the SQLite worker. For a <link>, the-// fetched CSS is itself rewritten (its api url() refs become blob: URLs and its-// other relative refs are absolutized, since relative paths would resolve-// against the blob: origin and break).-//-// Fetched assets are cached by absolute URL for the lifetime of the page and-// deliberately never revoked: unlike per-note images, fonts and theme assets are-// few, shared between stylesheets, and live as long as the app.-export function setupStylesheetInterceptor() {- const CSS_URL_RE = /url\(\s*(?:"([^"]+)"|'([^']+)'|([^"')][^)\s]*))\s*\)/g;-- // absolute URL of a fetched asset -> pending blob: URL (null = failed, retryable)- const assetBlobUrls = new Map<string, Promise<string | null>>();- // <link> elements get a fresh CSS blob per processed href; these are per-element,- // so they are revoked when the link is repointed or removed.- const linkBlobUrls = new WeakMap<HTMLLinkElement, string>();- const lastProcessedHref = new WeakMap<HTMLLinkElement, string>();-- function toLocalApiUrl(ref: string, baseHref: string): URL | null {- if (!ref || ref.startsWith("blob:") || ref.startsWith("data:") || ref.startsWith("#")) return null;- let abs: URL;- try {- abs = new URL(ref, baseHref);- } catch {- return null;- }- return (abs.origin === location.origin && isLocalApiRequest(abs)) ? abs : null;- }-- function fetchAssetAsBlobUrl(abs: URL): Promise<string | null> {- let pending = assetBlobUrls.get(abs.href);- if (!pending) {- pending = (async () => {- try {- const resp = await localFetch(new Request(abs.href));- if (!resp.ok) return null;- return URL.createObjectURL(await resp.blob());- } catch (err) {- console.warn("[StylesheetInterceptor] Failed to load", abs.href, err);- return null;- }- })();- assetBlobUrls.set(abs.href, pending);- // Drop failures from the cache so a later mutation can retry them.- void pending.then((url) => {- if (!url) assetBlobUrls.delete(abs.href);- });- }- return pending;- }-- /**- * Replaces local-API `url()` references with blob: URLs. When- * `absolutizeRelative` is set (for CSS that will be served from a blob: URL),- * the remaining relative references are resolved against `baseHref` instead.- * Returns null when there is nothing to rewrite.- */- async function rewriteCssText(cssText: string, baseHref: string, absolutizeRelative = false): Promise<string | null> {- const replacements = new Map<string, string>();- for (const match of cssText.matchAll(CSS_URL_RE)) {- const ref = match[1] ?? match[2] ?? match[3];- if (replacements.has(ref)) continue;- const abs = toLocalApiUrl(ref, baseHref);- if (abs) {- const blobUrl = await fetchAssetAsBlobUrl(abs);- if (blobUrl) replacements.set(ref, blobUrl);- } else if (absolutizeRelative && !/^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(ref)) {- try {- replacements.set(ref, new URL(ref, baseHref).href);- } catch {- // leave unparseable refs alone- }- }- }- if (!replacements.size) return null;- return cssText.replace(CSS_URL_RE, (full, dquoted, squoted, unquoted) => {- const replacement = replacements.get(dquoted ?? squoted ?? unquoted);- return replacement ? `url("${replacement}")` : full;- });- }-- async function processStyle(styleEl: HTMLStyleElement) {- const css = styleEl.textContent;- if (!css || !css.includes("url(")) return;- const rewritten = await rewriteCssText(css, location.href);- // Only apply if the text was not changed underneath us while fetching.- if (rewritten !== null && styleEl.textContent === css) {- styleEl.textContent = rewritten;- }- }-- async function processLink(link: HTMLLinkElement) {- if ((link.getAttribute("rel") ?? "").toLowerCase() !== "stylesheet") return;- const href = link.getAttribute("href");- if (!href) return;- const abs = toLocalApiUrl(href, location.href);- if (!abs) return;- if (lastProcessedHref.get(link) === href) return;- lastProcessedHref.set(link, href);-- try {- const resp = await localFetch(new Request(abs.href));- if (!resp.ok) {- lastProcessedHref.delete(link);- return;- }- const css = await resp.text();- const rewritten = (await rewriteCssText(css, abs.href, true)) ?? css;- releaseLinkBlobUrl(link);- const blobUrl = URL.createObjectURL(new Blob([rewritten], { type: "text/css" }));- linkBlobUrls.set(link, blobUrl);- link.setAttribute("href", blobUrl);- } catch (err) {- console.warn("[StylesheetInterceptor] Failed to load", abs.href, err);- lastProcessedHref.delete(link);- }- }-- function releaseLinkBlobUrl(link: HTMLLinkElement) {- const previous = linkBlobUrls.get(link);- if (previous) {- URL.revokeObjectURL(previous);- linkBlobUrls.delete(link);- }- }-- function processElement(el: Element) {- if (el instanceof HTMLStyleElement) void processStyle(el);- else if (el instanceof HTMLLinkElement) void processLink(el);- }-- const observer = new MutationObserver((records) => {- for (const record of records) {- if (record.type === "attributes" && record.attributeName === "href" && record.target instanceof HTMLLinkElement) {- void processLink(record.target);- } else if (record.type === "childList") {- for (const node of record.addedNodes) {- if (node instanceof Element) {- processElement(node);- node.querySelectorAll("style, link").forEach(processElement);- } else if (node.parentElement instanceof HTMLStyleElement) {- // Replacing a style's textContent surfaces as an added Text node.- void processStyle(node.parentElement);- }- }- for (const node of record.removedNodes) {- if (node instanceof HTMLLinkElement) {- releaseLinkBlobUrl(node);- } else if (node instanceof Element) {- node.querySelectorAll("link").forEach((link) => releaseLinkBlobUrl(link as HTMLLinkElement));- }- }- }- }- });-- function start() {- observer.observe(document.documentElement, {- subtree: true,- childList: true,- attributes: true,- attributeFilter: ["href"]- });- document.querySelectorAll("style, link").forEach(processElement);- }-- if (document.documentElement) {- start();- } else {- document.addEventListener("DOMContentLoaded", start, { once: true });- }-}diff --git a/apps/standalone/src/main.spec.ts b/apps/standalone/src/main.spec.tsindex 1aaa8348d6..b3b00c8096 100644--- a/apps/standalone/src/main.spec.ts+++ b/apps/standalone/src/main.spec.ts@@ -6,13 +6,14 @@ const mocks = vi.hoisted(() => ({registerNativeHttpHandler: vi.fn(),restoreBackup: vi.fn(),downloadDatabase: vi.fn(),+ saveDatabase: vi.fn(),announceLeadership: vi.fn(),localFetch: vi.fn(),localUpload: vi.fn(),capacitorHttpHandler: vi.fn(),saveUrlToDevice: vi.fn(),requestSecurityChange: vi.fn(),- installAndroidRequestBridge: vi.fn()+ installNativeRequestBridge: vi.fn()}));// Whether this tab wins the database lock. Only the leader may start a worker;@@ -25,6 +26,7 @@ vi.mock("./local-bridge.js", () => ({registerNativeHttpHandler: mocks.registerNativeHttpHandler,restoreBackup: mocks.restoreBackup,downloadDatabase: mocks.downloadDatabase,+ saveDatabase: mocks.saveDatabase,announceLeadership: mocks.announceLeadership,localFetch: mocks.localFetch,localUpload: mocks.localUpload,@@ -39,7 +41,7 @@ vi.mock("./leader_election.js", () => ({}));vi.mock("./services/capacitor_http_handler.js", () => ({ capacitorHttpHandler: mocks.capacitorHttpHandler }));vi.mock("./services/capacitor_download.js", () => ({ saveUrlToDevice: mocks.saveUrlToDevice }));-vi.mock("./android-request-bridge.js", () => ({ installAndroidRequestBridge: mocks.installAndroidRequestBridge }));+vi.mock("./native-request-bridge.js", () => ({ installNativeRequestBridge: mocks.installNativeRequestBridge }));// Avoid pulling the entire client bundle when loadScripts() runs.vi.mock("../../client/src/index.js", () => ({}));@@ -188,21 +190,33 @@ describe("bootstrap", () => {await vi.waitFor(() => expect(win.standaloneApi?.save?.saveUrl).toBe(mocks.saveUrlToDevice));});- it("answers through the Android request bridge without a SW when the shell injects it", async () => {+ it("answers through the native request bridge without a SW when the shell provides one", async () => {const sw: ServiceWorkerLike = { controller: null, register: vi.fn(), ready: Promise.resolve() };setServiceWorker(sw);- const win = window as unknown as { triliumRequestBridge?: unknown };- win.triliumRequestBridge = {};- try {- await runBootstrap();- await vi.waitFor(() => expect(mocks.installAndroidRequestBridge).toHaveBeenCalled());- expect(mocks.startLocalServerWorker).toHaveBeenCalled();- expect(mocks.attachServiceWorkerBridge).not.toHaveBeenCalled();- expect(sw.register).not.toHaveBeenCalled();- expect(document.body.innerHTML).toBe("");- } finally {- delete win.triliumRequestBridge;- }+ const win = window as unknown as WindowWithCapacitor;+ win.Capacitor = {};+ mocks.installNativeRequestBridge.mockReturnValue(true);++ await runBootstrap();+ await vi.waitFor(() => expect(mocks.installNativeRequestBridge).toHaveBeenCalled());+ expect(mocks.startLocalServerWorker).toHaveBeenCalled();+ expect(mocks.attachServiceWorkerBridge).not.toHaveBeenCalled();+ expect(sw.register).not.toHaveBeenCalled();+ expect(document.body.innerHTML).toBe("");+ });++ it("falls back to the SW when the shell has no native request bridge, and never asks on the web", async () => {+ setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });+ await runBootstrap();+ await vi.waitFor(() => expect(mocks.attachServiceWorkerBridge).toHaveBeenCalled());+ expect(mocks.installNativeRequestBridge).not.toHaveBeenCalled();++ mocks.attachServiceWorkerBridge.mockClear();+ (window as unknown as WindowWithCapacitor).Capacitor = {};+ mocks.installNativeRequestBridge.mockReturnValue(false);+ await runBootstrap();+ await vi.waitFor(() => expect(mocks.attachServiceWorkerBridge).toHaveBeenCalled());+ expect(mocks.installNativeRequestBridge).toHaveBeenCalled();});it("registers and waits for the SW, then loads scripts once it controls", async () => {diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.tsindex b464dba062..2750dd45b2 100644--- a/apps/standalone/src/main.ts+++ b/apps/standalone/src/main.ts@@ -4,7 +4,6 @@ import {initSplashProgress, reportSplashPhase, type SplashPhase} from "../../client/src/services/splash.js";import { showErrorOverlay } from "./error-overlay.js";-import { installIosInterceptors } from "./ios-interceptors.js";import { claimLeadership } from "./leader_election.js";import { announceLeadership, attachServiceWorkerBridge, downloadDatabase, localFetch, localUpload, registerNativeHttpHandler, restoreBackup, saveDatabase, startLocalServerWorker } from "./local-bridge.js";import { createSecurityApi } from "./security_gate.js";@@ -128,17 +127,12 @@ async function bootstrap() {announceLeadership();});- // iOS Capacitor loads on the capacitor:// scheme, where WebKit rejects- // service worker registration. Fall back to in-page request interceptors- // that route API calls straight to the local SQLite worker. The Android- // shell answers them natively (TriliumRequestBridge.java) and injects- // `triliumRequestBridge` to say so; on the web the service worker does.- if (location.protocol === "capacitor:") {- installIosInterceptors();- } else if ("triliumRequestBridge" in window) {- const { installAndroidRequestBridge } = await import("./android-request-bridge.js");- installAndroidRequestBridge();- } else {+ // The mobile shells answer local API requests natively (TriliumRequestBridge on Android+ // and iOS, where WebKit rejects a service worker on capacitor://); on the web, or on an+ // Android WebView without message listeners, the service worker does.+ const answeredNatively = "Capacitor" in window+ && (await import("./native-request-bridge.js")).installNativeRequestBridge();+ if (!answeredNatively) {attachServiceWorkerBridge();await waitForServiceWorkerControl();}diff --git a/apps/standalone/src/android-request-bridge.spec.ts b/apps/standalone/src/native-request-bridge.spec.tssimilarity index 67%rename from apps/standalone/src/android-request-bridge.spec.tsrename to apps/standalone/src/native-request-bridge.spec.tsindex 3be965f335..07ab4aec9e 100644--- a/apps/standalone/src/android-request-bridge.spec.ts+++ b/apps/standalone/src/native-request-bridge.spec.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { installAndroidRequestBridge } from "./android-request-bridge.js";+import { installNativeRequestBridge } from "./native-request-bridge.js";const mocks = vi.hoisted(() => ({localFetch: vi.fn()@@ -11,8 +11,13 @@ vi.mock("./local-bridge.js", () => ({isLocalApiRequest: (url: URL) => url.pathname.startsWith("/api/") || url.pathname.startsWith("/share/")}));+interface Channel {+ postMessage: ReturnType<typeof vi.fn>;+}+interface BridgeWindow {- triliumRequestBridge?: { postMessage: ReturnType<typeof vi.fn> };+ triliumRequestBridge?: Channel;+ webkit?: { messageHandlers?: { triliumRequestBridge?: Channel } };__triliumNativeRequest?: (request: Record<string, unknown>) => void;}@@ -28,13 +33,14 @@ beforeEach(() => {afterEach(() => {delete bridgeWindow.triliumRequestBridge;+ delete bridgeWindow.webkit;delete bridgeWindow.__triliumNativeRequest;vi.restoreAllMocks();});/** Installs the bridge, forwards one request, and returns every message the page sent back. */async function forward(request: Record<string, unknown>) {- installAndroidRequestBridge();+ installNativeRequestBridge();postMessage.mockClear();bridgeWindow.__triliumNativeRequest?.({method: "GET",@@ -50,16 +56,22 @@ async function forward(request: Record<string, unknown>) {typeof message === "string" ? JSON.parse(message) : message as ArrayBuffer);}-describe("installAndroidRequestBridge", () => {- it("does nothing without the native channel, and announces readiness with it", () => {+describe("installNativeRequestBridge", () => {+ it("finds the Android or the iOS channel, and reports when there is neither", () => {delete bridgeWindow.triliumRequestBridge;- installAndroidRequestBridge();+ expect(installNativeRequestBridge()).toBe(false);expect(bridgeWindow.__triliumNativeRequest).toBeUndefined();- bridgeWindow.triliumRequestBridge = { postMessage };- installAndroidRequestBridge();+ bridgeWindow.webkit = { messageHandlers: { triliumRequestBridge: { postMessage } } };+ expect(installNativeRequestBridge()).toBe(true);expect(bridgeWindow.__triliumNativeRequest).toBeTypeOf("function");expect(postMessage).toHaveBeenCalledWith(JSON.stringify({ type: "ready" }));++ delete bridgeWindow.webkit;+ const android = vi.fn();+ bridgeWindow.triliumRequestBridge = { postMessage: android };+ expect(installNativeRequestBridge()).toBe(true);+ expect(android).toHaveBeenCalledWith(JSON.stringify({ type: "ready" }));});it("answers from localFetch with a head, id-framed binary chunks and an end", async () => {@@ -67,7 +79,7 @@ describe("installAndroidRequestBridge", () => {const body = new Uint8Array(256 * 1024 * 2 + 3).map((_, i) => i % 251);mocks.localFetch.mockResolvedValue(new Response(body, {status: 206,- headers: { "content-type": "image/png" }+ headers: { "content-type": "image/png", "content-length": "1" }}));const messages = await forward({ id: 7, url: "https://localhost/api/images/x", headers: { range: "bytes=0-" } });@@ -77,7 +89,10 @@ describe("installAndroidRequestBridge", () => {expect(request.method).toBe("GET");expect(request.headers.get("range")).toBe("bytes=0-");- expect(messages[0]).toEqual({ type: "head", id: 7, status: 206, headers: { "content-type": "image/png" } });+ expect(messages[0]).toEqual({+ type: "head", id: 7, status: 206,+ headers: { "content-type": "image/png", "content-length": String(body.length) }+ });const frames = messages.slice(1, -1) as ArrayBuffer[];expect(frames.map((frame) => frame.byteLength)).toEqual([4 + 256 * 1024, 4 + 256 * 1024, 4 + 3]);for (const frame of frames) {@@ -88,30 +103,41 @@ describe("installAndroidRequestBridge", () => {expect(messages.at(-1)).toEqual({ type: "end", id: 7 });});- it("sends base64 chunks when the WebView cannot carry ArrayBuffers, and none for an empty body", async () => {+ it("sends base64 chunks over the iOS channel, and none for an empty body", async () => {+ delete bridgeWindow.triliumRequestBridge;+ bridgeWindow.webkit = { messageHandlers: { triliumRequestBridge: { postMessage } } };+mocks.localFetch.mockResolvedValue(new Response("hello"));- const messages = await forward({ id: 3, url: "https://localhost/api/notes", binary: false });+ const messages = await forward({ id: 3, url: "capacitor://localhost/api/notes", binary: false });expect(messages.slice(1)).toEqual([{ type: "chunk", id: 3, data: btoa("hello") },{ type: "end", id: 3 }]);mocks.localFetch.mockResolvedValue(new Response(null, { status: 204 }));- const empty = await forward({ id: 4, url: "https://localhost/api/notes" });+ const empty = await forward({ id: 4, url: "capacitor://localhost/api/notes", binary: false });expect(empty.map((message) => (message as { type: string }).type)).toEqual(["head", "end"]);});- it("turns a redirect into a page that navigates, since WebResourceResponse rejects 3xx", async () => {+ it("leaves the length of a HEAD answer to the worker", async () => {+ mocks.localFetch.mockResolvedValue(new Response(null, { headers: { "content-length": "42" } }));+ const messages = await forward({ id: 2, method: "HEAD", url: "https://localhost/api/notes" });++ expect((messages[0] as { headers: Record<string, string> }).headers["content-length"]).toBe("42");+ });++ it("turns a redirect into a page that navigates, since neither native response carries a 3xx", async () => {mocks.localFetch.mockResolvedValue(new Response(null, {status: 302,headers: { location: "../share/?a=1&b=\"2\"" }}));const messages = await forward({ id: 1, url: "https://localhost/share/x", binary: false });+ const html = atob((messages[1] as { data: string }).data);expect(messages[0]).toEqual({- type: "head", id: 1, status: 200, headers: { "content-type": "text/html; charset=utf-8" }+ type: "head", id: 1, status: 200,+ headers: { "content-type": "text/html; charset=utf-8", "content-length": String(html.length) }});- const html = atob((messages[1] as { data: string }).data);expect(html).toBe("<!DOCTYPE html><meta http-equiv=\"refresh\" content=\"0;url=../share/?a=1&b="2"\">");});diff --git a/apps/standalone/src/android-request-bridge.ts b/apps/standalone/src/native-request-bridge.tssimilarity index 56%rename from apps/standalone/src/android-request-bridge.tsrename to apps/standalone/src/native-request-bridge.tsindex 02ad2ba28f..674c42d451 100644--- a/apps/standalone/src/android-request-bridge.ts+++ b/apps/standalone/src/native-request-bridge.ts@@ -2,27 +2,32 @@ import { isLocalApiRequest, localFetch } from "./local-bridge.js";import { toBase64 } from "./services/capacitor_download.js";/**- * Page side of `TriliumRequestBridge.java`, which answers local API requests in the Android shell- * in place of the service worker.+ * Page side of the mobile shells' native request bridges, which answer local API requests in+ * place of a service worker: `TriliumRequestBridge.java` on Android and+ * `TriliumRequestBridge.swift` on iOS.*- * `WebViewClient.shouldInterceptRequest` sees every request the WebView issues, whichever part of- * the engine issued it (`fetch`, XHR, `<img>`, `@font-face`, iframes, media). For a local API path- * the native side calls `window.__triliumNativeRequest()`, this module answers it from- * `localFetch()`, and the reply travels back over the `window.triliumRequestBridge` message- * channel:+ * The native side sees every request the WebView issues, whichever part of the engine issued it+ * (`fetch`, XHR, `<img>`, `@font-face`, iframes, media): `WebViewClient.shouldInterceptRequest`+ * on Android, the `WKURLSchemeHandler` of `capacitor://` on iOS. For a local API path it calls+ * `window.__triliumNativeRequest()`, this module answers it from `localFetch()`, and the reply+ * travels back over the native channel as JSON strings:** - `{"type":"head","id","status","headers"}`, then the body as ArrayBuffer frames, each a 4-byte- * big-endian request id followed by the bytes — or, when the WebView cannot carry ArrayBuffers,- * `{"type":"chunk","id","data"}` with the bytes in base64.+ * big-endian request id followed by the bytes, or as `{"type":"chunk","id","data"}` with the+ * bytes in base64 when the channel cannot carry ArrayBuffers (iOS, older Android WebViews).* - `{"type":"end","id"}` once the body is complete, or `{"type":"error","id","message"}`.*- * `shouldInterceptRequest` exposes no request body, so the native side forwards only GET and HEAD.+ * Android's `shouldInterceptRequest` exposes no request body, so both platforms forward only GET+ * and HEAD; a request with a body goes through `standaloneApi.localFetch`.+ *+ * Returns whether a native channel was found; without one the page registers its service worker.*/-export function installAndroidRequestBridge() {+export function installNativeRequestBridge(): boolean {const bridgeWindow = window as RequestBridgeWindow;- const channel = bridgeWindow.triliumRequestBridge;+ const channel = bridgeWindow.triliumRequestBridge+ ?? bridgeWindow.webkit?.messageHandlers?.triliumRequestBridge;if (!channel) {- return;+ return false;}bridgeWindow.__triliumNativeRequest = (request) => {@@ -30,15 +35,16 @@ export function installAndroidRequestBridge() {};// The native side holds every request it intercepted until this arrives.channel.postMessage(JSON.stringify({ type: "ready" }));+ return true;}-/** Request forwarded by `TriliumRequestBridge.java`. */+/** Request forwarded by the native bridge. */interface NativeRequest {id: number;method: string;url: string;headers: Record<string, string>;- /** Whether the WebView carries ArrayBuffer messages; base64 chunks are sent otherwise. */+ /** Whether the channel carries ArrayBuffer messages; base64 chunks are sent otherwise. */binary: boolean;}@@ -47,7 +53,10 @@ interface RequestChannel {}interface RequestBridgeWindow {+ /** Android: the `WebMessageListener` that `TriliumRequestBridge.java` injects. */triliumRequestBridge?: RequestChannel;+ /** iOS: the script message handler that `TriliumRequestBridge.swift` registers. */+ webkit?: { messageHandlers?: { triliumRequestBridge?: RequestChannel } };__triliumNativeRequest?: (request: NativeRequest) => void;}@@ -63,7 +72,7 @@ async function answer(channel: RequestChannel, request: NativeRequest) {try {const url = new URL(request.url, location.href);if (!isLocalApiRequest(url)) {- // The prefix list in TriliumRequestBridge.java must match `isLocalApiRequest()`.+ // The native prefix lists must match `isLocalApiRequest()`.throw new Error(`Path is not routed to the local worker: ${url.pathname}`);}@@ -73,7 +82,13 @@ async function answer(channel: RequestChannel, request: NativeRequest) {})));const body = new Uint8Array(await response.arrayBuffer());- send({ type: "head", status: response.status, headers: Object.fromEntries(response.headers) });+ const headers = Object.fromEntries(response.headers);+ if (request.method !== "HEAD") {+ // The worker's value can count characters rather than bytes; WebKit's media loader+ // needs the exact length.+ headers["content-length"] = String(body.length);+ }+ send({ type: "head", status: response.status, headers });for (let offset = 0; offset < body.length; offset += CHUNK_SIZE) {const chunk = body.subarray(offset, offset + CHUNK_SIZE);if (request.binary) {@@ -90,9 +105,10 @@ async function answer(channel: RequestChannel, request: NativeRequest) {}/**- * `WebResourceResponse` rejects 3xx statuses, so a redirect (the share pages issue them) becomes a- * page that navigates to its target. A relative target resolves against the request URL, as it- * would for a real redirect.+ * Neither native response type carries a 3xx (`WebResourceResponse` rejects one, a+ * `WKURLSchemeTask` cannot redirect), so a redirect (the share pages issue them) becomes a page+ * that navigates to its target. A relative target resolves against the request URL, as it would+ * for a real redirect.*/function toNativeResponse(response: Response): Response {const location = response.headers.get("location");diff --git a/apps/standalone/src/services/capacitor_download.ts b/apps/standalone/src/services/capacitor_download.tsindex 843e1a8310..37c25bed0f 100644--- a/apps/standalone/src/services/capacitor_download.ts+++ b/apps/standalone/src/services/capacitor_download.ts@@ -3,9 +3,8 @@ import type { StandaloneSaveResult } from "@triliumnext/commons";/*** Saving a download inside the Capacitor shell, which has no download manager of its own: the* WebView drops a response that says `Content-Disposition: attachment`, silently. The page does- * the whole job instead — fetch (still routed to the worker by the service worker on Android and- * by the iOS interceptors on `capacitor://`), write to the app's storage, hand the file to the- * system share sheet.+ * the whole job instead — fetch (still routed to the worker by the shell's native request bridge),+ * write to the app's storage, hand the file to the system share sheet.** A database backup takes the same last step through {@link saveChunksToDevice}, reading its bytes* straight off the local worker rather than out of a response.diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.tsindex 9a0b3d41d8..563fd72c06 100644--- a/apps/standalone/src/sw.ts+++ b/apps/standalone/src/sw.ts@@ -426,7 +426,7 @@ self.addEventListener("fetch", (event) => {// On the Capacitor custom URL scheme (capacitor://) the WebView serves app assets// through its native URLSchemeHandler, which a service worker cannot reach via fetch() —// let those requests fall through to the WebView's own loader. In practice the SW is only- // registered on http/https origins (main.ts uses a fetch/XHR interceptor instead of a SW+ // registered on http/https origins (main.ts installs the native request bridge instead// on capacitor://), so this is a defensive guard rather than a hot path.if (self.location.protocol === "capacitor:") {return;diff --git a/packages/commons/src/lib/standalone_api_interface.ts b/packages/commons/src/lib/standalone_api_interface.tsindex 76b622282b..4c4fdf8538 100644--- a/packages/commons/src/lib/standalone_api_interface.ts+++ b/packages/commons/src/lib/standalone_api_interface.ts@@ -116,8 +116,8 @@ export interface StandaloneSaveApi {** The Capacitor WebView has no download manager: a navigation that resolves to an* `attachment` response is dropped, silently. So the bytes are fetched by the page instead —- * where the service worker (Android) or the iOS interceptors still route them to the local- * worker — written to the app's cache directory, and handed to the share sheet, which is+ * where the shell's native request bridge still routes them to the local worker — written+ * to the app's cache directory, and handed to the share sheet, which is* where the user picks what the file becomes: a file in Downloads, a Drive upload, a mail* attachment.*