Skip to content

Build your personal knowledge base with Trilium Notes

refactor(standalone): remove the dead capacitor:// scheme path

Elian Doranae763ad43fb7
diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.ts
index cc07834622..7f57a24f23 100644
--- a/apps/standalone/src/local-bridge.spec.ts
+++ b/apps/standalone/src/local-bridge.spec.ts
@@ -281,53 +281,3 @@ describe("pending request rejection", () => {
expect(() => worker.onmessage?.({ data: { type: "HTTP_REQUEST", id: "1", request: {} } })).not.toThrow();
});
});
-
-describe("localFetch", () => {
- it("posts a GET LOCAL_REQUEST with no body transfer and builds a Response from the reply", async () => {
- const bridge = await freshBridge();
- const promise = bridge.localFetch(new Request("http://x/api/notes"));
-
- const worker = lastWorker();
- await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(
- expect.objectContaining({ type: "LOCAL_REQUEST", request: expect.objectContaining({ method: "GET", body: null }) }),
- []
- ));
-
- const posted = worker.postMessage.mock.calls.at(-1)?.[0] as { id: string };
- const body = new TextEncoder().encode("hello").buffer;
- worker.onmessage?.({ data: { type: "LOCAL_RESPONSE", id: posted.id, response: { status: 201, headers: { "content-type": "text/plain" }, body } } });
-
- const res = await promise;
- expect(res.status).toBe(201);
- expect(res.headers.get("content-type")).toBe("text/plain");
- expect(await res.text()).toBe("hello");
- });
-
- it("transfers the body for non-GET requests and defaults a falsy status to 200", async () => {
- const bridge = await freshBridge();
- const promise = bridge.localFetch(new Request("http://x/api/notes", { method: "POST", body: "payload" }));
-
- const worker = lastWorker();
- await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(
- expect.objectContaining({ type: "LOCAL_REQUEST", request: expect.objectContaining({ method: "POST" }) }),
- [expect.any(ArrayBuffer)]
- ));
-
- const posted = worker.postMessage.mock.calls.at(-1)?.[0] as { id: string };
- worker.onmessage?.({ data: { type: "LOCAL_RESPONSE", id: posted.id, response: { status: 0, headers: {} } } });
-
- const res = await promise;
- expect(res.status).toBe(200);
- });
-});
-
-describe("isLocalApiRequest", () => {
- it("matches only the local API prefixes", async () => {
- const bridge = await freshBridge();
- for (const path of ["/bootstrap", "/api/notes", "/sync/changed", "/search/q"]) {
- expect(bridge.isLocalApiRequest(new URL(`http://x${path}`))).toBe(true);
- }
- expect(bridge.isLocalApiRequest(new URL("http://x/app.js"))).toBe(false);
- expect(bridge.isLocalApiRequest(new URL("http://x/"))).toBe(false);
- });
-});
diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.ts
index 1c039b1a68..087cb9acf5 100644
--- a/apps/standalone/src/local-bridge.ts
+++ b/apps/standalone/src/local-bridge.ts
@@ -2,39 +2,6 @@ import LocalServerWorker from "./local-server-worker?worker";
let localWorker: Worker | null = null;
const pending = new Map();
-const LOCAL_API_PREFIXES = ["/bootstrap", "/api/", "/sync/", "/search/"];
-
-export function isLocalApiRequest(url: URL): boolean {
- return LOCAL_API_PREFIXES.some(p => url.pathname.startsWith(p));
-}
-
-export async function localFetch(request: Request): Promise<Response> {
- startLocalServerWorker();
-
- const id = Math.random().toString(36).slice(2);
- const headersObj: Record<string, string> = {};
- for (const [k, v] of request.headers.entries()) headersObj[k] = v;
-
- const body = (request.method === "GET" || request.method === "HEAD")
- ? null
- : await request.arrayBuffer();
-
- const response = await new Promise<{ status: number; headers: Record<string, string>; body?: ArrayBuffer }>((resolve, reject) => {
- pending.set(id, { resolve, reject });
- localWorker!.postMessage({
- type: "LOCAL_REQUEST",
- id,
- request: { url: request.url, method: request.method, headers: headersObj, body }
- }, body ? [body] : []);
- });
-
- const respHeaders = new Headers();
- if (response.headers) {
- for (const [k, v] of Object.entries(response.headers)) respHeaders.set(k, v);
- }
- return new Response(response.body ?? null, { status: response.status || 200, headers: respHeaders });
-}
-
/**
* Handler for outbound HTTP requests from the worker.
* When registered, the worker's BridgedRequestProvider sends HTTP_REQUEST
diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.ts
index 1a757ffd66..8d28f69ca4 100644
--- a/apps/standalone/src/main.ts
+++ b/apps/standalone/src/main.ts
@@ -1,4 +1,4 @@
-import { attachServiceWorkerBridge, startLocalServerWorker, localFetch, isLocalApiRequest, registerNativeHttpHandler } from "./local-bridge.js";
+import { attachServiceWorkerBridge, registerNativeHttpHandler, startLocalServerWorker } from "./local-bridge.js";
async function waitForServiceWorkerControl(): Promise<void> {
if (!("serviceWorker" in navigator) || !navigator.serviceWorker) {
@@ -39,220 +39,6 @@ async function waitForServiceWorkerControl(): Promise<void> {
throw new Error("Reloading for service worker activation");
}
-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
-// interceptors above 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.
-function setupImageInterceptor() {
- const lastProcessedSrc = 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;
- }
-
- 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();
- img.setAttribute("src", URL.createObjectURL(blob));
- } 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) 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));
- }
- }
- }
- }
- });
-
- 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.
-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 as any);
-
- 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;
- }
-
- (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 (err) {
- 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;
-}
-
async function bootstrap() {
/* fixes https://github.com/webpack/webpack/issues/10035 */
window.global = globalThis;
@@ -268,19 +54,12 @@ async function bootstrap() {
// 1) Start local worker ASAP (so /bootstrap is fast)
startLocalServerWorker();
- // iOS Capacitor loads on capacitor:// scheme — WebKit rejects service worker
- // registration for non-HTTP/HTTPS origins. Use a fetch interceptor instead
- // to route API calls directly to the local SQLite worker. XHR must also be
- // patched because jQuery $.ajax (used by the client's server helpers) does
- // not go through window.fetch.
- if (location.protocol === "capacitor:") {
- setupFetchInterceptor();
- setupXhrInterceptor();
- setupImageInterceptor();
- } else {
- attachServiceWorkerBridge();
- await waitForServiceWorkerControl();
- }
+ // Route the client's API/sync calls to the local SQLite worker through the
+ // service worker. The mobile app runs on the https scheme (iosScheme in
+ // capacitor.config.json), so WebKit registers the SW normally — there is no
+ // capacitor:// origin to special-case.
+ attachServiceWorkerBridge();
+ await waitForServiceWorkerControl();
await loadScripts();
} catch (err) {
diff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.ts
index b29da63141..58abfd3f70 100644
--- a/apps/standalone/src/sw.spec.ts
+++ b/apps/standalone/src/sw.spec.ts
@@ -144,16 +144,6 @@ describe("fetch routing", () => {
expect(fetch).toHaveBeenCalled();
});
- it("bypasses SW routing on the capacitor:// scheme (assets load via the WebView)", async () => {
- // On a Capacitor custom scheme the WebView serves assets natively and the SW cannot
- // fetch() them, so it must not intercept — no respondWith, no SW-issued fetch.
- vi.stubGlobal("location", { origin, protocol: "capacitor:" });
- const handlers = await loadSw();
- const event = fetchEvent(`${origin}/app.js`);
- handlers.fetch(event);
- expect(event._response).toBeUndefined();
- expect(fetch).not.toHaveBeenCalled();
- });
});
describe("forwardToClientLocalServer", () => {
diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.ts
index f2ebfb9b61..48fb617882 100644
--- a/apps/standalone/src/sw.ts
+++ b/apps/standalone/src/sw.ts
@@ -192,15 +192,6 @@ self.addEventListener("fetch", (event) => {
return;
}
- // 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
- // on capacitor://), so this is a defensive guard rather than a hot path.
- if (self.location.protocol === "capacitor:") {
- return;
- }
-
// HTML files: network-first to ensure updates are reflected immediately
if (event.request.mode === "navigate" || url.pathname.endsWith(".html")) {
event.respondWith(networkFirst(event.request));