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/ios): start app on ios
AndreeaCorlaci969690e5bf76
diff --git a/apps/client-standalone/src/local-bridge.ts b/apps/client-standalone/src/local-bridge.tsindex 8d13d1f7ad..9bdeb016bc 100644--- a/apps/client-standalone/src/local-bridge.ts+++ b/apps/client-standalone/src/local-bridge.ts@@ -2,6 +2,39 @@ 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 });+}+function showFatalErrorDialog(message: string) {alert(message);}diff --git a/apps/client-standalone/src/main.ts b/apps/client-standalone/src/main.tsindex b7e36101d5..8b44b5e88e 100644--- a/apps/client-standalone/src/main.ts+++ b/apps/client-standalone/src/main.ts@@ -1,4 +1,4 @@-import { attachServiceWorkerBridge, startLocalServerWorker } from "./local-bridge.js";+import { attachServiceWorkerBridge, startLocalServerWorker, localFetch, isLocalApiRequest } from "./local-bridge.js";async function waitForServiceWorkerControl(): Promise<void> {if (!("serviceWorker" in navigator) || !navigator.serviceWorker) {@@ -18,7 +18,6 @@ async function waitForServiceWorkerControl(): Promise<void> {);}- // If already controlling, we're goodif (navigator.serviceWorker.controller) {console.log("[Bootstrap] Service worker already controlling");return;@@ -26,52 +25,55 @@ async function waitForServiceWorkerControl(): Promise<void> {console.log("[Bootstrap] Waiting for service worker to take control...");- // Register service workerawait navigator.serviceWorker.register("./sw.js", { scope: "/" });-- // Wait for it to be ready (installed + activated)await navigator.serviceWorker.ready;- // Check if we're now controllingif (navigator.serviceWorker.controller) {console.log("[Bootstrap] Service worker now controlling");return;}- // If not controlling yet, we need to reload the page for SW to take control- // This is standard PWA behavior on first installconsole.log("[Bootstrap] Service worker installed but not controlling yet - reloading page");-- // Wait a tiny bit for SW to fully activateawait new Promise(resolve => setTimeout(resolve, 100));-- // Reload to let SW take controlwindow.location.reload();-- // Throw to stop execution (page will reload)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);+ };++}+async function bootstrap() {/* fixes https://github.com/webpack/webpack/issues/10035 */window.global = globalThis;try {- // 1) Start local worker ASAP (so /bootstrap is fast)startLocalServerWorker();- // 2) Bridge SW -> local worker- attachServiceWorkerBridge();-- // 3) Wait for service worker to control the page (may reload on first install)- await waitForServiceWorkerControl();+ // 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.+ if (location.protocol === "capacitor:") {+ setupFetchInterceptor();+ } else {+ attachServiceWorkerBridge();+ await waitForServiceWorkerControl();+ }await loadScripts();} catch (err) {- // If error is from reload, it will stop here (page reloads)- // Otherwise, show error to userif (err instanceof Error && err.message.includes("Reloading")) {- // Page is reloading, do nothingreturn;}diff --git a/apps/client-standalone/src/sw.ts b/apps/client-standalone/src/sw.tsindex 4e5b5831f7..e48a0e2093 100644--- a/apps/client-standalone/src/sw.ts+++ b/apps/client-standalone/src/sw.ts@@ -179,6 +179,13 @@ self.addEventListener("fetch", (event) => {return;}+ // In dev mode, let the browser handle all non-API requests directly.+ // Custom URL scheme handlers (e.g. capacitor://) are not accessible via+ // fetch() from within a service worker context on iOS WKWebView.+ if (isDev) {+ return;+ }+// HTML files: network-first to ensure updates are reflected immediatelyif (event.request.mode === "navigate" || url.pathname.endsWith(".html")) {event.respondWith(networkFirst(event.request));diff --git a/apps/mobile/capacitor.config.json b/apps/mobile/capacitor.config.jsonindex 82e4835e38..5a2ac43394 100644--- a/apps/mobile/capacitor.config.json+++ b/apps/mobile/capacitor.config.json@@ -4,7 +4,11 @@"webDir": "../client-standalone/dist","server": {"androidScheme": "https",+ "iosScheme": "https","hostname": "localhost"},+ "ios": {+ "limitsNavigationsToAppBoundDomains": true+ },"plugins": {}}diff --git a/apps/mobile/ios/App/App.xcodeproj/project.pbxproj b/apps/mobile/ios/App/App.xcodeproj/project.pbxprojindex 97bd367d30..ebb11096ed 100644--- a/apps/mobile/ios/App/App.xcodeproj/project.pbxproj+++ b/apps/mobile/ios/App/App.xcodeproj/project.pbxproj@@ -15,6 +15,7 @@504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; };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 */; };/* End PBXBuildFile section *//* Begin PBXFileReference section */@@ -27,6 +28,7 @@504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };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>"; };958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; };/* End PBXFileReference section */@@ -62,6 +64,7 @@504EC3061FED79650016851F /* App */ = {isa = PBXGroup;children = (+ 6DB328352F98030500787D66 /* ViewController.swift */,50379B222058CBB4000EE86E /* capacitor.config.json */,504EC3071FED79650016851F /* AppDelegate.swift */,504EC30B1FED79650016851F /* Main.storyboard */,@@ -155,6 +158,7 @@isa = PBXSourcesBuildPhase;buildActionMask = 2147483647;files = (+ 6DB328362F98030500787D66 /* ViewController.swift in Sources */,504EC3081FED79650016851F /* AppDelegate.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;@@ -297,6 +301,7 @@ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;CODE_SIGN_STYLE = Automatic;CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = KDY6LYMAKA;INFOPLIST_FILE = App/Info.plist;IPHONEOS_DEPLOYMENT_TARGET = 15.0;LD_RUNPATH_SEARCH_PATHS = (@@ -319,6 +324,7 @@ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;CODE_SIGN_STYLE = Automatic;CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = KDY6LYMAKA;INFOPLIST_FILE = App/Info.plist;IPHONEOS_DEPLOYMENT_TARGET = 15.0;LD_RUNPATH_SEARCH_PATHS = (diff --git a/apps/mobile/ios/App/App/Base.lproj/Main.storyboard b/apps/mobile/ios/App/App/Base.lproj/Main.storyboardindex b44df7be8f..27a55681f6 100644--- a/apps/mobile/ios/App/App/Base.lproj/Main.storyboard+++ b/apps/mobile/ios/App/App/Base.lproj/Main.storyboard@@ -11,7 +11,7 @@<!--Bridge View Controller--><scene sceneID="tne-QT-ifu"><objects>- <viewController id="BYZ-38-t0r" customClass="CAPBridgeViewController" customModule="Capacitor" sceneMemberID="viewController"/>+ <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="App" sceneMemberID="viewController"/><placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/></objects></scene>diff --git a/apps/mobile/ios/App/App/Info.plist b/apps/mobile/ios/App/App/Info.plistindex e39340ff01..86e374940b 100644--- a/apps/mobile/ios/App/App/Info.plist+++ b/apps/mobile/ios/App/App/Info.plist@@ -47,5 +47,9 @@</array><key>UIViewControllerBasedStatusBarAppearance</key><true/>+ <key>WKAppBoundDomains</key>+ <array>+ <string>localhost</string>+ </array></dict></plist>diff --git a/apps/mobile/ios/App/App/ViewController.swift b/apps/mobile/ios/App/App/ViewController.swiftnew file mode 100644index 0000000000..5cd7696bc5--- /dev/null+++ b/apps/mobile/ios/App/App/ViewController.swift@@ -0,0 +1,4 @@+import UIKit+import Capacitor++class ViewController: CAPBridgeViewController {}