mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 05:21:15 +00:00
Merge dev into feat/native-apps
Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:
- server: /api/auth/native moves onto injected services. The session is
minted by the auth domain's new LoginSessionService (login bookkeeping and
SessionsService.issue in one transaction), the one-time codes live behind a
NativeHandoffStore port with a capped in-memory implementation that drops
expired codes on write instead of running a timer, both routes declare
response contracts, and the exchange answers { success: true }. Unit and
e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
(useAccountSettings, useTripExport), the native server card is a
desktop/phone pair on useNativeServer, the hand-off call moves out of the
page hook into native/, best-effort native failures go through
reportError instead of the console, and the address screen is known to
knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
@@ -1,12 +1,12 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { sha256 } from '@noble/hashes/sha2'
|
||||
import { bytesToHex } from '@noble/hashes/utils'
|
||||
import { BrowserSignInCancelled, createHandoffSecret, handoffUrl, signInThroughBrowser } from './browserSignIn'
|
||||
import { BrowserSignInCancelled, createHandoffSecret, handoffUrl, requestHandoffCode, signInThroughBrowser } from './browserSignIn'
|
||||
import { TrekShell } from './trekShell'
|
||||
import { nativeAuthApi } from '../api/nativeAuth'
|
||||
|
||||
vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } }))
|
||||
vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn() } }))
|
||||
vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } }))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(TrekShell.authenticate).mockReset()
|
||||
@@ -22,6 +22,14 @@ describe('createHandoffSecret', () => {
|
||||
})
|
||||
})
|
||||
|
||||
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))
|
||||
})
|
||||
})
|
||||
|
||||
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')
|
||||
|
||||
@@ -35,6 +35,12 @@ export function handoffUrl(origin: string, challenge: string, start?: BrowserSig
|
||||
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
|
||||
}
|
||||
|
||||
export class BrowserSignInCancelled extends Error {
|
||||
constructor() {
|
||||
super('Sign-in cancelled')
|
||||
|
||||
@@ -32,9 +32,11 @@ describe('toastHaptic', () => {
|
||||
})
|
||||
|
||||
it('does not let a missing vibrator surface as an error', async () => {
|
||||
const debug = vi.spyOn(console, 'debug').mockImplementation(() => {})
|
||||
const report = vi.fn()
|
||||
vi.stubGlobal('reportError', report)
|
||||
vi.mocked(Haptics.notification).mockRejectedValue(new Error('not available'))
|
||||
toastHaptic('error')
|
||||
await vi.waitFor(() => expect(debug).toHaveBeenCalledWith('[haptics]', expect.any(Error)))
|
||||
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)))
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Haptics, NotificationType } from '@capacitor/haptics'
|
||||
import { isNativeApp } from './platform'
|
||||
import { reportNativeFailure } from './reportFailure'
|
||||
|
||||
const FEEDBACK: Record<string, NotificationType | undefined> = {
|
||||
success: NotificationType.Success,
|
||||
@@ -15,5 +16,5 @@ const FEEDBACK: Record<string, NotificationType | undefined> = {
|
||||
export function toastHaptic(type: string): void {
|
||||
const feedback = FEEDBACK[type]
|
||||
if (!feedback || !isNativeApp()) return
|
||||
Haptics.notification({ type: feedback }).catch((err) => console.debug('[haptics]', err))
|
||||
Haptics.notification({ type: feedback }).catch(reportNativeFailure)
|
||||
}
|
||||
|
||||
@@ -98,9 +98,11 @@ describe('startNativeApp', () => {
|
||||
it('logs a failed refresh instead of throwing', async () => {
|
||||
vi.mocked(isNativeIos).mockReturnValue(true)
|
||||
vi.mocked(keepOfflineShellFresh).mockRejectedValue(new Error('down'))
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const report = vi.fn()
|
||||
vi.stubGlobal('reportError', report)
|
||||
startNativeApp()
|
||||
vi.advanceTimersByTime(15_000)
|
||||
await vi.waitFor(() => expect(warn).toHaveBeenCalled())
|
||||
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)))
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,6 +4,7 @@ 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'
|
||||
|
||||
/** Long enough that the warm-up never competes with the first screen's requests. */
|
||||
@@ -32,7 +33,8 @@ export function startNativeApp(): void {
|
||||
void Keyboard.setAccessoryBarVisible({ isVisible: false })
|
||||
window.setTimeout(() => {
|
||||
if (isEffectivelyOffline()) return
|
||||
keepOfflineShellFresh().catch((err) => console.warn('[native] offline start page not refreshed', err))
|
||||
// Not refreshed this time is no harm: the next launch tries again.
|
||||
keepOfflineShellFresh().catch(reportNativeFailure)
|
||||
}, OFFLINE_SHELL_DELAY_MS)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@ export function cacheFileName(filename: string): string {
|
||||
}
|
||||
|
||||
export function fileNameFromUrl(url: string): string {
|
||||
const last = url.split('?')[0]!.split('/').filter(Boolean).pop() ?? ''
|
||||
const [path = ''] = url.split('?', 1)
|
||||
const last = path.split('/').filter(Boolean).pop() ?? ''
|
||||
try {
|
||||
return decodeURIComponent(last)
|
||||
} catch {
|
||||
|
||||
@@ -35,8 +35,11 @@ async function warmCache(files: string[], fetchFile: (path: string) => Promise<u
|
||||
const queue = [...files]
|
||||
const worker = async (): Promise<void> => {
|
||||
for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
|
||||
// One missing chunk must not stop the rest; the next launch tries again.
|
||||
await fetchFile(`/${path}`).catch(() => undefined)
|
||||
try {
|
||||
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))
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('reportNativeFailure', () => {
|
||||
it('hands the failure to the page error event', () => {
|
||||
const report = vi.fn();
|
||||
vi.stubGlobal('reportError', report);
|
||||
const err = new Error('share failed');
|
||||
reportNativeFailure(err);
|
||||
expect(report).toHaveBeenCalledWith(err);
|
||||
});
|
||||
|
||||
it('does nothing where the runtime has no reportError', () => {
|
||||
vi.stubGlobal('reportError', undefined);
|
||||
expect(() => reportNativeFailure(new Error('x'))).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* For the app's best-effort calls (a haptic tap, the offline start page, a
|
||||
* share sheet): the failure is not worth a toast, but it must not vanish
|
||||
* either. reportError() hands it to the page's error event, which
|
||||
* utils/globalErrorHandlers.ts logs like any other uncaught error.
|
||||
*/
|
||||
export function reportNativeFailure(err: unknown): void {
|
||||
if (typeof globalThis.reportError === 'function') globalThis.reportError(err);
|
||||
}
|
||||
Reference in New Issue
Block a user