fix(native): Prettier on the native client files, rate-limit e2e requests in sequence

Formats the files the client formatting gate listed, and NATIVE-E2E-005 sends its twenty exchange attempts one after another: all at once they reset the test server's connections.
This commit is contained in:
Maurice
2026-10-25 17:41:32 +01:00
parent 99c1a2d6c7
commit 6f3c051c7c
30 changed files with 993 additions and 858 deletions
+56 -48
View File
@@ -1,71 +1,79 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { sha256 } from '@noble/hashes/sha2'
import { bytesToHex } from '@noble/hashes/utils'
import { BrowserSignInCancelled, createHandoffSecret, handoffUrl, requestHandoffCode, signInThroughBrowser } from './browserSignIn'
import { TrekShell } from './trekShell'
import { nativeAuthApi } from '../api/nativeAuth'
import { sha256 } from '@noble/hashes/sha2';
import { bytesToHex } from '@noble/hashes/utils';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { nativeAuthApi } from '../api/nativeAuth';
import {
BrowserSignInCancelled,
createHandoffSecret,
handoffUrl,
requestHandoffCode,
signInThroughBrowser,
} from './browserSignIn';
import { TrekShell } from './trekShell';
vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } }))
vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } }))
vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } }));
vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } }));
beforeEach(() => {
vi.mocked(TrekShell.authenticate).mockReset()
vi.mocked(nativeAuthApi.exchange).mockReset().mockResolvedValue()
})
vi.mocked(TrekShell.authenticate).mockReset();
vi.mocked(nativeAuthApi.exchange).mockReset().mockResolvedValue();
});
describe('createHandoffSecret', () => {
it('pairs a fresh 64-character verifier with the hex sha256 the server checks against', () => {
const { verifier, challenge } = createHandoffSecret()
expect(verifier).toMatch(/^[0-9a-f]{64}$/)
expect(challenge).toBe(bytesToHex(sha256(new TextEncoder().encode(verifier))))
expect(createHandoffSecret().verifier).not.toBe(verifier)
})
})
const { verifier, challenge } = createHandoffSecret();
expect(verifier).toMatch(/^[0-9a-f]{64}$/);
expect(challenge).toBe(bytesToHex(sha256(new TextEncoder().encode(verifier))));
expect(createHandoffSecret().verifier).not.toBe(verifier);
});
});
describe('requestHandoffCode', () => {
it('asks the server for the one-time code bound to the challenge', async () => {
vi.mocked(nativeAuthApi.handoff).mockResolvedValue({ code: 'c-1' })
await expect(requestHandoffCode('ab'.repeat(32))).resolves.toBe('c-1')
expect(nativeAuthApi.handoff).toHaveBeenCalledWith('ab'.repeat(32))
})
})
vi.mocked(nativeAuthApi.handoff).mockResolvedValue({ code: 'c-1' });
await expect(requestHandoffCode('ab'.repeat(32))).resolves.toBe('c-1');
expect(nativeAuthApi.handoff).toHaveBeenCalledWith('ab'.repeat(32));
});
});
describe('handoffUrl', () => {
it('points at the hand-off page with the challenge and an optional start', () => {
expect(handoffUrl('https://trek.example.com', 'c')).toBe('https://trek.example.com/native-handoff?challenge=c')
expect(handoffUrl('https://trek.example.com', 'c', 'oidc')).toBe('https://trek.example.com/native-handoff?challenge=c&start=oidc')
})
})
expect(handoffUrl('https://trek.example.com', 'c')).toBe('https://trek.example.com/native-handoff?challenge=c');
expect(handoffUrl('https://trek.example.com', 'c', 'oidc')).toBe(
'https://trek.example.com/native-handoff?challenge=c&start=oidc'
);
});
});
describe('signInThroughBrowser', () => {
it('opens the hand-off page and redeems the returned code with the verifier', async () => {
vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth?code=abc' })
vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth?code=abc' });
await signInThroughBrowser('oidc')
await signInThroughBrowser('oidc');
const opened = new URL(vi.mocked(TrekShell.authenticate).mock.calls[0][0].url)
expect(opened.pathname).toBe('/native-handoff')
expect(opened.searchParams.get('start')).toBe('oidc')
expect(vi.mocked(TrekShell.authenticate).mock.calls[0][0].callbackScheme).toBe('com.liketrek.trek')
const { code, verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0]
expect(code).toBe('abc')
expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(opened.searchParams.get('challenge'))
})
const opened = new URL(vi.mocked(TrekShell.authenticate).mock.calls[0][0].url);
expect(opened.pathname).toBe('/native-handoff');
expect(opened.searchParams.get('start')).toBe('oidc');
expect(vi.mocked(TrekShell.authenticate).mock.calls[0][0].callbackScheme).toBe('com.liketrek.trek');
const { code, verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0];
expect(code).toBe('abc');
expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(opened.searchParams.get('challenge'));
});
it('turns a closed browser into BrowserSignInCancelled', async () => {
vi.mocked(TrekShell.authenticate).mockRejectedValue(Object.assign(new Error('closed'), { code: 'CANCELLED' }))
await expect(signInThroughBrowser()).rejects.toBeInstanceOf(BrowserSignInCancelled)
expect(nativeAuthApi.exchange).not.toHaveBeenCalled()
})
vi.mocked(TrekShell.authenticate).mockRejectedValue(Object.assign(new Error('closed'), { code: 'CANCELLED' }));
await expect(signInThroughBrowser()).rejects.toBeInstanceOf(BrowserSignInCancelled);
expect(nativeAuthApi.exchange).not.toHaveBeenCalled();
});
it('passes other failures on', async () => {
vi.mocked(TrekShell.authenticate).mockRejectedValue(new Error('no browser'))
await expect(signInThroughBrowser()).rejects.toThrow('no browser')
})
vi.mocked(TrekShell.authenticate).mockRejectedValue(new Error('no browser'));
await expect(signInThroughBrowser()).rejects.toThrow('no browser');
});
it('refuses a return without a code', async () => {
vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth' })
await expect(signInThroughBrowser()).rejects.toThrow('without a sign-in code')
expect(nativeAuthApi.exchange).not.toHaveBeenCalled()
})
})
vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth' });
await expect(signInThroughBrowser()).rejects.toThrow('without a sign-in code');
expect(nativeAuthApi.exchange).not.toHaveBeenCalled();
});
});
+27 -27
View File
@@ -1,7 +1,7 @@
import { sha256 } from '@noble/hashes/sha2'
import { bytesToHex } from '@noble/hashes/utils'
import { nativeAuthApi } from '../api/nativeAuth'
import { APP_URL_SCHEME, TrekShell } from './trekShell'
import { sha256 } from '@noble/hashes/sha2';
import { bytesToHex } from '@noble/hashes/utils';
import { nativeAuthApi } from '../api/nativeAuth';
import { APP_URL_SCHEME, TrekShell } from './trekShell';
/**
* SSO and passkeys cannot run inside the app's WebView: identity providers
@@ -17,51 +17,51 @@ import { APP_URL_SCHEME, TrekShell } from './trekShell'
* home networks reach theirs.
*/
export const HANDOFF_PATH = '/native-handoff'
export const HANDOFF_PATH = '/native-handoff';
export type BrowserSignInStart = 'oidc'
export type BrowserSignInStart = 'oidc';
export function createHandoffSecret(): { verifier: string; challenge: string } {
const bytes = crypto.getRandomValues(new Uint8Array(32))
const verifier = bytesToHex(bytes)
return { verifier, challenge: bytesToHex(sha256(new TextEncoder().encode(verifier))) }
const bytes = crypto.getRandomValues(new Uint8Array(32));
const verifier = bytesToHex(bytes);
return { verifier, challenge: bytesToHex(sha256(new TextEncoder().encode(verifier))) };
}
export function handoffUrl(origin: string, challenge: string, start?: BrowserSignInStart, invite?: string): string {
const url = new URL(HANDOFF_PATH, origin)
url.searchParams.set('challenge', challenge)
if (start) url.searchParams.set('start', start)
if (invite) url.searchParams.set('invite', invite)
return url.href
const url = new URL(HANDOFF_PATH, origin);
url.searchParams.set('challenge', challenge);
if (start) url.searchParams.set('start', start);
if (invite) url.searchParams.set('invite', invite);
return url.href;
}
/** The browser side: trade the signed-in session for a one-time code bound to `challenge`. */
export async function requestHandoffCode(challenge: string): Promise<string> {
const { code } = await nativeAuthApi.handoff(challenge)
return code
const { code } = await nativeAuthApi.handoff(challenge);
return code;
}
export class BrowserSignInCancelled extends Error {
constructor() {
super('Sign-in cancelled')
this.name = 'BrowserSignInCancelled'
super('Sign-in cancelled');
this.name = 'BrowserSignInCancelled';
}
}
/** Resolves once the WebView holds a session cookie of its own. */
export async function signInThroughBrowser(start?: BrowserSignInStart, invite?: string): Promise<void> {
const { verifier, challenge } = createHandoffSecret()
let returned: string
const { verifier, challenge } = createHandoffSecret();
let returned: string;
try {
;({ url: returned } = await TrekShell.authenticate({
({ url: returned } = await TrekShell.authenticate({
url: handoffUrl(window.location.origin, challenge, start, invite),
callbackScheme: APP_URL_SCHEME,
}))
}));
} catch (err) {
if ((err as { code?: string })?.code === 'CANCELLED') throw new BrowserSignInCancelled()
throw err
if ((err as { code?: string })?.code === 'CANCELLED') throw new BrowserSignInCancelled();
throw err;
}
const code = new URL(returned).searchParams.get('code')
if (!code) throw new Error('The browser returned without a sign-in code')
await nativeAuthApi.exchange({ code, verifier })
const code = new URL(returned).searchParams.get('code');
if (!code) throw new Error('The browser returned without a sign-in code');
await nativeAuthApi.exchange({ code, verifier });
}
+30 -28
View File
@@ -1,42 +1,44 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Haptics, NotificationType } from '@capacitor/haptics'
import { toastHaptic } from './haptics'
import { isNativeApp } from './platform'
import { Haptics, NotificationType } from '@capacitor/haptics';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { toastHaptic } from './haptics';
import { isNativeApp } from './platform';
vi.mock('@capacitor/haptics', () => ({
Haptics: { notification: vi.fn() },
NotificationType: { Success: 'SUCCESS', Warning: 'WARNING', Error: 'ERROR' },
}))
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }))
}));
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
beforeEach(() => {
vi.mocked(Haptics.notification).mockReset().mockResolvedValue()
vi.mocked(isNativeApp).mockReturnValue(true)
})
vi.mocked(Haptics.notification).mockReset().mockResolvedValue();
vi.mocked(isNativeApp).mockReturnValue(true);
});
describe('toastHaptic', () => {
it('taps for success, warning and error toasts in the app', () => {
toastHaptic('success')
toastHaptic('warning')
toastHaptic('error')
toastHaptic('success');
toastHaptic('warning');
toastHaptic('error');
expect(vi.mocked(Haptics.notification).mock.calls.map(([o]) => o?.type)).toEqual([
NotificationType.Success, NotificationType.Warning, NotificationType.Error,
])
})
NotificationType.Success,
NotificationType.Warning,
NotificationType.Error,
]);
});
it('stays still for info toasts and in a browser', () => {
toastHaptic('info')
vi.mocked(isNativeApp).mockReturnValue(false)
toastHaptic('success')
expect(Haptics.notification).not.toHaveBeenCalled()
})
toastHaptic('info');
vi.mocked(isNativeApp).mockReturnValue(false);
toastHaptic('success');
expect(Haptics.notification).not.toHaveBeenCalled();
});
it('does not let a missing vibrator surface as an error', async () => {
const report = vi.fn()
vi.stubGlobal('reportError', report)
vi.mocked(Haptics.notification).mockRejectedValue(new Error('not available'))
toastHaptic('error')
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)))
vi.unstubAllGlobals()
})
})
const report = vi.fn();
vi.stubGlobal('reportError', report);
vi.mocked(Haptics.notification).mockRejectedValue(new Error('not available'));
toastHaptic('error');
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)));
vi.unstubAllGlobals();
});
});
+7 -7
View File
@@ -1,12 +1,12 @@
import { Haptics, NotificationType } from '@capacitor/haptics'
import { isNativeApp } from './platform'
import { reportNativeFailure } from './reportFailure'
import { Haptics, NotificationType } from '@capacitor/haptics';
import { isNativeApp } from './platform';
import { reportNativeFailure } from './reportFailure';
const FEEDBACK: Record<string, NotificationType | undefined> = {
success: NotificationType.Success,
warning: NotificationType.Warning,
error: NotificationType.Error,
}
};
/**
* The short tap a native app gives when something saved, warned or failed.
@@ -14,7 +14,7 @@ const FEEDBACK: Record<string, NotificationType | undefined> = {
* one; plain info toasts stay silent. Does nothing in a browser.
*/
export function toastHaptic(type: string): void {
const feedback = FEEDBACK[type]
if (!feedback || !isNativeApp()) return
Haptics.notification({ type: feedback }).catch(reportNativeFailure)
const feedback = FEEDBACK[type];
if (!feedback || !isNativeApp()) return;
Haptics.notification({ type: feedback }).catch(reportNativeFailure);
}
+83 -83
View File
@@ -1,109 +1,109 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { App } from '@capacitor/app'
import { Keyboard } from '@capacitor/keyboard'
import { SplashScreen } from '@capacitor/splash-screen'
import { StatusBar, Style } from '@capacitor/status-bar'
import { startNativeApp } from './nativeApp'
import { isNativeApp, isNativeIos } from './platform'
import { keepOfflineShellFresh } from './offlineShell'
import { isEffectivelyOffline } from '../sync/networkMode'
import { App } from '@capacitor/app';
import { Keyboard } from '@capacitor/keyboard';
import { SplashScreen } from '@capacitor/splash-screen';
import { StatusBar, Style } from '@capacitor/status-bar';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { isEffectivelyOffline } from '../sync/networkMode';
import { startNativeApp } from './nativeApp';
import { keepOfflineShellFresh } from './offlineShell';
import { isNativeApp, isNativeIos } from './platform';
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: vi.fn() } }))
vi.mock('@capacitor/keyboard', () => ({ Keyboard: { setAccessoryBarVisible: vi.fn() } }))
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } }))
vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } }))
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() }))
vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }))
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() }))
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: vi.fn() } }));
vi.mock('@capacitor/keyboard', () => ({ Keyboard: { setAccessoryBarVisible: vi.fn() } }));
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } }));
vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } }));
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() }));
vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }));
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() }));
function backButtonHandler(): (event: { canGoBack: boolean }) => void {
const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton')
if (!call) throw new Error('no backButton listener')
return call[1] as unknown as (event: { canGoBack: boolean }) => void
const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton');
if (!call) throw new Error('no backButton listener');
return call[1] as unknown as (event: { canGoBack: boolean }) => void;
}
beforeEach(() => {
vi.useFakeTimers()
vi.clearAllMocks()
vi.mocked(isNativeApp).mockReturnValue(true)
vi.mocked(isNativeIos).mockReturnValue(false)
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
vi.mocked(keepOfflineShellFresh).mockResolvedValue()
document.documentElement.classList.remove('dark')
})
vi.useFakeTimers();
vi.clearAllMocks();
vi.mocked(isNativeApp).mockReturnValue(true);
vi.mocked(isNativeIos).mockReturnValue(false);
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
vi.mocked(keepOfflineShellFresh).mockResolvedValue();
document.documentElement.classList.remove('dark');
});
afterEach(() => {
vi.useRealTimers()
})
vi.useRealTimers();
});
describe('startNativeApp', () => {
it('does nothing in a browser', () => {
vi.mocked(isNativeApp).mockReturnValue(false)
startNativeApp()
expect(App.addListener).not.toHaveBeenCalled()
expect(StatusBar.setStyle).not.toHaveBeenCalled()
})
vi.mocked(isNativeApp).mockReturnValue(false);
startNativeApp();
expect(App.addListener).not.toHaveBeenCalled();
expect(StatusBar.setStyle).not.toHaveBeenCalled();
});
it('hides the splash after the first frame', () => {
startNativeApp()
vi.runOnlyPendingTimers()
expect(SplashScreen.hide).toHaveBeenCalled()
})
startNativeApp();
vi.runOnlyPendingTimers();
expect(SplashScreen.hide).toHaveBeenCalled();
});
it('walks back through history before it leaves the app', () => {
const back = vi.spyOn(window.history, 'back').mockImplementation(() => {})
startNativeApp()
backButtonHandler()({ canGoBack: true })
expect(back).toHaveBeenCalled()
backButtonHandler()({ canGoBack: false })
expect(App.minimizeApp).toHaveBeenCalled()
})
const back = vi.spyOn(window.history, 'back').mockImplementation(() => {});
startNativeApp();
backButtonHandler()({ canGoBack: true });
expect(back).toHaveBeenCalled();
backButtonHandler()({ canGoBack: false });
expect(App.minimizeApp).toHaveBeenCalled();
});
it('keeps the status bar icons readable when the scheme changes', async () => {
startNativeApp()
expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light })
document.documentElement.classList.add('dark')
await vi.waitFor(() => expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark }))
})
startNativeApp();
expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light });
document.documentElement.classList.add('dark');
await vi.waitFor(() => expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark }));
});
it('hides the keyboard accessory bar on iOS only', () => {
startNativeApp()
expect(Keyboard.setAccessoryBarVisible).not.toHaveBeenCalled()
vi.mocked(isNativeIos).mockReturnValue(true)
startNativeApp()
expect(Keyboard.setAccessoryBarVisible).toHaveBeenCalledWith({ isVisible: false })
})
startNativeApp();
expect(Keyboard.setAccessoryBarVisible).not.toHaveBeenCalled();
vi.mocked(isNativeIos).mockReturnValue(true);
startNativeApp();
expect(Keyboard.setAccessoryBarVisible).toHaveBeenCalledWith({ isVisible: false });
});
it('refreshes the offline start on iOS once the first screen has settled', () => {
vi.mocked(isNativeIos).mockReturnValue(true)
startNativeApp()
expect(keepOfflineShellFresh).not.toHaveBeenCalled()
vi.advanceTimersByTime(15_000)
expect(keepOfflineShellFresh).toHaveBeenCalled()
})
vi.mocked(isNativeIos).mockReturnValue(true);
startNativeApp();
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
vi.advanceTimersByTime(15_000);
expect(keepOfflineShellFresh).toHaveBeenCalled();
});
it('skips the refresh while offline, and never on Android', () => {
vi.mocked(isNativeIos).mockReturnValue(true)
vi.mocked(isEffectivelyOffline).mockReturnValue(true)
startNativeApp()
vi.advanceTimersByTime(15_000)
expect(keepOfflineShellFresh).not.toHaveBeenCalled()
vi.mocked(isNativeIos).mockReturnValue(true);
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
startNativeApp();
vi.advanceTimersByTime(15_000);
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
vi.mocked(isNativeIos).mockReturnValue(false)
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
startNativeApp()
vi.advanceTimersByTime(15_000)
expect(keepOfflineShellFresh).not.toHaveBeenCalled()
})
vi.mocked(isNativeIos).mockReturnValue(false);
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
startNativeApp();
vi.advanceTimersByTime(15_000);
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
});
it('logs a failed refresh instead of throwing', async () => {
vi.mocked(isNativeIos).mockReturnValue(true)
vi.mocked(keepOfflineShellFresh).mockRejectedValue(new Error('down'))
const report = vi.fn()
vi.stubGlobal('reportError', report)
startNativeApp()
vi.advanceTimersByTime(15_000)
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)))
vi.unstubAllGlobals()
})
})
vi.mocked(isNativeIos).mockReturnValue(true);
vi.mocked(keepOfflineShellFresh).mockRejectedValue(new Error('down'));
const report = vi.fn();
vi.stubGlobal('reportError', report);
startNativeApp();
vi.advanceTimersByTime(15_000);
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)));
vi.unstubAllGlobals();
});
});
+26 -24
View File
@@ -1,41 +1,43 @@
import { App } from '@capacitor/app'
import { Keyboard } from '@capacitor/keyboard'
import { SplashScreen } from '@capacitor/splash-screen'
import { StatusBar, Style } from '@capacitor/status-bar'
import { isNativeApp, isNativeIos } from './platform'
import { keepOfflineShellFresh } from './offlineShell'
import { reportNativeFailure } from './reportFailure'
import { isEffectivelyOffline } from '../sync/networkMode'
import { App } from '@capacitor/app';
import { Keyboard } from '@capacitor/keyboard';
import { SplashScreen } from '@capacitor/splash-screen';
import { StatusBar, Style } from '@capacitor/status-bar';
import { isEffectivelyOffline } from '../sync/networkMode';
import { keepOfflineShellFresh } from './offlineShell';
import { isNativeApp, isNativeIos } from './platform';
import { reportNativeFailure } from './reportFailure';
/** Long enough that the warm-up never competes with the first screen's requests. */
const OFFLINE_SHELL_DELAY_MS = 15_000
const OFFLINE_SHELL_DELAY_MS = 15_000;
/**
* What the UI does differently when it runs inside the iOS or Android app.
* Everything else is the same UI a browser gets from this server.
*/
export function startNativeApp(): void {
if (!isNativeApp()) return
if (!isNativeApp()) return;
followThemeInStatusBar()
followThemeInStatusBar();
// Android's back gesture: through the app's own history first, and only
// then out of the app, the way a browser tab would behave.
void App.addListener('backButton', ({ canGoBack }) => {
if (canGoBack) window.history.back()
else void App.minimizeApp()
})
if (canGoBack) window.history.back();
else void App.minimizeApp();
});
requestAnimationFrame(() => { void SplashScreen.hide() })
requestAnimationFrame(() => {
void SplashScreen.hide();
});
if (isNativeIos()) {
// The "‹ › Done" strip above the keyboard is a web form's, not an app's.
void Keyboard.setAccessoryBarVisible({ isVisible: false })
void Keyboard.setAccessoryBarVisible({ isVisible: false });
window.setTimeout(() => {
if (isEffectivelyOffline()) return
if (isEffectivelyOffline()) return;
// Not refreshed this time is no harm: the next launch tries again.
keepOfflineShellFresh().catch(reportNativeFailure)
}, OFFLINE_SHELL_DELAY_MS)
keepOfflineShellFresh().catch(reportNativeFailure);
}, OFFLINE_SHELL_DELAY_MS);
}
}
@@ -45,10 +47,10 @@ export function startNativeApp(): void {
* every way the scheme changes, including "follow the system".
*/
function followThemeInStatusBar(): void {
const root = document.documentElement
const root = document.documentElement;
const apply = (): void => {
void StatusBar.setStyle({ style: root.classList.contains('dark') ? Style.Dark : Style.Light })
}
apply()
new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] })
void StatusBar.setStyle({ style: root.classList.contains('dark') ? Style.Dark : Style.Light });
};
apply();
new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] });
}
+36 -32
View File
@@ -1,49 +1,53 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Directory, Filesystem } from '@capacitor/filesystem'
import { Share } from '@capacitor/share'
import { cacheFileName, fileNameFromUrl, shareFile } from './nativeFiles'
import { Directory, Filesystem } from '@capacitor/filesystem';
import { Share } from '@capacitor/share';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { cacheFileName, fileNameFromUrl, shareFile } from './nativeFiles';
vi.mock('@capacitor/filesystem', () => ({ Directory: { Cache: 'CACHE' }, Filesystem: { writeFile: vi.fn() } }))
vi.mock('@capacitor/share', () => ({ Share: { share: vi.fn() } }))
vi.mock('@capacitor/filesystem', () => ({ Directory: { Cache: 'CACHE' }, Filesystem: { writeFile: vi.fn() } }));
vi.mock('@capacitor/share', () => ({ Share: { share: vi.fn() } }));
beforeEach(() => {
vi.mocked(Filesystem.writeFile).mockReset().mockResolvedValue({ uri: 'file:///cache/trip.pdf' })
vi.mocked(Share.share).mockReset().mockResolvedValue({})
})
vi.mocked(Filesystem.writeFile).mockReset().mockResolvedValue({ uri: 'file:///cache/trip.pdf' });
vi.mocked(Share.share).mockReset().mockResolvedValue({});
});
describe('cacheFileName', () => {
it('keeps a readable name but nothing that could leave the cache directory', () => {
expect(cacheFileName('Lisbon 2026.pdf')).toBe('Lisbon 2026.pdf')
expect(cacheFileName('../../etc/passwd')).toBe('_.._etc_passwd')
expect(cacheFileName('a:b*c?"d"<e>|f\u0001.txt')).toBe('a_b_c__d__e__f_.txt')
expect(cacheFileName('...hidden')).toBe('hidden')
expect(cacheFileName(' ')).toBe('download')
})
})
expect(cacheFileName('Lisbon 2026.pdf')).toBe('Lisbon 2026.pdf');
expect(cacheFileName('../../etc/passwd')).toBe('_.._etc_passwd');
expect(cacheFileName('a:b*c?"d"<e>|f\u0001.txt')).toBe('a_b_c__d__e__f_.txt');
expect(cacheFileName('...hidden')).toBe('hidden');
expect(cacheFileName(' ')).toBe('download');
});
});
describe('fileNameFromUrl', () => {
it('takes the decoded last path segment', () => {
expect(fileNameFromUrl('/api/trips/1/files/42/Boarding%20pass.pdf?token=x')).toBe('Boarding pass.pdf')
expect(fileNameFromUrl('/uploads/files/')).toBe('files')
expect(fileNameFromUrl('/bad/%E0%A4%A')).toBe('%E0%A4%A')
})
})
expect(fileNameFromUrl('/api/trips/1/files/42/Boarding%20pass.pdf?token=x')).toBe('Boarding pass.pdf');
expect(fileNameFromUrl('/uploads/files/')).toBe('files');
expect(fileNameFromUrl('/bad/%E0%A4%A')).toBe('%E0%A4%A');
});
});
describe('shareFile', () => {
it('writes the blob to the cache and hands it to the share sheet', async () => {
await shareFile(new Blob(['hello'], { type: 'text/plain' }), 'note.txt')
await shareFile(new Blob(['hello'], { type: 'text/plain' }), 'note.txt');
expect(Filesystem.writeFile).toHaveBeenCalledWith({ path: 'note.txt', data: btoa('hello'), directory: Directory.Cache })
expect(Share.share).toHaveBeenCalledWith({ files: ['file:///cache/trip.pdf'] })
})
expect(Filesystem.writeFile).toHaveBeenCalledWith({
path: 'note.txt',
data: btoa('hello'),
directory: Directory.Cache,
});
expect(Share.share).toHaveBeenCalledWith({ files: ['file:///cache/trip.pdf'] });
});
it('treats a dismissed sheet as the user changing their mind', async () => {
vi.mocked(Share.share).mockRejectedValue(new Error('Share canceled'))
await expect(shareFile(new Blob(['x']), 'x.txt')).resolves.toBeUndefined()
})
vi.mocked(Share.share).mockRejectedValue(new Error('Share canceled'));
await expect(shareFile(new Blob(['x']), 'x.txt')).resolves.toBeUndefined();
});
it('passes a real failure on', async () => {
vi.mocked(Share.share).mockRejectedValue(new Error('No activity found'))
await expect(shareFile(new Blob(['x']), 'x.txt')).rejects.toThrow('No activity found')
})
})
vi.mocked(Share.share).mockRejectedValue(new Error('No activity found'));
await expect(shareFile(new Blob(['x']), 'x.txt')).rejects.toThrow('No activity found');
});
});
+19 -17
View File
@@ -1,28 +1,30 @@
import { Directory, Filesystem } from '@capacitor/filesystem'
import { Share } from '@capacitor/share'
import { Directory, Filesystem } from '@capacitor/filesystem';
import { Share } from '@capacitor/share';
function toBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1))
reader.onerror = () => reject(reader.error)
reader.readAsDataURL(blob)
})
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1));
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
}
/** Readable, but safe as a single path segment inside the cache directory. */
export function cacheFileName(filename: string): string {
const cleaned = Array.from(filename, (ch) => (ch.charCodeAt(0) < 32 || '\\/:*?"<>|'.includes(ch) ? '_' : ch)).join('').trim()
return cleaned.replace(/^\.+/, '') || 'download'
const cleaned = Array.from(filename, (ch) => (ch.charCodeAt(0) < 32 || '\\/:*?"<>|'.includes(ch) ? '_' : ch))
.join('')
.trim();
return cleaned.replace(/^\.+/, '') || 'download';
}
export function fileNameFromUrl(url: string): string {
const [path = ''] = url.split('?', 1)
const last = path.split('/').filter(Boolean).pop() ?? ''
const [path = ''] = url.split('?', 1);
const last = path.split('/').filter(Boolean).pop() ?? '';
try {
return decodeURIComponent(last)
return decodeURIComponent(last);
} catch {
return last
return last;
}
}
@@ -36,12 +38,12 @@ export async function shareFile(blob: Blob, filename: string): Promise<void> {
path: cacheFileName(filename),
data: await toBase64(blob),
directory: Directory.Cache,
})
});
try {
await Share.share({ files: [uri] })
await Share.share({ files: [uri] });
} catch (err) {
// Dismissing the sheet rejects; that is the user's choice, not a failure.
if (/cancel/i.test(String((err as Error)?.message))) return
throw err
if (/cancel/i.test(String((err as Error)?.message))) return;
throw err;
}
}
+35 -31
View File
@@ -1,19 +1,23 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { keepOfflineShellFresh, manifestFiles } from './offlineShell'
import { TrekShell } from './trekShell'
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { keepOfflineShellFresh, manifestFiles } from './offlineShell';
import { TrekShell } from './trekShell';
vi.mock('./trekShell', () => ({ TrekShell: { refreshOfflineCopy: vi.fn() } }))
vi.mock('./trekShell', () => ({ TrekShell: { refreshOfflineCopy: vi.fn() } }));
const manifest = {
'index.html': { file: 'assets/index-a1b2c3d4.js', css: ['assets/index-e5f6a7b8.css'], assets: ['assets/poppins-11223344.woff2'] },
'index.html': {
file: 'assets/index-a1b2c3d4.js',
css: ['assets/index-e5f6a7b8.css'],
assets: ['assets/poppins-11223344.woff2'],
},
'src/pages/AtlasPage.tsx': { file: 'assets/AtlasPage-99887766.js', css: ['assets/index-e5f6a7b8.css'] },
_shared: { file: 'assets/shared-55443322.js', assets: 'not-a-list' },
broken: null,
}
};
beforeEach(() => {
vi.mocked(TrekShell.refreshOfflineCopy).mockReset().mockResolvedValue({ saved: true })
})
vi.mocked(TrekShell.refreshOfflineCopy).mockReset().mockResolvedValue({ saved: true });
});
describe('manifestFiles', () => {
it('collects every chunk, stylesheet and asset once', () => {
@@ -23,44 +27,44 @@ describe('manifestFiles', () => {
'assets/index-e5f6a7b8.css',
'assets/poppins-11223344.woff2',
'assets/shared-55443322.js',
])
})
]);
});
it('returns nothing for something that is not a manifest', () => {
expect(manifestFiles(null)).toEqual([])
expect(manifestFiles('x')).toEqual([])
})
})
expect(manifestFiles(null)).toEqual([]);
expect(manifestFiles('x')).toEqual([]);
});
});
describe('keepOfflineShellFresh', () => {
it('refreshes the stored start page and fetches every file of the build', async () => {
const fetched: string[] = []
const fetched: string[] = [];
const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input)
const url = String(input);
if (url === '/asset-manifest.json') {
expect(init).toEqual({ cache: 'no-store' })
return new Response(JSON.stringify(manifest))
expect(init).toEqual({ cache: 'no-store' });
return new Response(JSON.stringify(manifest));
}
fetched.push(url)
if (url.includes('shared')) throw new Error('offline for a moment')
return new Response('x')
}) as unknown as typeof fetch
fetched.push(url);
if (url.includes('shared')) throw new Error('offline for a moment');
return new Response('x');
}) as unknown as typeof fetch;
await keepOfflineShellFresh(fetchImpl)
await keepOfflineShellFresh(fetchImpl);
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled()
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled();
expect(fetched.sort()).toEqual([
'/assets/AtlasPage-99887766.js',
'/assets/index-a1b2c3d4.js',
'/assets/index-e5f6a7b8.css',
'/assets/poppins-11223344.woff2',
'/assets/shared-55443322.js',
])
})
]);
});
it('stops after the start page when the build has no manifest', async () => {
const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch
await keepOfflineShellFresh(fetchImpl)
expect(fetchImpl).toHaveBeenCalledTimes(1)
})
})
const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch;
await keepOfflineShellFresh(fetchImpl);
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
});
+20 -20
View File
@@ -1,4 +1,4 @@
import { TrekShell } from './trekShell'
import { TrekShell } from './trekShell';
/**
* iOS only. WKWebView runs no service worker for a domain the app does not
@@ -10,45 +10,45 @@ import { TrekShell } from './trekShell'
* routes nobody has opened yet.
*/
const MANIFEST_URL = '/asset-manifest.json'
const CONCURRENCY = 4
const MANIFEST_URL = '/asset-manifest.json';
const CONCURRENCY = 4;
interface ManifestChunk {
file?: string
css?: string[]
assets?: string[]
file?: string;
css?: string[];
assets?: string[];
}
export function manifestFiles(manifest: unknown): string[] {
if (typeof manifest !== 'object' || manifest === null) return []
const files = new Set<string>()
if (typeof manifest !== 'object' || manifest === null) return [];
const files = new Set<string>();
for (const chunk of Object.values(manifest as Record<string, ManifestChunk>)) {
if (typeof chunk?.file === 'string') files.add(chunk.file)
if (typeof chunk?.file === 'string') files.add(chunk.file);
for (const list of [chunk?.css, chunk?.assets]) {
if (Array.isArray(list)) list.forEach((f) => typeof f === 'string' && files.add(f))
if (Array.isArray(list)) list.forEach((f) => typeof f === 'string' && files.add(f));
}
}
return [...files]
return [...files];
}
async function warmCache(files: string[], fetchFile: (path: string) => Promise<unknown>): Promise<void> {
const queue = [...files]
const queue = [...files];
const worker = async (): Promise<void> => {
for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
try {
await fetchFile(`/${path}`)
await fetchFile(`/${path}`);
} catch {
// One missing chunk must not stop the rest; the next launch tries again.
}
}
}
await Promise.all(Array.from({ length: CONCURRENCY }, worker))
};
await Promise.all(Array.from({ length: CONCURRENCY }, worker));
}
export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch): Promise<void> {
await TrekShell.refreshOfflineCopy()
const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' })
if (!response.ok) return
const files = manifestFiles(await response.json())
await warmCache(files, (path) => fetchImpl(path).then((r) => r.blob()))
await TrekShell.refreshOfflineCopy();
const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' });
if (!response.ok) return;
const files = manifestFiles(await response.json());
await warmCache(files, (path) => fetchImpl(path).then((r) => r.blob()));
}
+135 -92
View File
@@ -1,61 +1,72 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
fromOfflineUrl, installOfflineProtocol, offlineProtocol, offlineStyle, rewriteDocument, toOfflineUrl,
} from './offlineTiles'
import { isNativeIos } from './platform'
fromOfflineUrl,
installOfflineProtocol,
offlineProtocol,
offlineStyle,
rewriteDocument,
toOfflineUrl,
} from './offlineTiles';
import { isNativeIos } from './platform';
vi.mock('./platform', () => ({ isNativeIos: vi.fn() }))
vi.mock('./platform', () => ({ isNativeIos: vi.fn() }));
const cached = new Map<string, Response>()
const cache = { match: vi.fn(async (url: string) => cached.get(url)?.clone()) }
const cached = new Map<string, Response>();
const cache = { match: vi.fn(async (url: string) => cached.get(url)?.clone()) };
beforeEach(() => {
cached.clear()
vi.mocked(isNativeIos).mockReturnValue(true)
vi.stubGlobal('caches', { open: vi.fn(async () => cache) })
})
cached.clear();
vi.mocked(isNativeIos).mockReturnValue(true);
vi.stubGlobal('caches', { open: vi.fn(async () => cache) });
});
afterEach(() => {
vi.unstubAllGlobals()
})
vi.unstubAllGlobals();
});
function params(url: string, type: 'json' | 'arrayBuffer' | 'image' | 'string') {
return { url, type }
return { url, type };
}
describe('URL rewriting', () => {
it('moves https URLs onto the protocol and back, and leaves everything else', () => {
expect(toOfflineUrl('https://tiles.openfreemap.org/styles/positron')).toBe('trek-offline://tiles.openfreemap.org/styles/positron')
expect(fromOfflineUrl('trek-offline://tiles.openfreemap.org/styles/positron')).toBe('https://tiles.openfreemap.org/styles/positron')
expect(toOfflineUrl('mapbox://styles/mapbox/streets-v12')).toBe('mapbox://styles/mapbox/streets-v12')
expect(fromOfflineUrl('https://x.test/a')).toBe('https://x.test/a')
})
expect(toOfflineUrl('https://tiles.openfreemap.org/styles/positron')).toBe(
'trek-offline://tiles.openfreemap.org/styles/positron'
);
expect(fromOfflineUrl('trek-offline://tiles.openfreemap.org/styles/positron')).toBe(
'https://tiles.openfreemap.org/styles/positron'
);
expect(toOfflineUrl('mapbox://styles/mapbox/streets-v12')).toBe('mapbox://styles/mapbox/streets-v12');
expect(fromOfflineUrl('https://x.test/a')).toBe('https://x.test/a');
});
it('rewrites the style only inside the iOS app with Cache Storage', () => {
const style = 'https://tiles.openfreemap.org/styles/liberty?key=abc'
expect(offlineStyle(style)).toBe('trek-offline://tiles.openfreemap.org/styles/liberty?key=abc')
expect(offlineStyle({ version: 8 })).toEqual({ version: 8 })
const style = 'https://tiles.openfreemap.org/styles/liberty?key=abc';
expect(offlineStyle(style)).toBe('trek-offline://tiles.openfreemap.org/styles/liberty?key=abc');
expect(offlineStyle({ version: 8 })).toEqual({ version: 8 });
vi.mocked(isNativeIos).mockReturnValue(false)
expect(offlineStyle(style)).toBe(style)
vi.mocked(isNativeIos).mockReturnValue(false);
expect(offlineStyle(style)).toBe(style);
vi.mocked(isNativeIos).mockReturnValue(true)
vi.stubGlobal('caches', undefined)
expect(offlineStyle(style)).toBe(style)
})
vi.mocked(isNativeIos).mockReturnValue(true);
vi.stubGlobal('caches', undefined);
expect(offlineStyle(style)).toBe(style);
});
it('points sources, tiles, glyphs and sprites of a style at the protocol', () => {
expect(rewriteDocument({
version: 8,
glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
sprite: [{ id: 'default', url: 'https://tiles.openfreemap.org/sprites/ofm' }, 'odd'],
sources: {
openmaptiles: { type: 'vector', url: 'https://tiles.openfreemap.org/planet' },
inline: { type: 'raster', tiles: ['https://a.test/{z}/{x}/{y}.png', 7] },
broken: null,
},
layers: [],
})).toEqual({
expect(
rewriteDocument({
version: 8,
glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
sprite: [{ id: 'default', url: 'https://tiles.openfreemap.org/sprites/ofm' }, 'odd'],
sources: {
openmaptiles: { type: 'vector', url: 'https://tiles.openfreemap.org/planet' },
inline: { type: 'raster', tiles: ['https://a.test/{z}/{x}/{y}.png', 7] },
broken: null,
},
layers: [],
})
).toEqual({
version: 8,
glyphs: 'trek-offline://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
sprite: [{ id: 'default', url: 'trek-offline://tiles.openfreemap.org/sprites/ofm' }, 'odd'],
@@ -65,76 +76,108 @@ describe('URL rewriting', () => {
broken: null,
},
layers: [],
})
})
});
});
it('handles a TileJSON, a single sprite URL and things that are not documents', () => {
expect(rewriteDocument({ tiles: ['https://t.test/20250101/{z}/{x}/{y}.pbf'] })).toEqual({ tiles: ['trek-offline://t.test/20250101/{z}/{x}/{y}.pbf'] })
expect(rewriteDocument({ sprite: 'https://s.test/sprite' })).toEqual({ sprite: 'trek-offline://s.test/sprite' })
expect(rewriteDocument('x')).toBe('x')
expect(rewriteDocument([1])).toEqual([1])
})
})
expect(rewriteDocument({ tiles: ['https://t.test/20250101/{z}/{x}/{y}.pbf'] })).toEqual({
tiles: ['trek-offline://t.test/20250101/{z}/{x}/{y}.pbf'],
});
expect(rewriteDocument({ sprite: 'https://s.test/sprite' })).toEqual({ sprite: 'trek-offline://s.test/sprite' });
expect(rewriteDocument('x')).toBe('x');
expect(rewriteDocument([1])).toEqual([1]);
});
});
describe('offlineProtocol', () => {
it('answers a document from the network and rewrites it', async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ tiles: ['https://t.test/{z}/{x}/{y}.pbf'] })))
vi.stubGlobal('fetch', fetchMock)
const result = await offlineProtocol(params('trek-offline://t.test/planet', 'json'), new AbortController())
expect(fetchMock).toHaveBeenCalledWith('https://t.test/planet', expect.objectContaining({ mode: 'cors' }))
expect(result.data).toEqual({ tiles: ['trek-offline://t.test/{z}/{x}/{y}.pbf'] })
})
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ tiles: ['https://t.test/{z}/{x}/{y}.pbf'] })));
vi.stubGlobal('fetch', fetchMock);
const result = await offlineProtocol(params('trek-offline://t.test/planet', 'json'), new AbortController());
expect(fetchMock).toHaveBeenCalledWith('https://t.test/planet', expect.objectContaining({ mode: 'cors' }));
expect(result.data).toEqual({ tiles: ['trek-offline://t.test/{z}/{x}/{y}.pbf'] });
});
it('falls back to the cached document when the network is gone', async () => {
cached.set('https://t.test/style', new Response(JSON.stringify({ version: 8 })))
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('offline') }))
const result = await offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())
expect(result.data).toEqual({ version: 8 })
})
cached.set('https://t.test/style', new Response(JSON.stringify({ version: 8 })));
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw new TypeError('offline');
})
);
const result = await offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController());
expect(result.data).toEqual({ version: 8 });
});
it('serves tiles from the cache without asking the network', async () => {
cached.set('https://t.test/1/2/3.pbf', new Response(new Uint8Array([1, 2, 3])))
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const result = await offlineProtocol(params('trek-offline://t.test/1/2/3.pbf', 'arrayBuffer'), new AbortController())
expect(new Uint8Array(result.data as ArrayBuffer)).toEqual(new Uint8Array([1, 2, 3]))
expect(fetchMock).not.toHaveBeenCalled()
})
cached.set('https://t.test/1/2/3.pbf', new Response(new Uint8Array([1, 2, 3])));
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
const result = await offlineProtocol(
params('trek-offline://t.test/1/2/3.pbf', 'arrayBuffer'),
new AbortController()
);
expect(new Uint8Array(result.data as ArrayBuffer)).toEqual(new Uint8Array([1, 2, 3]));
expect(fetchMock).not.toHaveBeenCalled();
});
it('fetches an uncached tile, and returns text for string requests', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('hello')))
const tile = await offlineProtocol(params('trek-offline://t.test/9/9/9.png', 'image'), new AbortController())
expect(new TextDecoder().decode(tile.data as ArrayBuffer)).toBe('hello')
const text = await offlineProtocol(params('trek-offline://t.test/a.txt', 'string'), new AbortController())
expect(text.data).toBe('hello')
})
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('hello'))
);
const tile = await offlineProtocol(params('trek-offline://t.test/9/9/9.png', 'image'), new AbortController());
expect(new TextDecoder().decode(tile.data as ArrayBuffer)).toBe('hello');
const text = await offlineProtocol(params('trek-offline://t.test/a.txt', 'string'), new AbortController());
expect(text.data).toBe('hello');
});
it('fails loudly on an uncached tile offline or an HTTP error', async () => {
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('offline') }))
await expect(offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())).rejects.toThrow('offline')
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw new TypeError('offline');
})
);
await expect(
offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())
).rejects.toThrow('offline');
vi.stubGlobal('fetch', vi.fn(async () => new Response('nope', { status: 404 })))
await expect(offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())).rejects.toThrow('HTTP 404')
await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())).rejects.toThrow('Not available offline')
})
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('nope', { status: 404 }))
);
await expect(
offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())
).rejects.toThrow('HTTP 404');
await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())).rejects.toThrow(
'Not available offline'
);
});
it('passes an abort straight through for documents', async () => {
const controller = new AbortController()
controller.abort()
vi.stubGlobal('fetch', vi.fn(async () => { throw new DOMException('aborted', 'AbortError') }))
await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), controller)).rejects.toThrow('aborted')
})
})
const controller = new AbortController();
controller.abort();
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw new DOMException('aborted', 'AbortError');
})
);
await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), controller)).rejects.toThrow('aborted');
});
});
describe('installOfflineProtocol', () => {
it('registers only inside the iOS app', () => {
const addProtocol = vi.fn()
installOfflineProtocol({ addProtocol })
expect(addProtocol).toHaveBeenCalledWith('trek-offline', offlineProtocol)
const addProtocol = vi.fn();
installOfflineProtocol({ addProtocol });
expect(addProtocol).toHaveBeenCalledWith('trek-offline', offlineProtocol);
addProtocol.mockClear()
vi.mocked(isNativeIos).mockReturnValue(false)
installOfflineProtocol({ addProtocol })
expect(addProtocol).not.toHaveBeenCalled()
})
})
addProtocol.mockClear();
vi.mocked(isNativeIos).mockReturnValue(false);
installOfflineProtocol({ addProtocol });
expect(addProtocol).not.toHaveBeenCalled();
});
});
+57 -47
View File
@@ -1,6 +1,6 @@
import type { AddProtocolAction, GetResourceResponse, RequestParameters } from 'maplibre-gl'
import { VECTOR_CACHE } from '../sync/glPrefetcher'
import { isNativeIos } from './platform'
import type { AddProtocolAction, GetResourceResponse, RequestParameters } from 'maplibre-gl';
import { VECTOR_CACHE } from '../sync/glPrefetcher';
import { isNativeIos } from './platform';
/**
* Offline vector maps for the iOS app.
@@ -16,32 +16,33 @@ import { isNativeIos } from './platform'
* the app.
*/
const OFFLINE_SCHEME = 'trek-offline'
const PREFIX = `${OFFLINE_SCHEME}://`
const OFFLINE_SCHEME = 'trek-offline';
const PREFIX = `${OFFLINE_SCHEME}://`;
function offlineTilesActive(): boolean {
return isNativeIos() && typeof caches !== 'undefined'
return isNativeIos() && typeof caches !== 'undefined';
}
export function toOfflineUrl(url: string): string {
return url.startsWith('https://') ? PREFIX + url.slice('https://'.length) : url
return url.startsWith('https://') ? PREFIX + url.slice('https://'.length) : url;
}
export function fromOfflineUrl(url: string): string {
return url.startsWith(PREFIX) ? 'https://' + url.slice(PREFIX.length) : url
return url.startsWith(PREFIX) ? 'https://' + url.slice(PREFIX.length) : url;
}
/** The style URL to hand MapLibre: rewritten inside the iOS app, untouched anywhere else. */
export function offlineStyle<T>(style: T): T {
return offlineTilesActive() && typeof style === 'string' ? (toOfflineUrl(style) as T) : style
return offlineTilesActive() && typeof style === 'string' ? (toOfflineUrl(style) as T) : style;
}
type Doc = Record<string, unknown>
type Doc = Record<string, unknown>;
/** What a protocol handler may hand MapLibre back. */
type ProtocolData = Awaited<ReturnType<AddProtocolAction>>['data']
type ProtocolData = Awaited<ReturnType<AddProtocolAction>>['data'];
const isDoc = (value: unknown): value is Doc => typeof value === 'object' && value !== null && !Array.isArray(value)
const rewriteList = (value: unknown): unknown => (Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? toOfflineUrl(v) : v)) : value)
const isDoc = (value: unknown): value is Doc => typeof value === 'object' && value !== null && !Array.isArray(value);
const rewriteList = (value: unknown): unknown =>
Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? toOfflineUrl(v) : v)) : value;
/**
* Points the URLs inside a style document or a TileJSON at the protocol, so
@@ -49,24 +50,28 @@ const rewriteList = (value: unknown): unknown => (Array.isArray(value) ? value.m
* the tiles as well, not only for the style.
*/
export function rewriteDocument(doc: unknown): unknown {
if (!isDoc(doc)) return doc
const out: Doc = { ...doc }
if ('tiles' in out) out.tiles = rewriteList(out.tiles)
if (typeof out.glyphs === 'string') out.glyphs = toOfflineUrl(out.glyphs)
if (typeof out.sprite === 'string') out.sprite = toOfflineUrl(out.sprite)
if (!isDoc(doc)) return doc;
const out: Doc = { ...doc };
if ('tiles' in out) out.tiles = rewriteList(out.tiles);
if (typeof out.glyphs === 'string') out.glyphs = toOfflineUrl(out.glyphs);
if (typeof out.sprite === 'string') out.sprite = toOfflineUrl(out.sprite);
else if (Array.isArray(out.sprite)) {
out.sprite = out.sprite.map((entry) => (isDoc(entry) && typeof entry.url === 'string' ? { ...entry, url: toOfflineUrl(entry.url) } : entry))
out.sprite = out.sprite.map((entry) =>
isDoc(entry) && typeof entry.url === 'string' ? { ...entry, url: toOfflineUrl(entry.url) } : entry
);
}
if (isDoc(out.sources)) {
out.sources = Object.fromEntries(Object.entries(out.sources).map(([id, source]) => {
if (!isDoc(source)) return [id, source]
const rewritten: Doc = { ...source }
if (typeof rewritten.url === 'string') rewritten.url = toOfflineUrl(rewritten.url)
if ('tiles' in rewritten) rewritten.tiles = rewriteList(rewritten.tiles)
return [id, rewritten]
}))
out.sources = Object.fromEntries(
Object.entries(out.sources).map(([id, source]) => {
if (!isDoc(source)) return [id, source];
const rewritten: Doc = { ...source };
if (typeof rewritten.url === 'string') rewritten.url = toOfflineUrl(rewritten.url);
if ('tiles' in rewritten) rewritten.tiles = rewriteList(rewritten.tiles);
return [id, rewritten];
})
);
}
return out
return out;
}
/**
@@ -75,32 +80,37 @@ export function rewriteDocument(doc: unknown): unknown {
* their URL, so the cache goes first and saves the round trip.
*/
async function load(url: string, networkFirst: boolean, signal: AbortSignal): Promise<Response> {
const cache = await caches.open(VECTOR_CACHE)
const cache = await caches.open(VECTOR_CACHE);
if (!networkFirst) {
const cached = await cache.match(url)
if (cached) return cached
const cached = await cache.match(url);
if (cached) return cached;
}
try {
const response = await fetch(url, { mode: 'cors', signal })
if (response.ok) return response
if (!networkFirst) return response
const response = await fetch(url, { mode: 'cors', signal });
if (response.ok) return response;
if (!networkFirst) return response;
} catch (err) {
if (signal.aborted || !networkFirst) throw err
if (signal.aborted || !networkFirst) throw err;
}
const cached = await cache.match(url)
if (cached) return cached
throw new Error(`Not available offline: ${url}`)
const cached = await cache.match(url);
if (cached) return cached;
throw new Error(`Not available offline: ${url}`);
}
export const offlineProtocol: AddProtocolAction = async (params: RequestParameters, abortController: AbortController): Promise<GetResourceResponse<ProtocolData>> => {
const url = fromOfflineUrl(params.url)
const response = await load(url, params.type === 'json', abortController.signal)
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`)
if (params.type === 'json') return { data: rewriteDocument(await response.json()) as ProtocolData }
if (params.type === 'string') return { data: await response.text() }
return { data: await response.arrayBuffer() }
}
export const offlineProtocol: AddProtocolAction = async (
params: RequestParameters,
abortController: AbortController
): Promise<GetResourceResponse<ProtocolData>> => {
const url = fromOfflineUrl(params.url);
const response = await load(url, params.type === 'json', abortController.signal);
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
if (params.type === 'json') return { data: rewriteDocument(await response.json()) as ProtocolData };
if (params.type === 'string') return { data: await response.text() };
return { data: await response.arrayBuffer() };
};
export function installOfflineProtocol(maplibre: { addProtocol: (name: string, action: AddProtocolAction) => void }): void {
if (offlineTilesActive()) maplibre.addProtocol(OFFLINE_SCHEME, offlineProtocol)
export function installOfflineProtocol(maplibre: {
addProtocol: (name: string, action: AddProtocolAction) => void;
}): void {
if (offlineTilesActive()) maplibre.addProtocol(OFFLINE_SCHEME, offlineProtocol);
}
+23 -23
View File
@@ -1,33 +1,33 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Capacitor } from '@capacitor/core'
import { isNativeApp, isNativeIos, nativeServerHost } from './platform'
import { Capacitor } from '@capacitor/core';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { isNativeApp, isNativeIos, nativeServerHost } from './platform';
vi.mock('@capacitor/core', () => ({ Capacitor: { isNativePlatform: vi.fn(), getPlatform: vi.fn() } }))
vi.mock('@capacitor/core', () => ({ Capacitor: { isNativePlatform: vi.fn(), getPlatform: vi.fn() } }));
beforeEach(() => {
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(true)
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios')
})
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(true);
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios');
});
describe('platform', () => {
it('tells the app from a browser', () => {
expect(isNativeApp()).toBe(true)
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false)
expect(isNativeApp()).toBe(false)
})
expect(isNativeApp()).toBe(true);
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
expect(isNativeApp()).toBe(false);
});
it('narrows to iOS', () => {
expect(isNativeIos()).toBe(true)
vi.mocked(Capacitor.getPlatform).mockReturnValue('android')
expect(isNativeIos()).toBe(false)
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios')
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false)
expect(isNativeIos()).toBe(false)
})
expect(isNativeIos()).toBe(true);
vi.mocked(Capacitor.getPlatform).mockReturnValue('android');
expect(isNativeIos()).toBe(false);
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios');
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
expect(isNativeIos()).toBe(false);
});
it('names the server the WebView sits on, only inside the app', () => {
expect(nativeServerHost()).toBe(window.location.host)
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false)
expect(nativeServerHost()).toBeNull()
})
})
expect(nativeServerHost()).toBe(window.location.host);
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
expect(nativeServerHost()).toBeNull();
});
});
+4 -4
View File
@@ -1,15 +1,15 @@
import { Capacitor } from '@capacitor/core'
import { Capacitor } from '@capacitor/core';
/** True inside the iOS and Android apps, where the WebView shows this server's UI. */
export function isNativeApp(): boolean {
return Capacitor.isNativePlatform()
return Capacitor.isNativePlatform();
}
export function isNativeIos(): boolean {
return isNativeApp() && Capacitor.getPlatform() === 'ios'
return isNativeApp() && Capacitor.getPlatform() === 'ios';
}
/** The server the app is connected to: the WebView sits on its origin. */
export function nativeServerHost(): string | null {
return isNativeApp() ? window.location.host : null
return isNativeApp() ? window.location.host : null;
}
+58 -46
View File
@@ -1,73 +1,85 @@
import { describe, it, expect, vi } from 'vitest'
import { candidateUrls, probeServer, type ProbeResponse } from './serverAddress'
import { describe, expect, it, vi } from 'vitest';
import { candidateUrls, probeServer, type ProbeResponse } from './serverAddress';
const features = (url: string, data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true }): ProbeResponse =>
({ status: 200, data, url })
const features = (
url: string,
data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true }
): ProbeResponse => ({ status: 200, data, url });
describe('candidateUrls', () => {
it('tries https before http when no scheme was typed', () => {
expect(candidateUrls('trek.example.com')).toEqual(['https://trek.example.com', 'http://trek.example.com'])
expect(candidateUrls(' 192.168.1.10:3001/ ')).toEqual(['https://192.168.1.10:3001', 'http://192.168.1.10:3001'])
})
expect(candidateUrls('trek.example.com')).toEqual(['https://trek.example.com', 'http://trek.example.com']);
expect(candidateUrls(' 192.168.1.10:3001/ ')).toEqual(['https://192.168.1.10:3001', 'http://192.168.1.10:3001']);
});
it('keeps an explicit scheme and path, without query, hash or trailing slashes', () => {
expect(candidateUrls('http://nas.local:3001/trek/?x=1#y')).toEqual(['http://nas.local:3001/trek'])
expect(candidateUrls('HTTPS://Trek.Example.com//')).toEqual(['https://trek.example.com'])
})
expect(candidateUrls('http://nas.local:3001/trek/?x=1#y')).toEqual(['http://nas.local:3001/trek']);
expect(candidateUrls('HTTPS://Trek.Example.com//')).toEqual(['https://trek.example.com']);
});
it('returns nothing for empty input or other schemes', () => {
expect(candidateUrls(' ')).toEqual([])
expect(candidateUrls('ftp://trek.example.com')).toEqual([])
expect(candidateUrls('javascript://alert(1)')).toEqual([])
})
})
expect(candidateUrls(' ')).toEqual([]);
expect(candidateUrls('ftp://trek.example.com')).toEqual([]);
expect(candidateUrls('javascript://alert(1)')).toEqual([]);
});
});
describe('probeServer', () => {
it('accepts a server that reports nativeApp and follows its redirect', async () => {
const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features'))
expect(await probeServer('http://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' })
expect(get).toHaveBeenCalledWith('http://trek.example.com/api/health/features')
})
const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features'));
expect(await probeServer('http://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
expect(get).toHaveBeenCalledWith('http://trek.example.com/api/health/features');
});
it('falls back to the candidate itself when the final URL is not the probe path', async () => {
const get = vi.fn().mockResolvedValue(features('https://sso.example.com/login'))
expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' })
})
const get = vi.fn().mockResolvedValue(features('https://sso.example.com/login'));
expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
});
it('moves on to plain http when https cannot be reached', async () => {
const get = vi.fn()
const get = vi
.fn()
.mockRejectedValueOnce(new Error('ECONNREFUSED'))
.mockResolvedValueOnce(features('http://192.168.1.10:3001/api/health/features'))
expect(await probeServer('192.168.1.10:3001', get)).toEqual({ ok: true, url: 'http://192.168.1.10:3001' })
expect(get).toHaveBeenNthCalledWith(2, 'http://192.168.1.10:3001/api/health/features')
})
.mockResolvedValueOnce(features('http://192.168.1.10:3001/api/health/features'));
expect(await probeServer('192.168.1.10:3001', get)).toEqual({ ok: true, url: 'http://192.168.1.10:3001' });
expect(get).toHaveBeenNthCalledWith(2, 'http://192.168.1.10:3001/api/health/features');
});
it('names a TREK server without the native flag as too old', async () => {
const get = vi.fn().mockResolvedValue(features('https://old.example.com/api/health/features', { bookingImport: true, aiParsing: false }))
expect(await probeServer('https://old.example.com', get)).toEqual({ ok: false, reason: 'tooOld' })
})
const get = vi
.fn()
.mockResolvedValue(
features('https://old.example.com/api/health/features', { bookingImport: true, aiParsing: false })
);
expect(await probeServer('https://old.example.com', get)).toEqual({ ok: false, reason: 'tooOld' });
});
it('tells a server that is not TREK apart from one that is not there', async () => {
const html = vi.fn().mockResolvedValue({ status: 200, data: '<html>', url: 'https://x.example.com/api/health/features' })
expect(await probeServer('https://x.example.com', html)).toEqual({ ok: false, reason: 'notTrek' })
const html = vi
.fn()
.mockResolvedValue({ status: 200, data: '<html>', url: 'https://x.example.com/api/health/features' });
expect(await probeServer('https://x.example.com', html)).toEqual({ ok: false, reason: 'notTrek' });
const missing = vi.fn().mockResolvedValue({ status: 404, data: {}, url: 'https://x.example.com/api/health/features' })
expect(await probeServer('https://x.example.com', missing)).toEqual({ ok: false, reason: 'notTrek' })
const missing = vi
.fn()
.mockResolvedValue({ status: 404, data: {}, url: 'https://x.example.com/api/health/features' });
expect(await probeServer('https://x.example.com', missing)).toEqual({ ok: false, reason: 'notTrek' });
const down = vi.fn().mockRejectedValue(new Error('timeout'))
expect(await probeServer('x.example.com', down)).toEqual({ ok: false, reason: 'unreachable' })
})
const down = vi.fn().mockRejectedValue(new Error('timeout'));
expect(await probeServer('x.example.com', down)).toEqual({ ok: false, reason: 'unreachable' });
});
it('keeps the most telling failure across candidates', async () => {
const get = vi.fn()
const get = vi
.fn()
.mockResolvedValueOnce(features('https://nas.local/api/health/features', { bookingImport: false }))
.mockRejectedValueOnce(new Error('ECONNREFUSED'))
expect(await probeServer('nas.local', get)).toEqual({ ok: false, reason: 'tooOld' })
})
.mockRejectedValueOnce(new Error('ECONNREFUSED'));
expect(await probeServer('nas.local', get)).toEqual({ ok: false, reason: 'tooOld' });
});
it('refuses input that is not an address', async () => {
const get = vi.fn()
expect(await probeServer('', get)).toEqual({ ok: false, reason: 'invalid' })
expect(get).not.toHaveBeenCalled()
})
})
const get = vi.fn();
expect(await probeServer('', get)).toEqual({ ok: false, reason: 'invalid' });
expect(get).not.toHaveBeenCalled();
});
});
+31 -33
View File
@@ -3,30 +3,28 @@
* can load, or a reason it cannot.
*/
export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'tooOld'
type ProbeResult =
| { ok: true; url: string; reason?: undefined }
| { ok: false; reason: ProbeFailure; url?: undefined }
export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'tooOld';
type ProbeResult = { ok: true; url: string; reason?: undefined } | { ok: false; reason: ProbeFailure; url?: undefined };
export interface ProbeResponse {
status: number
data: unknown
status: number;
data: unknown;
/** The URL after redirects. */
url: string
url: string;
}
export type ProbeGet = (url: string) => Promise<ProbeResponse>
export type ProbeGet = (url: string) => Promise<ProbeResponse>;
const FEATURES_PATH = '/api/health/features'
const FEATURES_PATH = '/api/health/features';
function normalize(raw: string): string | null {
let parsed: URL
let parsed: URL;
try {
parsed = new URL(raw)
parsed = new URL(raw);
} catch {
return null
return null;
}
if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || !parsed.hostname) return null
return parsed.origin + parsed.pathname.replace(/\/+$/, '')
if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || !parsed.hostname) return null;
return parsed.origin + parsed.pathname.replace(/\/+$/, '');
}
/**
@@ -34,45 +32,45 @@ function normalize(raw: string): string | null {
* home network is often reached as a bare IP and port without TLS.
*/
export function candidateUrls(input: string): string[] {
const trimmed = input.trim()
if (!trimmed) return []
const trimmed = input.trim();
if (!trimmed) return [];
const candidates = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)
? [normalize(trimmed)]
: [normalize(`https://${trimmed}`), normalize(`http://${trimmed}`)]
return candidates.filter((url): url is string => url !== null)
: [normalize(`https://${trimmed}`), normalize(`http://${trimmed}`)];
return candidates.filter((url): url is string => url !== null);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
return typeof value === 'object' && value !== null;
}
function judge(response: ProbeResponse): ProbeResult {
if (response.status !== 200 || !isRecord(response.data)) return { ok: false, reason: 'notTrek' }
if (response.status !== 200 || !isRecord(response.data)) return { ok: false, reason: 'notTrek' };
if (response.data.nativeApp === true) {
// Follow a redirect (http to https, a canonical host) so the app loads the
// address the server actually answers on.
const base = response.url.endsWith(FEATURES_PATH) ? response.url.slice(0, -FEATURES_PATH.length) : null
return { ok: true, url: (base && normalize(base)) || '' }
const base = response.url.endsWith(FEATURES_PATH) ? response.url.slice(0, -FEATURES_PATH.length) : null;
return { ok: true, url: (base && normalize(base)) || '' };
}
return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' }
return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' };
}
const FAILURE_RANK: Record<ProbeFailure, number> = { invalid: 0, unreachable: 1, notTrek: 2, tooOld: 3 }
const FAILURE_RANK: Record<ProbeFailure, number> = { invalid: 0, unreachable: 1, notTrek: 2, tooOld: 3 };
export async function probeServer(input: string, get: ProbeGet): Promise<ProbeResult> {
const candidates = candidateUrls(input)
if (!candidates.length) return { ok: false, reason: 'invalid' }
const candidates = candidateUrls(input);
if (!candidates.length) return { ok: false, reason: 'invalid' };
let failure: ProbeFailure = 'unreachable'
let failure: ProbeFailure = 'unreachable';
for (const candidate of candidates) {
let verdict: ProbeResult
let verdict: ProbeResult;
try {
verdict = judge(await get(candidate + FEATURES_PATH))
verdict = judge(await get(candidate + FEATURES_PATH));
} catch {
continue
continue;
}
if (verdict.ok) return { ok: true, url: verdict.url || candidate }
if (FAILURE_RANK[verdict.reason] > FAILURE_RANK[failure]) failure = verdict.reason
if (verdict.ok) return { ok: true, url: verdict.url || candidate };
if (FAILURE_RANK[verdict.reason] > FAILURE_RANK[failure]) failure = verdict.reason;
}
return { ok: false, reason: failure }
return { ok: false, reason: failure };
}
+10 -10
View File
@@ -1,4 +1,4 @@
import { registerPlugin } from '@capacitor/core'
import { registerPlugin } from '@capacitor/core';
/**
* The app's own native plugin, implemented in
@@ -12,25 +12,25 @@ import { registerPlugin } from '@capacitor/core'
* worker.
*/
export interface TrekShellPlugin {
getServer(): Promise<{ url: string | null }>
getServer(): Promise<{ url: string | null }>;
/** Remembers the server and loads it. The current page is gone afterwards. */
setServer(options: { url: string }): Promise<void>
setServer(options: { url: string }): Promise<void>;
/** Forgets the server and returns to the address screen. */
resetServer(): Promise<void>
resetServer(): Promise<void>;
/** Loads the remembered server again, after it could not be reached. */
reload(): Promise<void>
reload(): Promise<void>;
/**
* Opens `url` in the system browser and resolves with the URL it was sent
* back to under `callbackScheme`. Rejects with code `CANCELLED` when the
* user closes the browser.
*/
authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>
authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>;
/** iOS: stores the server's start page for a cold start without network. */
refreshOfflineCopy(): Promise<{ saved: boolean }>
refreshOfflineCopy(): Promise<{ saved: boolean }>;
/** iOS: loads that copy under the server's origin. False when there is none. */
openOfflineCopy(): Promise<{ opened: boolean }>
openOfflineCopy(): Promise<{ opened: boolean }>;
}
export const TrekShell = registerPlugin<TrekShellPlugin>('TrekShell')
export const TrekShell = registerPlugin<TrekShellPlugin>('TrekShell');
export const APP_URL_SCHEME = 'com.liketrek.trek'
export const APP_URL_SCHEME = 'com.liketrek.trek';