mirror of
https://git.um-react.app/um/um-react.git
synced 2026-11-25 06:46:59 +00:00
feat: integrate platform provider with enhanced crypto handling and new AppLayout component
- Added a new `AppLayout` component to manage navigation and routing within the application. - Refactored `AppRoot` to utilize `PlatformLoadGuard` for ensuring platform readiness before rendering. - Introduced `useAppStore` hook for accessing the Redux store directly. - Updated `SDKVersion` and `PanelQingTing` components to leverage the new platform provider for crypto operations. - Enhanced error handling with `PlatformNotInitializedError` for better user feedback on uninitialized platform states. - Added tests for new functionalities and ensured compatibility with the updated platform architecture.
This commit is contained in:
1 parent
cb5531e9e4
commit
b5fdc8ebbe
18 files changed
+466
-102
No files matched your search
@@ -1,19 +1,28 @@
|
||||
import { renderWithProviders, screen, waitFor } from '~/test-utils/test-helper';
|
||||
import { act, renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||
import { AppRoot } from '~/components/AppRoot';
|
||||
|
||||
vi.mock('../decrypt-worker/client', () => {
|
||||
// Must match the dynamic import specifier used by browserCrypto (`~/decrypt-worker/client`).
|
||||
// Plain functions: vitest `mockReset` clears vi.fn mockResolvedValue between tests.
|
||||
vi.mock('~/decrypt-worker/client', () => {
|
||||
return {
|
||||
workerClientBus: {
|
||||
request: vi.fn().mockResolvedValue('dummy'),
|
||||
request: () => Promise.resolve('dummy'),
|
||||
},
|
||||
decryptionQueue: {
|
||||
add: () => Promise.resolve({ decrypted: 'blob://dummy', ext: 'flac' }),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
test('should be able to render App', async () => {
|
||||
renderWithProviders(<AppRoot />);
|
||||
await act(async () => {
|
||||
renderWithProviders(<AppRoot />);
|
||||
// Flush Suspense retry after platform.init() (dynamic import) settles.
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// Should eventually load sdk version
|
||||
await waitFor(() => screen.getByTestId('sdk-version'));
|
||||
// Platform Suspense gate + SDK version fetch
|
||||
expect(await screen.findByTestId('sdk-version')).toBeInTheDocument();
|
||||
|
||||
// Quick sanity check of known strings.
|
||||
expect(screen.getByText(/音乐解锁/i)).toBeInTheDocument();
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { NavLink, Route, Routes } from 'react-router';
|
||||
import { MdHome, MdQuestionAnswer, MdSettings } from 'react-icons/md';
|
||||
import { Bounce, ToastContainer } from 'react-toastify';
|
||||
|
||||
import { Footer } from '~/components/Footer';
|
||||
import { FaqHome } from '~/faq/FaqHome';
|
||||
import { FAQ_PAGES } from '~/faq/FAQPages';
|
||||
import { SettingsHome } from '~/features/settings/SettingsHome';
|
||||
import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
|
||||
import { FaqTab } from '~/tabs/FaqTab';
|
||||
import { MainTab } from '~/tabs/MainTab';
|
||||
import { SettingsTab } from '~/tabs/SettingsTab';
|
||||
|
||||
const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
|
||||
|
||||
/** Main chrome (nav / routes / toast / footer). Render only after platform `init()` resolves. */
|
||||
export function AppLayout() {
|
||||
return (
|
||||
<>
|
||||
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
|
||||
<NavLink to="/" role="tab" className={tabClassNames}>
|
||||
<MdHome />
|
||||
应用
|
||||
</NavLink>
|
||||
<NavLink to="/settings" role="tab" className={tabClassNames}>
|
||||
<MdSettings />
|
||||
设置
|
||||
</NavLink>
|
||||
<NavLink to="/questions" role="tab" className={tabClassNames}>
|
||||
<MdQuestionAnswer />
|
||||
答疑
|
||||
</NavLink>
|
||||
</div>
|
||||
|
||||
<main className="flex-1 flex justify-center min-h-0 overflow-auto">
|
||||
<Routes>
|
||||
<Route path="/" Component={MainTab} />
|
||||
<Route path="/settings" Component={SettingsTab}>
|
||||
<Route index Component={SettingsHome} />
|
||||
{Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
|
||||
<Route key={key} path={key} Component={Tab} />
|
||||
))}
|
||||
</Route>
|
||||
<Route path="/questions" Component={FaqTab}>
|
||||
<Route index Component={FaqHome} />
|
||||
{FAQ_PAGES.map(({ id, Component }) => (
|
||||
<Route key={id} path={id} Component={Component} />
|
||||
))}
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
|
||||
<ToastContainer
|
||||
position="bottom-center"
|
||||
autoClose={5000}
|
||||
newestOnTop
|
||||
closeOnClick={false}
|
||||
pauseOnFocusLoss
|
||||
draggable
|
||||
theme="colored"
|
||||
transition={Bounce}
|
||||
/>
|
||||
|
||||
<Footer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
+24
-64
@@ -1,83 +1,43 @@
|
||||
import { useEffect } from 'react';
|
||||
import { BrowserRouter, NavLink, Route, Routes } from 'react-router';
|
||||
import { MdSettings, MdHome, MdQuestionAnswer } from 'react-icons/md';
|
||||
|
||||
import { MainTab } from '~/tabs/MainTab';
|
||||
import { SettingsTab } from '~/tabs/SettingsTab';
|
||||
|
||||
import { Suspense } from 'react';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { Provider } from 'react-redux';
|
||||
|
||||
import { AppLayout } from '~/components/AppLayout';
|
||||
import { persistSettings } from '~/features/settings/persistSettings';
|
||||
import { setupStore } from '~/store';
|
||||
import { Footer } from '~/components/Footer';
|
||||
import { FaqTab } from '~/tabs/FaqTab';
|
||||
import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
|
||||
import { Bounce, ToastContainer } from 'react-toastify';
|
||||
import { SettingsHome } from '~/features/settings/SettingsHome';
|
||||
import { FAQ_PAGES } from '~/faq/FAQPages';
|
||||
import { FaqHome } from '~/faq/FaqHome';
|
||||
import { createPlatformProvider } from '~/platform/createPlatformProvider';
|
||||
import { PlatformLoadGuard } from '~/platform/PlatformLoadGuard';
|
||||
import { PlatformProviderHost } from '~/platform/PlatformContext';
|
||||
import { setPlatform } from '~/platform/platformSingleton';
|
||||
import { setupStore } from '~/store';
|
||||
|
||||
// Private to this file only.
|
||||
const store = setupStore();
|
||||
const platform = createPlatformProvider();
|
||||
setPlatform(platform);
|
||||
|
||||
const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
|
||||
const platformReady = platform.init().then(() => {
|
||||
setPlatform(platform);
|
||||
persistSettings(store, platform);
|
||||
});
|
||||
|
||||
function AppBootFallback() {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center min-h-0" role="status" aria-live="polite">
|
||||
<span className="loading loading-spinner loading-lg text-primary" />
|
||||
<span className="sr-only">加载中</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AppRoot() {
|
||||
useEffect(() => persistSettings(store, platform), []);
|
||||
|
||||
return (
|
||||
<BrowserRouter basename={window.BASE_URL || '/'}>
|
||||
<Provider store={store}>
|
||||
<PlatformProviderHost provider={platform}>
|
||||
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
|
||||
<NavLink to="/" role="tab" className={tabClassNames}>
|
||||
<MdHome />
|
||||
应用
|
||||
</NavLink>
|
||||
<NavLink to="/settings" role="tab" className={tabClassNames}>
|
||||
<MdSettings />
|
||||
设置
|
||||
</NavLink>
|
||||
<NavLink to="/questions" role="tab" className={tabClassNames}>
|
||||
<MdQuestionAnswer />
|
||||
答疑
|
||||
</NavLink>
|
||||
</div>
|
||||
|
||||
<main className="flex-1 flex justify-center min-h-0 overflow-auto">
|
||||
<Routes>
|
||||
<Route path="/" Component={MainTab} />
|
||||
<Route path="/settings" Component={SettingsTab}>
|
||||
<Route index Component={SettingsHome} />
|
||||
{Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
|
||||
<Route key={key} path={key} Component={Tab} />
|
||||
))}
|
||||
</Route>
|
||||
<Route path="/questions" Component={FaqTab}>
|
||||
<Route index Component={FaqHome} />
|
||||
{FAQ_PAGES.map(({ id, Component }) => (
|
||||
<Route key={id} path={id} Component={Component} />
|
||||
))}
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
|
||||
<ToastContainer
|
||||
position="bottom-center"
|
||||
autoClose={5000}
|
||||
newestOnTop
|
||||
closeOnClick={false}
|
||||
pauseOnFocusLoss
|
||||
draggable
|
||||
theme="colored"
|
||||
transition={Bounce}
|
||||
/>
|
||||
|
||||
<Footer />
|
||||
<Suspense fallback={<AppBootFallback />}>
|
||||
<PlatformLoadGuard ready={platformReady}>
|
||||
<AppLayout />
|
||||
</PlatformLoadGuard>
|
||||
</Suspense>
|
||||
</PlatformProviderHost>
|
||||
</Provider>
|
||||
</BrowserRouter>
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import { MdInfoOutline } from 'react-icons/md';
|
||||
import { workerClientBus } from '~/decrypt-worker/client';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
const getSDKVersion = async (): Promise<string> => {
|
||||
return workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
|
||||
};
|
||||
|
||||
export function SDKVersion() {
|
||||
const { crypto } = usePlatform();
|
||||
const refDialog = useRef<HTMLDialogElement>(null);
|
||||
const [sdkVersion, setSdkVersion] = useState('...');
|
||||
useEffect(() => {
|
||||
getSDKVersion().then(setSdkVersion, () => setSdkVersion('N/A'));
|
||||
}, []);
|
||||
crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null).then(setSdkVersion, () => setSdkVersion('N/A'));
|
||||
}, [crypto]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { WorkerActionName } from '~/decrypt-worker/actions';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||
import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import { setPlatform } from '~/platform/platformSingleton';
|
||||
import { setupStore } from '~/store';
|
||||
import { ListingMode, ProcessState, processFile, selectFiles } from '../fileListingSlice';
|
||||
import { untouchedFile } from './__fixture__/file-list';
|
||||
|
||||
describe('processFile', () => {
|
||||
test('parses headers via platform.crypto then enqueueDecrypts', async () => {
|
||||
const request = vi.fn((action: WorkerActionName) => {
|
||||
if (action === 'FIND_QMC_MUSICEX_NAME') {
|
||||
return Promise.resolve('track.mflac');
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
const enqueueDecrypt = vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' });
|
||||
const crypto: BrowserCrypto = { request, enqueueDecrypt };
|
||||
setPlatform(createBrowserProvider({ crypto }));
|
||||
|
||||
const fileId = 'file://untouched';
|
||||
const store = setupStore({
|
||||
fileListing: {
|
||||
files: { [fileId]: { ...untouchedFile } },
|
||||
displayMode: ListingMode.LIST,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await store.dispatch(processFile({ fileId }));
|
||||
|
||||
expect(result.type).toBe(processFile.fulfilled.type);
|
||||
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||
blobURI: untouchedFile.raw,
|
||||
});
|
||||
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
||||
blobURI: untouchedFile.raw,
|
||||
});
|
||||
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
||||
blobURI: untouchedFile.raw,
|
||||
});
|
||||
expect(enqueueDecrypt).toHaveBeenCalledTimes(1);
|
||||
const [decryptPayload, onPreProcess] = enqueueDecrypt.mock.calls[0] as [
|
||||
{ fileId: string; blobURI: string; options: { fileName: string } },
|
||||
() => void,
|
||||
];
|
||||
expect(decryptPayload).toMatchObject({
|
||||
fileId,
|
||||
blobURI: untouchedFile.raw,
|
||||
options: { fileName: untouchedFile.fileName },
|
||||
});
|
||||
expect(typeof onPreProcess).toBe('function');
|
||||
|
||||
const file = selectFiles(store.getState())[fileId];
|
||||
expect(file.state).toBe(ProcessState.COMPLETE);
|
||||
expect(file.decrypted).toBe('blob://out');
|
||||
expect(file.ext).toBe('flac');
|
||||
});
|
||||
|
||||
test('rejects when file id is missing', async () => {
|
||||
const crypto: BrowserCrypto = {
|
||||
request: vi.fn(),
|
||||
enqueueDecrypt: vi.fn(),
|
||||
};
|
||||
setPlatform(createBrowserProvider({ crypto }));
|
||||
const store = setupStore({
|
||||
fileListing: {
|
||||
files: {},
|
||||
displayMode: ListingMode.LIST,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await store.dispatch(processFile({ fileId: 'missing' }));
|
||||
expect(result.type).toBe(processFile.rejected.type);
|
||||
});
|
||||
});
|
||||
@@ -4,12 +4,12 @@ import type { RootState } from '~/store';
|
||||
|
||||
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
|
||||
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
|
||||
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
|
||||
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
|
||||
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
|
||||
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
|
||||
import { selectKugouKey } from '~/features/kugou/keyLookup';
|
||||
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
||||
import { getPlatform } from '~/platform/platformSingleton';
|
||||
import { cleanFilename } from '~/util/cleanFilename';
|
||||
|
||||
export enum ProcessState {
|
||||
@@ -70,14 +70,15 @@ export const processFile = createAsyncThunk<
|
||||
thunkAPI.dispatch(setFileAsProcessing({ id: fileId }));
|
||||
};
|
||||
|
||||
const { crypto } = getPlatform();
|
||||
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
|
||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||
crypto.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
||||
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
||||
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
]);
|
||||
@@ -89,7 +90,7 @@ export const processFile = createAsyncThunk<
|
||||
kugouKey: selectKugouKey(state, kugouHdr),
|
||||
qingTingAndroidKey: selectQtfmAndroidKey(state),
|
||||
};
|
||||
return decryptionQueue.add({ fileId, blobURI: file.raw, options }, onPreProcess);
|
||||
return crypto.enqueueDecrypt({ fileId, blobURI: file.raw, options }, onPreProcess);
|
||||
});
|
||||
|
||||
export const fileListingSlice = createSlice({
|
||||
|
||||
@@ -6,14 +6,15 @@ import { selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
||||
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
|
||||
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
|
||||
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
|
||||
import { workerClientBus } from '~/decrypt-worker/client.ts';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
|
||||
|
||||
export function PanelQingTing() {
|
||||
const dispatch = useAppDispatch();
|
||||
const { crypto } = usePlatform();
|
||||
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
|
||||
const setSecretKey = (secretKey: string) => {
|
||||
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
|
||||
@@ -31,7 +32,7 @@ export function PanelQingTing() {
|
||||
const dataMap = parseQtfmDeviceInfoFromText(plainText);
|
||||
if (dataMap) {
|
||||
e.preventDefault();
|
||||
workerClientBus
|
||||
crypto
|
||||
.request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
|
||||
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { useDispatch, useSelector, useStore } from 'react-redux';
|
||||
import type { TypedUseSelectorHook } from 'react-redux';
|
||||
import type { RootState, AppDispatch } from './store';
|
||||
import type { RootState, AppDispatch, AppStore } from './store';
|
||||
|
||||
export const useAppDispatch: () => AppDispatch = useDispatch;
|
||||
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
||||
export const useAppStore: () => AppStore = useStore;
|
||||
@@ -0,0 +1,10 @@
|
||||
import { use, type PropsWithChildren, type ReactNode } from 'react';
|
||||
|
||||
/**
|
||||
* Suspends children until `ready` fulfills (e.g. `provider.init()` + `setPlatform`).
|
||||
* Must be wrapped in `<Suspense fallback={...}>`.
|
||||
*/
|
||||
export function PlatformLoadGuard({ ready, children }: PropsWithChildren<{ ready: Promise<unknown> }>): ReactNode {
|
||||
use(ready);
|
||||
return children;
|
||||
}
|
||||
@@ -19,6 +19,8 @@ import type {
|
||||
* - Every provider implements **all** methods; never omit methods or silently no-op.
|
||||
* - Capability missing / platform will never support → `NotSupportedMethod`.
|
||||
* - Declared / planned but not wired yet (stub) → `NotImplementedError`.
|
||||
* - Heavy backends (e.g. decrypt worker) load only inside `init()`; constructing the provider
|
||||
* and reading `crypto` must not create a Worker or fetch the worker chunk.
|
||||
* - `capabilities` is the only UI switch source; UI must not call `supportsDirectoryPicker()` etc.
|
||||
* (those helpers stay for BrowserProvider internal capability detection).
|
||||
*/
|
||||
@@ -26,7 +28,17 @@ export interface PlatformProvider {
|
||||
readonly id: 'browser' | 'tauri';
|
||||
readonly capabilities: PlatformCapabilities;
|
||||
|
||||
/** RPC aligned with `WorkerActionMap`; UI should not import `decrypt-worker/client`. */
|
||||
/**
|
||||
* One-shot async setup (idempotent). Browser: dynamically import decrypt-worker/client and create Worker.
|
||||
* Must complete before the first successful `crypto.request` / `enqueueDecrypt` (unless a test injects crypto).
|
||||
* May run in parallel with `settings.load`.
|
||||
*/
|
||||
init(): Promise<void>;
|
||||
|
||||
/**
|
||||
* RPC aligned with `WorkerActionMap`; UI should not import `decrypt-worker/client`.
|
||||
* Obtaining this object has no side effects (no Worker).
|
||||
*/
|
||||
crypto: {
|
||||
request<K extends WorkerActionName>(
|
||||
action: K,
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { AndroidImportType, BatchDownloadType } from '~/platform/capabilities';
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
|
||||
import { createPlatformProvider } from '~/platform/createPlatformProvider';
|
||||
import { NotImplementedError, NotSupportedMethod } from '~/platform/errors';
|
||||
import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||
|
||||
function createMockCrypto(overrides: Partial<BrowserCrypto> = {}): BrowserCrypto {
|
||||
return {
|
||||
request: vi.fn().mockResolvedValue('9.9.9'),
|
||||
enqueueDecrypt: vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' }),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BrowserProvider', () => {
|
||||
test('jsdom without directory/save pickers exposes only PackZip', () => {
|
||||
@@ -34,10 +43,80 @@ describe('BrowserProvider', () => {
|
||||
await expect(provider.keys.importAndroidAdb({})).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||
});
|
||||
|
||||
test('unwired browser methods throw NotImplementedError', async () => {
|
||||
const provider = createBrowserProvider();
|
||||
test('crypto before init rejects with PlatformNotInitializedError', async () => {
|
||||
const loadCrypto = vi.fn();
|
||||
const provider = createBrowserProvider({ loadCrypto });
|
||||
|
||||
await expect(provider.crypto.request('VERSION', null)).rejects.toSatisfy((err: unknown) => {
|
||||
return (
|
||||
err instanceof PlatformNotInitializedError &&
|
||||
err.code === 'NOT_INITIALIZED' &&
|
||||
err.capability === 'crypto.request'
|
||||
);
|
||||
});
|
||||
expect(loadCrypto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('constructing provider does not call loadCrypto', () => {
|
||||
const loadCrypto = vi.fn();
|
||||
createBrowserProvider({ loadCrypto });
|
||||
expect(loadCrypto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('init loads crypto once and is idempotent under concurrency', async () => {
|
||||
const request = vi.fn().mockResolvedValue('9.9.9');
|
||||
const loadCrypto = vi.fn().mockResolvedValue(createMockCrypto({ request }));
|
||||
const provider = createBrowserProvider({ loadCrypto });
|
||||
|
||||
await Promise.all([provider.init(), provider.init()]);
|
||||
await provider.init();
|
||||
|
||||
expect(loadCrypto).toHaveBeenCalledTimes(1);
|
||||
await expect(provider.crypto.request('VERSION', null)).resolves.toBe('9.9.9');
|
||||
expect(request).toHaveBeenCalledWith('VERSION', null);
|
||||
});
|
||||
|
||||
test('crypto.* waits for in-flight init', async () => {
|
||||
let resolveLoad!: (value: BrowserCrypto) => void;
|
||||
const loadCrypto = vi.fn(
|
||||
() =>
|
||||
new Promise<BrowserCrypto>((resolve) => {
|
||||
resolveLoad = resolve;
|
||||
}),
|
||||
);
|
||||
const provider = createBrowserProvider({ loadCrypto });
|
||||
|
||||
const initPromise = provider.init();
|
||||
const requestPromise = provider.crypto.request('VERSION', null);
|
||||
|
||||
resolveLoad(createMockCrypto());
|
||||
await initPromise;
|
||||
await expect(requestPromise).resolves.toBe('9.9.9');
|
||||
});
|
||||
|
||||
test('crypto uses injected backend without init', async () => {
|
||||
const request = vi.fn().mockResolvedValue('injected');
|
||||
const enqueueDecrypt = vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' });
|
||||
const loadCrypto = vi.fn();
|
||||
const provider = createBrowserProvider({ crypto: { request, enqueueDecrypt }, loadCrypto });
|
||||
|
||||
await expect(provider.crypto.request('VERSION', null)).resolves.toBe('injected');
|
||||
await expect(
|
||||
provider.crypto.enqueueDecrypt({
|
||||
fileId: 'file://1',
|
||||
blobURI: 'blob://in',
|
||||
options: { fileName: 'a.bin' },
|
||||
}),
|
||||
).resolves.toEqual({ decrypted: 'blob://out', ext: 'flac' });
|
||||
await expect(provider.init()).resolves.toBeUndefined();
|
||||
expect(loadCrypto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('unwired download methods throw NotImplementedError', async () => {
|
||||
const provider = createBrowserProvider({
|
||||
crypto: createMockCrypto(),
|
||||
});
|
||||
|
||||
await expect(provider.crypto.request('VERSION', null)).rejects.toBeInstanceOf(NotImplementedError);
|
||||
await expect(provider.download.saveOne({ url: 'blob:x', fileName: 'a.flac' })).rejects.toBeInstanceOf(
|
||||
NotImplementedError,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { loadDecryptWorkerCrypto } from '~/platform/browser/browserCrypto';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||
|
||||
const { mockRequest, mockAdd } = vi.hoisted(() => ({
|
||||
mockRequest: vi.fn(),
|
||||
mockAdd: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('~/decrypt-worker/client', () => ({
|
||||
workerClientBus: {
|
||||
request: mockRequest,
|
||||
},
|
||||
decryptionQueue: {
|
||||
add: mockAdd,
|
||||
},
|
||||
}));
|
||||
|
||||
describe('loadDecryptWorkerCrypto', () => {
|
||||
beforeEach(() => {
|
||||
mockRequest.mockResolvedValue('1.2.3');
|
||||
mockAdd.mockResolvedValue({ decrypted: 'blob://d', ext: 'mp3' });
|
||||
});
|
||||
|
||||
test('request forwards to workerClientBus after dynamic import', async () => {
|
||||
const crypto = await loadDecryptWorkerCrypto();
|
||||
|
||||
await expect(crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null)).resolves.toBe('1.2.3');
|
||||
expect(mockRequest).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
|
||||
});
|
||||
|
||||
test('enqueueDecrypt forwards to decryptionQueue.add after dynamic import', async () => {
|
||||
const crypto = await loadDecryptWorkerCrypto();
|
||||
const onPreProcess = vi.fn();
|
||||
const payload = {
|
||||
fileId: 'file://1',
|
||||
blobURI: 'blob://in',
|
||||
options: { fileName: 'a.bin' },
|
||||
};
|
||||
|
||||
await expect(crypto.enqueueDecrypt(payload, onPreProcess)).resolves.toEqual({
|
||||
decrypted: 'blob://d',
|
||||
ext: 'mp3',
|
||||
});
|
||||
expect(mockAdd).toHaveBeenCalledWith(payload, onPreProcess);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||
import { NotImplementedError, NotSupportedMethod } from '~/platform/errors';
|
||||
import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||
|
||||
describe('platform capabilities enums', () => {
|
||||
test('BatchDownloadType members stay stable', () => {
|
||||
@@ -74,3 +74,16 @@ describe('NotSupportedMethod', () => {
|
||||
expect(unsupported.code).not.toBe(unimplemented.code);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlatformNotInitializedError', () => {
|
||||
test('exposes code, capability, and default message', () => {
|
||||
const err = new PlatformNotInitializedError('crypto.request');
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err).toBeInstanceOf(PlatformNotInitializedError);
|
||||
expect(err.code).toBe('NOT_INITIALIZED');
|
||||
expect(err.capability).toBe('crypto.request');
|
||||
expect(err.name).toBe('PlatformNotInitializedError');
|
||||
expect(err.message).toBe('Platform not initialized; call init() before using crypto.request');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AndroidImportType, type BatchDownloadType, type NativeImportType } from '~/platform/capabilities';
|
||||
import { NotImplementedError, NotSupportedMethod } from '~/platform/errors';
|
||||
import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||
import type {
|
||||
AndroidAdbImportOptions,
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
NativeImportResult,
|
||||
PlatformCapabilities,
|
||||
} from '~/platform/types';
|
||||
import { loadDecryptWorkerCrypto, type BrowserCrypto } from './browserCrypto';
|
||||
import { createBrowserSettingsIo, DEFAULT_SETTINGS_STORAGE_KEY, type SettingsStorage } from './browserSettingsIo';
|
||||
import { detectBrowserDownloadTypes } from './detectDownloadCapabilities';
|
||||
|
||||
@@ -24,14 +25,21 @@ export interface BrowserProviderOptions {
|
||||
settingsStorage?: SettingsStorage;
|
||||
/** Defaults to `um-react-settings`. */
|
||||
settingsStorageKey?: string;
|
||||
/**
|
||||
* Injected crypto backend (tests). When set, `crypto.*` works without loading the worker
|
||||
* and `init()` resolves immediately.
|
||||
*/
|
||||
crypto?: BrowserCrypto;
|
||||
/** Defaults to dynamic-importing decrypt-worker/client. Injected in tests. */
|
||||
loadCrypto?: () => Promise<BrowserCrypto>;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-browser `PlatformProvider`.
|
||||
* Capabilities follow runtime File System Access / save-picker probing (no DirectWrite).
|
||||
* `settings` persists production settings via localStorage (or injected storage).
|
||||
* crypto / download currently throw `NotImplementedError` (not yet delegated to
|
||||
* the existing worker / download helpers).
|
||||
* `crypto` binds to the decrypt worker only inside `init()` (dynamic import; no construct-time Worker).
|
||||
* `download` currently throws `NotImplementedError` (not yet delegated to download helpers).
|
||||
* Native and ADB key import throw `NotSupportedMethod` (`nativeKeyAccess` empty, `androidKeyAccess` None).
|
||||
*/
|
||||
export function createBrowserProvider(options: BrowserProviderOptions = {}): PlatformProvider {
|
||||
@@ -46,15 +54,44 @@ export function createBrowserProvider(options: BrowserProviderOptions = {}): Pla
|
||||
options.settingsStorageKey ?? DEFAULT_SETTINGS_STORAGE_KEY,
|
||||
);
|
||||
|
||||
const loadCrypto = options.loadCrypto ?? loadDecryptWorkerCrypto;
|
||||
let backend: BrowserCrypto | null = options.crypto ?? null;
|
||||
let initPromise: Promise<void> | null = options.crypto ? Promise.resolve() : null;
|
||||
|
||||
async function requireBackend(capability: string): Promise<BrowserCrypto> {
|
||||
if (backend) {
|
||||
return backend;
|
||||
}
|
||||
if (initPromise) {
|
||||
await initPromise;
|
||||
if (backend) {
|
||||
return backend;
|
||||
}
|
||||
}
|
||||
throw new PlatformNotInitializedError(capability);
|
||||
}
|
||||
|
||||
const crypto: BrowserCrypto = {
|
||||
request: (action, payload) => requireBackend('crypto.request').then((api) => api.request(action, payload)),
|
||||
enqueueDecrypt: (payload, onPreProcess) =>
|
||||
requireBackend('crypto.enqueueDecrypt').then((api) => api.enqueueDecrypt(payload, onPreProcess)),
|
||||
};
|
||||
|
||||
return {
|
||||
id: 'browser',
|
||||
capabilities,
|
||||
|
||||
crypto: {
|
||||
request: () => notImplemented('crypto.request'),
|
||||
enqueueDecrypt: () => notImplemented('crypto.enqueueDecrypt'),
|
||||
init(): Promise<void> {
|
||||
if (!initPromise) {
|
||||
initPromise = loadCrypto().then((loaded) => {
|
||||
backend = loaded;
|
||||
});
|
||||
}
|
||||
return initPromise;
|
||||
},
|
||||
|
||||
crypto,
|
||||
|
||||
settings: {
|
||||
load: () => settingsIo.load(),
|
||||
save: (settings) => settingsIo.save(settings),
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { WorkerActionMap, WorkerActionName } from '~/decrypt-worker/actions';
|
||||
import type { DecryptionResult } from '~/decrypt-worker/constants';
|
||||
import type { DecryptCommandPayload } from '~/decrypt-worker/types';
|
||||
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||
|
||||
export type BrowserCrypto = PlatformProvider['crypto'];
|
||||
|
||||
/**
|
||||
* Lazily binds to decrypt-worker after a dynamic import.
|
||||
* This module must not statically import `~/decrypt-worker/client` (Worker side effect).
|
||||
*/
|
||||
export async function loadDecryptWorkerCrypto(): Promise<BrowserCrypto> {
|
||||
const { decryptionQueue, workerClientBus } = await import('~/decrypt-worker/client');
|
||||
|
||||
return {
|
||||
request<K extends WorkerActionName>(
|
||||
action: K,
|
||||
payload: WorkerActionMap[K]['req'],
|
||||
): Promise<WorkerActionMap[K]['res']> {
|
||||
return workerClientBus.request(action, payload);
|
||||
},
|
||||
enqueueDecrypt(payload: DecryptCommandPayload, onPreProcess?: () => void): Promise<DecryptionResult> {
|
||||
return decryptionQueue.add(payload, onPreProcess);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,22 @@ export class NotImplementedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when `crypto.*` (or other init-gated APIs) is used before `provider.init()` completes.
|
||||
* Distinct from {@link NotImplementedError} (not wired) and {@link NotSupportedMethod} (unsupported).
|
||||
*/
|
||||
export class PlatformNotInitializedError extends Error {
|
||||
readonly code = 'NOT_INITIALIZED' as const;
|
||||
|
||||
constructor(
|
||||
readonly capability: string,
|
||||
message?: string,
|
||||
) {
|
||||
super(message ?? `Platform not initialized; call init() before using ${capability}`);
|
||||
this.name = 'PlatformNotInitializedError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when the current platform explicitly does not support a method / mode
|
||||
* (e.g. Browser `keys.importNative`, or `saveMany(DirectWrite)` when not in `downloadTypes`).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PlatformProvider } from './PlatformProvider';
|
||||
|
||||
/** Non-React callers (thunks / modules) after AppRoot initializes the singleton. */
|
||||
/** Non-React callers (thunks / modules) after AppRoot finishes `init()` and publishes the singleton. */
|
||||
let platformSingleton: PlatformProvider | null = null;
|
||||
|
||||
export function setPlatform(provider: PlatformProvider): void {
|
||||
@@ -9,7 +9,7 @@ export function setPlatform(provider: PlatformProvider): void {
|
||||
|
||||
export function getPlatform(): PlatformProvider {
|
||||
if (!platformSingleton) {
|
||||
throw new Error('Platform provider is not initialized. Call setPlatform() from AppRoot first.');
|
||||
throw new Error('Platform provider is not ready. Call setPlatform() after provider.init() completes.');
|
||||
}
|
||||
return platformSingleton;
|
||||
}
|
||||
@@ -2,8 +2,10 @@ import { RenderOptions, render } from '@testing-library/react';
|
||||
import { PropsWithChildren } from 'react';
|
||||
import { Provider } from 'react-redux';
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
|
||||
import { PlatformProviderHost } from '~/platform/PlatformContext';
|
||||
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||
import { setPlatform } from '~/platform/platformSingleton';
|
||||
import { AppStore, RootState, setupStore } from '~/store';
|
||||
|
||||
// Adapted from: https://redux.js.org/usage/writing-tests
|
||||
@@ -11,10 +13,16 @@ import { AppStore, RootState, setupStore } from '~/store';
|
||||
// eslint-disable-next-line react-refresh/only-export-components
|
||||
export * from '@testing-library/react';
|
||||
|
||||
/** Default test crypto: no dynamic import of decrypt-worker (avoids teardown races). */
|
||||
const defaultTestCrypto: BrowserCrypto = {
|
||||
request: () => Promise.resolve(null as never),
|
||||
enqueueDecrypt: () => Promise.reject(new Error('default test crypto: enqueueDecrypt not configured')),
|
||||
};
|
||||
|
||||
export interface ExtendedRenderOptions extends RenderOptions {
|
||||
preloadedState?: Partial<RootState>;
|
||||
store?: AppStore;
|
||||
/** Override platform backend (defaults to BrowserProvider). */
|
||||
/** Override platform backend (defaults to BrowserProvider with stub crypto). */
|
||||
platform?: PlatformProvider;
|
||||
}
|
||||
|
||||
@@ -23,10 +31,15 @@ export function renderWithProviders(
|
||||
{
|
||||
preloadedState = {},
|
||||
store = setupStore(preloadedState),
|
||||
platform = createBrowserProvider(),
|
||||
platform = createBrowserProvider({ crypto: defaultTestCrypto }),
|
||||
...renderOptions
|
||||
}: ExtendedRenderOptions = {},
|
||||
) {
|
||||
// Publish singleton only after init (matches AppRoot). Stub crypto resolves immediately.
|
||||
void platform.init().then(() => {
|
||||
setPlatform(platform);
|
||||
});
|
||||
|
||||
function Wrapper({ children }: PropsWithChildren<unknown>): React.JSX.Element {
|
||||
return (
|
||||
<Provider store={store}>
|
||||
|
||||
Reference in new issue
Block a user