mirror of
https://git.um-react.app/um/um-react.git
synced 2026-12-03 01:34:00 +00:00
Compare commits
7
Commits
d86323e38a
...
79e5b45e6b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79e5b45e6b | ||
|
|
ef4cd9c21e | ||
|
|
94eab8ecf6 | ||
|
|
d424837e66 | ||
|
|
b5fdc8ebbe | ||
|
|
cb5531e9e4 | ||
|
|
cc688b85bd |
No files matched your search
@@ -92,8 +92,21 @@ docker run -d -p 8080:80 --name um-react um-react
|
|||||||
|
|
||||||
然后访问 `http://localhost:8080` 即可。
|
然后访问 `http://localhost:8080` 即可。
|
||||||
|
|
||||||
|
## 部署到子目录
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> 项目不支持运行在子目录下。
|
> 官方 Docker 镜像与默认构建产物按站点**根路径**(`/`)部署,不支持部署到子目录下。
|
||||||
|
|
||||||
|
若要部署到子目录(例如 `https://example.com/um-react/`),你需要重新使用 Vite 进行构建,并指定 `--base` 参数(路径以 `/` 开头、以 `/` 结尾)。
|
||||||
|
|
||||||
|
以部署到 `https://example.com/um-react/` 为例:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm exec vite build --base=/um-react/
|
||||||
|
pnpm build:finalize
|
||||||
|
```
|
||||||
|
|
||||||
|
部署时,服务器还需把该子目录下的所有前端路由回退到对应的 `index.html`(SPA)。
|
||||||
|
|
||||||
## 开发相关
|
## 开发相关
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,6 @@
|
|||||||
<link rel="icon" href="/favicon.ico" />
|
<link rel="icon" href="/favicon.ico" />
|
||||||
<link rel="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" />
|
<link rel="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" />
|
||||||
<meta name="theme-color" content="#4DBA87" />
|
<meta name="theme-color" content="#4DBA87" />
|
||||||
<script>
|
|
||||||
// 设置基础路径,如果希望部署在/music-unlock/,则改为 '/music-unlock/',默认部署在根路径
|
|
||||||
window.BASE_URL = '/';
|
|
||||||
</script>
|
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { minify } from 'terser';
|
import { minify } from 'terser';
|
||||||
import { readFileSync, writeFileSync, readdirSync } from 'fs';
|
import { readFileSync, writeFileSync, readdirSync } from 'fs';
|
||||||
|
|
||||||
for (const file of readdirSync('dist/assets')) {
|
const assetsDir = 'dist/um-react.assets';
|
||||||
|
|
||||||
|
for (const file of readdirSync(assetsDir)) {
|
||||||
if (!/\.(mjs|js)$/.test(file)) {
|
if (!/\.(mjs|js)$/.test(file)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -9,11 +11,11 @@ for (const file of readdirSync('dist/assets')) {
|
|||||||
console.log(`minifying ${file}...`);
|
console.log(`minifying ${file}...`);
|
||||||
const isModule = /\.mjs$/.test(file);
|
const isModule = /\.mjs$/.test(file);
|
||||||
|
|
||||||
const output = await minify(readFileSync(`dist/assets/${file}`, 'utf-8'), {
|
const output = await minify(readFileSync(`${assetsDir}/${file}`, 'utf-8'), {
|
||||||
compress: true,
|
compress: true,
|
||||||
mangle: true,
|
mangle: true,
|
||||||
module: isModule,
|
module: isModule,
|
||||||
});
|
});
|
||||||
|
|
||||||
writeFileSync(`dist/assets/${file}`, output.code);
|
writeFileSync(`${assetsDir}/${file}`, output.code);
|
||||||
}
|
}
|
||||||
@@ -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';
|
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 {
|
return {
|
||||||
workerClientBus: {
|
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 () => {
|
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
|
// Platform Suspense gate + SDK version fetch
|
||||||
await waitFor(() => screen.getByTestId('sdk-version'));
|
expect(await screen.findByTestId('sdk-version')).toBeInTheDocument();
|
||||||
|
|
||||||
// Quick sanity check of known strings.
|
// Quick sanity check of known strings.
|
||||||
expect(screen.getByText(/音乐解锁/i)).toBeInTheDocument();
|
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 />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
+30
-63
@@ -1,77 +1,44 @@
|
|||||||
import { useEffect } from 'react';
|
import { Suspense } from 'react';
|
||||||
import { BrowserRouter, NavLink, Route, Routes } from 'react-router';
|
import { BrowserRouter } from 'react-router';
|
||||||
import { MdSettings, MdHome, MdQuestionAnswer } from 'react-icons/md';
|
|
||||||
|
|
||||||
import { MainTab } from '~/tabs/MainTab';
|
|
||||||
import { SettingsTab } from '~/tabs/SettingsTab';
|
|
||||||
|
|
||||||
import { Provider } from 'react-redux';
|
import { Provider } from 'react-redux';
|
||||||
|
|
||||||
|
import { AppLayout } from '~/components/AppLayout';
|
||||||
import { persistSettings } from '~/features/settings/persistSettings';
|
import { persistSettings } from '~/features/settings/persistSettings';
|
||||||
|
import { createPlatformProvider } from '~/platform/createPlatformProvider';
|
||||||
|
import { PlatformLoadGuard } from '~/platform/PlatformLoadGuard';
|
||||||
|
import { PlatformProviderHost } from '~/platform/PlatformContext';
|
||||||
|
import { setPlatform } from '~/platform/platformSingleton';
|
||||||
import { setupStore } from '~/store';
|
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';
|
|
||||||
|
|
||||||
// Private to this file only.
|
// Private to this file only.
|
||||||
const store = setupStore();
|
const store = setupStore();
|
||||||
|
const platform = createPlatformProvider();
|
||||||
|
|
||||||
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() {
|
export function AppRoot() {
|
||||||
useEffect(() => persistSettings(store), []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BrowserRouter basename={window.BASE_URL || '/'}>
|
<BrowserRouter basename={import.meta.env.BASE_URL}>
|
||||||
<Provider store={store}>
|
<Provider store={store}>
|
||||||
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
|
<PlatformProviderHost provider={platform}>
|
||||||
<NavLink to="/" role="tab" className={tabClassNames}>
|
<Suspense fallback={<AppBootFallback />}>
|
||||||
<MdHome />
|
<PlatformLoadGuard ready={platformReady}>
|
||||||
应用
|
<AppLayout />
|
||||||
</NavLink>
|
</PlatformLoadGuard>
|
||||||
<NavLink to="/settings" role="tab" className={tabClassNames}>
|
</Suspense>
|
||||||
<MdSettings />
|
</PlatformProviderHost>
|
||||||
设置
|
|
||||||
</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 />
|
|
||||||
</Provider>
|
</Provider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
);
|
);
|
||||||
|
|||||||
+22
-123
@@ -2,17 +2,18 @@ import { DecryptedAudioFile, ProcessState, selectFiles } from '~/features/file-l
|
|||||||
import { FaDownload } from 'react-icons/fa';
|
import { FaDownload } from 'react-icons/fa';
|
||||||
import { useAppSelector } from '~/hooks';
|
import { useAppSelector } from '~/hooks';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { SimpleQueue } from '~/util/SimpleQueue';
|
|
||||||
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
|
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
|
||||||
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes';
|
||||||
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { resolveWritableDirectory } from '~/util/downloadDirectoryHandle';
|
|
||||||
import { downloadZipAsBlob, downloadZipViaSavePicker, ZipSourceFile } from '~/util/streamZip';
|
|
||||||
import { triggerAnchorDownload } from '~/util/triggerDownload';
|
|
||||||
|
|
||||||
export function DownloadAll() {
|
export function DownloadAll() {
|
||||||
const files = useAppSelector(selectFiles);
|
const files = useAppSelector(selectFiles);
|
||||||
const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
|
const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
|
||||||
|
const { download, capabilities } = usePlatform();
|
||||||
|
|
||||||
|
if (capabilities.downloadTypes.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const downloadAllAsync = async () => {
|
const downloadAllAsync = async () => {
|
||||||
const fileList = Object.values(files);
|
const fileList = Object.values(files);
|
||||||
@@ -36,12 +37,16 @@ export function DownloadAll() {
|
|||||||
|
|
||||||
// Single file: direct blob download, no ZIP / directory picker.
|
// Single file: direct blob download, no ZIP / directory picker.
|
||||||
if (completeFiles.length === 1) {
|
if (completeFiles.length === 1) {
|
||||||
downloadSingleBlob(completeFiles[0]);
|
const file = completeFiles[0];
|
||||||
|
await download.saveOne({
|
||||||
|
url: file.decrypted,
|
||||||
|
fileName: decryptedDownloadName(file),
|
||||||
|
});
|
||||||
toast.success('已开始下载');
|
toast.success('已开始下载');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const modes = buildEnabledModes(batchSettings);
|
const modes = buildEnabledDownloadModes(batchSettings, capabilities.downloadTypes);
|
||||||
if (modes.length === 0) {
|
if (modes.length === 0) {
|
||||||
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
|
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
|
||||||
return;
|
return;
|
||||||
@@ -49,9 +54,17 @@ export function DownloadAll() {
|
|||||||
|
|
||||||
toast.warning('开始下载,请稍候');
|
toast.warning('开始下载,请稍候');
|
||||||
|
|
||||||
|
const manyInput = {
|
||||||
|
files: completeFiles.map((file) => ({
|
||||||
|
url: file.decrypted,
|
||||||
|
fileName: decryptedDownloadName(file),
|
||||||
|
})),
|
||||||
|
rememberDirectory: batchSettings.rememberDirectory,
|
||||||
|
};
|
||||||
|
|
||||||
for (const mode of modes) {
|
for (const mode of modes) {
|
||||||
try {
|
try {
|
||||||
const result = await runMode(mode, completeFiles, batchSettings.rememberDirectory);
|
const result = await download.saveMany(mode, manyInput);
|
||||||
if (result === 'ok') {
|
if (result === 'ok') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -79,120 +92,6 @@ export function DownloadAll() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type BatchMode = 'directory' | 'streamingZip' | 'blobZip';
|
|
||||||
|
|
||||||
function buildEnabledModes(
|
|
||||||
settings: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'>,
|
|
||||||
): BatchMode[] {
|
|
||||||
const modes: BatchMode[] = [];
|
|
||||||
if (settings.directoryPicker && supportsDirectoryPicker()) {
|
|
||||||
modes.push('directory');
|
|
||||||
}
|
|
||||||
if (settings.streamingZip && supportsStreamingZipDownload()) {
|
|
||||||
modes.push('streamingZip');
|
|
||||||
}
|
|
||||||
if (settings.blobZip) {
|
|
||||||
modes.push('blobZip');
|
|
||||||
}
|
|
||||||
return modes;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function runMode(
|
|
||||||
mode: BatchMode,
|
|
||||||
completeFiles: DecryptedAudioFile[],
|
|
||||||
rememberDirectory: boolean,
|
|
||||||
): Promise<'ok' | 'cancelled'> {
|
|
||||||
switch (mode) {
|
|
||||||
case 'directory':
|
|
||||||
return downloadToDirectory(completeFiles, rememberDirectory);
|
|
||||||
case 'streamingZip':
|
|
||||||
return downloadStreamingZip(completeFiles);
|
|
||||||
case 'blobZip':
|
|
||||||
await downloadBlobZip(completeFiles);
|
|
||||||
return 'ok';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadToDirectory(
|
|
||||||
completeFiles: DecryptedAudioFile[],
|
|
||||||
remember: boolean,
|
|
||||||
): Promise<'ok' | 'cancelled'> {
|
|
||||||
const dir = await resolveWritableDirectory(remember);
|
|
||||||
if (!dir) {
|
|
||||||
return 'cancelled';
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileCount = completeFiles.length;
|
|
||||||
const queue = new SimpleQueue(8);
|
|
||||||
const promises = completeFiles.map(async (file) => {
|
|
||||||
try {
|
|
||||||
await queue.enter();
|
|
||||||
await writeFileToDirectory(file, dir);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`下载失败: ${file.fileName}`, e);
|
|
||||||
toast.error(`出现错误: ${e instanceof Error ? e.message : String(e)}`);
|
|
||||||
throw e;
|
|
||||||
} finally {
|
|
||||||
queue.leave();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const promiseResults = await Promise.allSettled(promises);
|
|
||||||
const success = promiseResults.filter((result) => result.status === 'fulfilled').length;
|
|
||||||
const level = success === fileCount ? 'success' : success === 0 ? 'error' : 'warning';
|
|
||||||
toast[level](`成功下载: ${success}/${fileCount}首`);
|
|
||||||
|
|
||||||
if (success === 0) {
|
|
||||||
throw new Error('未能写入任何文件到所选目录');
|
|
||||||
}
|
|
||||||
return 'ok';
|
|
||||||
}
|
|
||||||
|
|
||||||
function decryptedDownloadName(file: DecryptedAudioFile): string {
|
function decryptedDownloadName(file: DecryptedAudioFile): string {
|
||||||
return `${file.cleanName}.${file.ext}`;
|
return `${file.cleanName}.${file.ext}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function writeFileToDirectory(file: DecryptedAudioFile, dir: FileSystemDirectoryHandle) {
|
|
||||||
const fileHandle = await dir.getFileHandle(decryptedDownloadName(file), { create: true });
|
|
||||||
const fileStream = await fileHandle.createWritable();
|
|
||||||
try {
|
|
||||||
const res = await fetch(file.decrypted);
|
|
||||||
if (!res.ok) {
|
|
||||||
throw new Error(`无法读取文件: ${decryptedDownloadName(file)} (${res.status})`);
|
|
||||||
}
|
|
||||||
if (!res.body) {
|
|
||||||
await fileStream.write(await res.arrayBuffer());
|
|
||||||
await fileStream.close();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await res.body.pipeTo(fileStream);
|
|
||||||
} catch (e) {
|
|
||||||
await fileStream.abort();
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toZipSources(files: DecryptedAudioFile[]): ZipSourceFile[] {
|
|
||||||
return files.map((file) => ({
|
|
||||||
name: decryptedDownloadName(file),
|
|
||||||
url: file.decrypted,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
function downloadSingleBlob(file: DecryptedAudioFile) {
|
|
||||||
triggerAnchorDownload(file.decrypted, decryptedDownloadName(file));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadStreamingZip(completeFiles: DecryptedAudioFile[]): Promise<'ok' | 'cancelled'> {
|
|
||||||
const sources = toZipSources(completeFiles);
|
|
||||||
const result = await downloadZipViaSavePicker(sources);
|
|
||||||
if (result === 'ok') {
|
|
||||||
toast.success(`已导出 ZIP(${completeFiles.length} 首)`);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadBlobZip(completeFiles: DecryptedAudioFile[]): Promise<void> {
|
|
||||||
await downloadZipAsBlob(toZipSources(completeFiles));
|
|
||||||
toast.success(`已开始下载 ZIP(${completeFiles.length} 首)`);
|
|
||||||
}
|
|
||||||
@@ -1,18 +1,15 @@
|
|||||||
import { MdInfoOutline } from 'react-icons/md';
|
import { MdInfoOutline } from 'react-icons/md';
|
||||||
import { workerClientBus } from '~/decrypt-worker/client';
|
|
||||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
const getSDKVersion = async (): Promise<string> => {
|
|
||||||
return workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
|
|
||||||
};
|
|
||||||
|
|
||||||
export function SDKVersion() {
|
export function SDKVersion() {
|
||||||
|
const { crypto } = usePlatform();
|
||||||
const refDialog = useRef<HTMLDialogElement>(null);
|
const refDialog = useRef<HTMLDialogElement>(null);
|
||||||
const [sdkVersion, setSdkVersion] = useState('...');
|
const [sdkVersion, setSdkVersion] = useState('...');
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getSDKVersion().then(setSdkVersion, () => setSdkVersion('N/A'));
|
crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null).then(setSdkVersion, () => setSdkVersion('N/A'));
|
||||||
}, []);
|
}, [crypto]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { DownloadAll } from '~/components/DownloadAll';
|
||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||||
|
|
||||||
|
test('hides download-all control when platform has no downloadTypes', () => {
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: {
|
||||||
|
request: () => Promise.resolve(null as never),
|
||||||
|
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||||
|
},
|
||||||
|
downloadTypes: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(<DownloadAll />, { platform });
|
||||||
|
|
||||||
|
expect(screen.queryByTitle('下载全部')).not.toBeInTheDocument();
|
||||||
|
expect(document.getElementById('downloadAll')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renders download-all control when PackZip is available', () => {
|
||||||
|
renderWithProviders(<DownloadAll />);
|
||||||
|
|
||||||
|
expect(screen.getByTitle('下载全部')).toBeInTheDocument();
|
||||||
|
expect(document.getElementById('downloadAll')).not.toBeNull();
|
||||||
|
});
|
||||||
@@ -2,6 +2,7 @@ import { DecryptedAudioFile, deleteFile, ProcessState } from './fileListingSlice
|
|||||||
import { useAppDispatch } from '~/hooks';
|
import { useAppDispatch } from '~/hooks';
|
||||||
import { FileError } from './FileError';
|
import { FileError } from './FileError';
|
||||||
import classNames from 'classnames';
|
import classNames from 'classnames';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
|
|
||||||
interface FileRowProps {
|
interface FileRowProps {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -10,7 +11,9 @@ interface FileRowProps {
|
|||||||
|
|
||||||
export function FileRow({ id, file }: FileRowProps) {
|
export function FileRow({ id, file }: FileRowProps) {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
|
const { capabilities } = usePlatform();
|
||||||
const isDecrypted = file.state === ProcessState.COMPLETE;
|
const isDecrypted = file.state === ProcessState.COMPLETE;
|
||||||
|
const showDownload = capabilities.downloadTypes.length > 0;
|
||||||
|
|
||||||
const decryptedName = file.cleanName + '.' + file.ext;
|
const decryptedName = file.cleanName + '.' + file.ext;
|
||||||
|
|
||||||
@@ -32,18 +35,20 @@ export function FileRow({ id, file }: FileRowProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="card-actions justify-end">
|
<div className="card-actions justify-end">
|
||||||
<a
|
{showDownload && (
|
||||||
href={file.decrypted}
|
<a
|
||||||
download={decryptedName}
|
href={file.decrypted}
|
||||||
title={`下载: ${decryptedName}`}
|
download={decryptedName}
|
||||||
className={classNames('btn', {
|
title={`下载: ${decryptedName}`}
|
||||||
'btn-primary': file.decrypted,
|
className={classNames('btn', {
|
||||||
'cursor-not-allowed pointer-events-none': !file.decrypted,
|
'btn-primary': file.decrypted,
|
||||||
})}
|
'cursor-not-allowed pointer-events-none': !file.decrypted,
|
||||||
data-testid="audio-download"
|
})}
|
||||||
>
|
data-testid="audio-download"
|
||||||
下载
|
>
|
||||||
</a>
|
下载
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
<button type="button" className="btn btn-error" onClick={() => dispatch(deleteFile({ id }))}>
|
<button type="button" className="btn btn-error" onClick={() => dispatch(deleteFile({ id }))}>
|
||||||
删除
|
删除
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||||
import { untouchedFile } from './__fixture__/file-list';
|
import { untouchedFile } from './__fixture__/file-list';
|
||||||
import { FileRow } from '../FileRow';
|
import { FileRow } from '../FileRow';
|
||||||
@@ -14,4 +15,19 @@ test('should render basic title (done)', () => {
|
|||||||
renderWithProviders(<FileRow id="file://done" file={completedFile} />);
|
renderWithProviders(<FileRow id="file://done" file={completedFile} />);
|
||||||
|
|
||||||
expect(screen.getAllByTestId('file-row')).toHaveLength(1);
|
expect(screen.getAllByTestId('file-row')).toHaveLength(1);
|
||||||
|
expect(screen.getByTestId('audio-download')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hides single-file download when platform has no downloadTypes', () => {
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: {
|
||||||
|
request: () => Promise.resolve(null as never),
|
||||||
|
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||||
|
},
|
||||||
|
downloadTypes: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(<FileRow id="file://done" file={completedFile} />, { platform });
|
||||||
|
|
||||||
|
expect(screen.queryByTestId('audio-download')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
@@ -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 { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
|
||||||
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
|
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
|
||||||
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
|
|
||||||
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
|
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
|
||||||
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
|
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
|
||||||
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
|
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
|
||||||
import { selectKugouKey } from '~/features/kugou/keyLookup';
|
import { selectKugouKey } from '~/features/kugou/keyLookup';
|
||||||
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
||||||
|
import { getPlatform } from '~/platform/platformSingleton';
|
||||||
import { cleanFilename } from '~/util/cleanFilename';
|
import { cleanFilename } from '~/util/cleanFilename';
|
||||||
|
|
||||||
export enum ProcessState {
|
export enum ProcessState {
|
||||||
@@ -70,14 +70,15 @@ export const processFile = createAsyncThunk<
|
|||||||
thunkAPI.dispatch(setFileAsProcessing({ id: fileId }));
|
thunkAPI.dispatch(setFileAsProcessing({ id: fileId }));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const { crypto } = getPlatform();
|
||||||
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
|
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,
|
blobURI: file.raw,
|
||||||
}),
|
}),
|
||||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
||||||
blobURI: file.raw,
|
blobURI: file.raw,
|
||||||
}),
|
}),
|
||||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
||||||
blobURI: file.raw,
|
blobURI: file.raw,
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
@@ -89,7 +90,7 @@ export const processFile = createAsyncThunk<
|
|||||||
kugouKey: selectKugouKey(state, kugouHdr),
|
kugouKey: selectKugouKey(state, kugouHdr),
|
||||||
qingTingAndroidKey: selectQtfmAndroidKey(state),
|
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({
|
export const fileListingSlice = createSlice({
|
||||||
|
|||||||
@@ -6,14 +6,15 @@ import { selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
|||||||
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
|
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
|
||||||
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
|
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
|
||||||
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
|
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
|
||||||
import { workerClientBus } from '~/decrypt-worker/client.ts';
|
|
||||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
|
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
|
|
||||||
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
|
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
|
||||||
|
|
||||||
export function PanelQingTing() {
|
export function PanelQingTing() {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
|
const { crypto } = usePlatform();
|
||||||
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
|
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
|
||||||
const setSecretKey = (secretKey: string) => {
|
const setSecretKey = (secretKey: string) => {
|
||||||
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
|
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
|
||||||
@@ -31,7 +32,7 @@ export function PanelQingTing() {
|
|||||||
const dataMap = parseQtfmDeviceInfoFromText(plainText);
|
const dataMap = parseQtfmDeviceInfoFromText(plainText);
|
||||||
if (dataMap) {
|
if (dataMap) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
workerClientBus
|
crypto
|
||||||
.request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
|
.request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
|
||||||
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
|
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import { configureStore } from '@reduxjs/toolkit';
|
||||||
|
import { afterEach, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import type { SettingsStorage } from '~/platform/browser/browserSettingsIo';
|
||||||
|
import { persistSettings, mergeSettings } from '../persistSettings';
|
||||||
|
import { settingsSlice, setProductionChanges, type ProductionSettings } from '../settingsSlice';
|
||||||
|
|
||||||
|
function createMemoryStorage(initial: Record<string, string> = {}): SettingsStorage & { data: Record<string, string> } {
|
||||||
|
const data = { ...initial };
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
getItem(key: string) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : null;
|
||||||
|
},
|
||||||
|
setItem(key: string, value: string) {
|
||||||
|
data[key] = value;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createStore() {
|
||||||
|
return configureStore({
|
||||||
|
reducer: { settings: settingsSlice.reducer },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('persistSettings', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loads via provider, merges, and dispatches production', async () => {
|
||||||
|
const stored: ProductionSettings = {
|
||||||
|
...settingsSlice.getInitialState().production,
|
||||||
|
qmc2: {
|
||||||
|
allowFuzzyNameSearch: false,
|
||||||
|
keys: { 'a.mflac': 'ek' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const storage = createMemoryStorage({ 'um-react-settings': JSON.stringify(stored) });
|
||||||
|
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
const unsubscribe = persistSettings(store, provider);
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(store.getState().settings.production.qmc2.keys).toEqual({ 'a.mflac': 'ek' });
|
||||||
|
expect(store.getState().settings.production.qmc2.allowFuzzyNameSearch).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
unsubscribe();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ignores failed loads and keeps defaults', async () => {
|
||||||
|
const storage = createMemoryStorage({ 'um-react-settings': '{bad' });
|
||||||
|
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||||
|
const store = createStore();
|
||||||
|
const defaults = settingsSlice.getInitialState().production;
|
||||||
|
|
||||||
|
const unsubscribe = persistSettings(store, provider);
|
||||||
|
// Give the rejected load a turn to settle.
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
expect(store.getState().settings.production).toEqual(defaults);
|
||||||
|
unsubscribe();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('debounced save writes production through provider', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const storage = createMemoryStorage();
|
||||||
|
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
const unsubscribe = persistSettings(store, provider);
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
const next = mergeSettings({
|
||||||
|
...settingsSlice.getInitialState().production,
|
||||||
|
qmc2: { allowFuzzyNameSearch: true, keys: { 'b.mflac': 'x' } },
|
||||||
|
});
|
||||||
|
store.dispatch(setProductionChanges(next));
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(150);
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
expect(JSON.parse(storage.data['um-react-settings'])).toEqual(next);
|
||||||
|
unsubscribe();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,15 +2,19 @@ import { useCallback, useEffect, useId, useState, type ReactNode } from 'react';
|
|||||||
import { useAppDispatch, useAppSelector } from '~/hooks';
|
import { useAppDispatch, useAppSelector } from '~/hooks';
|
||||||
import { selectStagingBatchDownloadSettings } from '../settingsSelector';
|
import { selectStagingBatchDownloadSettings } from '../settingsSelector';
|
||||||
import { BatchDownloadSettings, updateBatchDownloadSetting } from '../settingsSlice';
|
import { BatchDownloadSettings, updateBatchDownloadSetting } from '../settingsSlice';
|
||||||
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
|
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
|
|
||||||
export function PanelGeneral() {
|
export function PanelGeneral() {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
const batch = useAppSelector(selectStagingBatchDownloadSettings);
|
const batch = useAppSelector(selectStagingBatchDownloadSettings);
|
||||||
const canDirectoryPicker = supportsDirectoryPicker();
|
const { capabilities } = usePlatform();
|
||||||
const canStreamingZip = supportsStreamingZipDownload();
|
const downloadTypes = new Set(capabilities.downloadTypes);
|
||||||
|
const canDirectoryPicker = downloadTypes.has(BatchDownloadType.SelectDirectory);
|
||||||
|
const canStreamingZip = downloadTypes.has(BatchDownloadType.StreamZip);
|
||||||
|
const canBlobZip = downloadTypes.has(BatchDownloadType.PackZip);
|
||||||
const [hasRememberedDir, setHasRememberedDir] = useState(false);
|
const [hasRememberedDir, setHasRememberedDir] = useState(false);
|
||||||
|
|
||||||
const refreshRemembered = useCallback(() => {
|
const refreshRemembered = useCallback(() => {
|
||||||
@@ -57,7 +61,7 @@ export function PanelGeneral() {
|
|||||||
description={
|
description={
|
||||||
canDirectoryPicker
|
canDirectoryPicker
|
||||||
? '通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。'
|
? '通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。'
|
||||||
: '当前浏览器不支持 showDirectoryPicker。'
|
: '当前环境不支持选择目录批量下载。'
|
||||||
}
|
}
|
||||||
onChange={(checked) => setBatch('directoryPicker', checked)}
|
onChange={(checked) => setBatch('directoryPicker', checked)}
|
||||||
/>
|
/>
|
||||||
@@ -93,20 +97,26 @@ export function PanelGeneral() {
|
|||||||
description={
|
description={
|
||||||
canStreamingZip
|
canStreamingZip
|
||||||
? '边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。'
|
? '边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。'
|
||||||
: '当前浏览器不支持 showSaveFilePicker,无法流式写出 ZIP。'
|
: '当前环境不支持流式写出 ZIP。'
|
||||||
}
|
}
|
||||||
onChange={(checked) => setBatch('streamingZip', checked)}
|
onChange={(checked) => setBatch('streamingZip', checked)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<BatchOption
|
<BatchOption
|
||||||
id={idBlobZip}
|
id={idBlobZip}
|
||||||
checked={batch.blobZip}
|
checked={batch.blobZip && canBlobZip}
|
||||||
|
disabled={!canBlobZip}
|
||||||
|
dimmed={!canBlobZip}
|
||||||
title="生成单个 ZIP 并触发下载"
|
title="生成单个 ZIP 并触发下载"
|
||||||
description={
|
description={
|
||||||
<>
|
canBlobZip ? (
|
||||||
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
|
<>
|
||||||
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
|
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
|
||||||
</>
|
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'当前环境不支持打包 ZIP 下载。'
|
||||||
|
)
|
||||||
}
|
}
|
||||||
onChange={(checked) => setBatch('blobZip', checked)}
|
onChange={(checked) => setBatch('blobZip', checked)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral';
|
||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||||
|
|
||||||
|
const stubCrypto = {
|
||||||
|
request: () => Promise.resolve(null as never),
|
||||||
|
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||||
|
};
|
||||||
|
|
||||||
|
test('disables directory and streaming options when only PackZip is capable', () => {
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: stubCrypto,
|
||||||
|
downloadTypes: [BatchDownloadType.PackZip],
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(<PanelGeneral />, { platform });
|
||||||
|
|
||||||
|
expect(screen.getByLabelText(/使用选择目录批量下载/)).toBeDisabled();
|
||||||
|
expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled();
|
||||||
|
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).not.toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('disables pack-zip when capability is absent', () => {
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: stubCrypto,
|
||||||
|
downloadTypes: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(<PanelGeneral />, { platform });
|
||||||
|
|
||||||
|
expect(screen.getByLabelText(/使用选择目录批量下载/)).toBeDisabled();
|
||||||
|
expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled();
|
||||||
|
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).toBeDisabled();
|
||||||
|
});
|
||||||
@@ -13,8 +13,7 @@ import { getLogger } from '~/util/logUtils';
|
|||||||
import { parseKwm2ProductionKey } from '~/features/kwm/types';
|
import { parseKwm2ProductionKey } from '~/features/kwm/types';
|
||||||
import { sanitizeQtfmAndroidKey } from '~/features/qtfm/types';
|
import { sanitizeQtfmAndroidKey } from '~/features/qtfm/types';
|
||||||
import { deepClone } from '~/util/deepClone';
|
import { deepClone } from '~/util/deepClone';
|
||||||
|
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||||
const DEFAULT_STORAGE_KEY = 'um-react-settings';
|
|
||||||
|
|
||||||
function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined): BatchDownloadSettings {
|
function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined): BatchDownloadSettings {
|
||||||
const result = { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS };
|
const result = { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS };
|
||||||
@@ -75,28 +74,47 @@ export function mergeSettings(settings: ProductionSettings): ProductionSettings
|
|||||||
return draft;
|
return draft;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function persistSettings(store: AppStore, storageKey = DEFAULT_STORAGE_KEY) {
|
/**
|
||||||
|
* Load production settings via `provider.settings`, merge into the store, and
|
||||||
|
* debounce-save on production changes. Storage details stay inside the provider.
|
||||||
|
*/
|
||||||
|
export function persistSettings(store: AppStore, provider: PlatformProvider) {
|
||||||
let lastSettings: unknown;
|
let lastSettings: unknown;
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
try {
|
const unsubscribe = store.subscribe(
|
||||||
const loadedSettings = JSON.parse(localStorage.getItem(storageKey) ?? '') as ProductionSettings;
|
|
||||||
if (loadedSettings) {
|
|
||||||
const mergedSettings = mergeSettings(loadedSettings);
|
|
||||||
store.dispatch(setProductionChanges(mergedSettings));
|
|
||||||
getLogger().debug('settings loaded');
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// load failed, ignore.
|
|
||||||
}
|
|
||||||
|
|
||||||
return store.subscribe(
|
|
||||||
debounce({ delay: 150 }, () => {
|
debounce({ delay: 150 }, () => {
|
||||||
const currentSettings = store.getState().settings.production;
|
const currentSettings = store.getState().settings.production;
|
||||||
if (lastSettings !== currentSettings) {
|
if (lastSettings !== currentSettings) {
|
||||||
lastSettings = currentSettings;
|
lastSettings = currentSettings;
|
||||||
localStorage.setItem(storageKey, JSON.stringify(currentSettings));
|
void provider.settings.save(currentSettings).then(
|
||||||
getLogger().debug('settings saved');
|
() => getLogger().debug('settings saved'),
|
||||||
|
() => {
|
||||||
|
// save failed; keep lastSettings so we do not spin-retry on every tick
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
void provider.settings
|
||||||
|
.load()
|
||||||
|
.then((loadedSettings) => {
|
||||||
|
if (cancelled || !loadedSettings) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const mergedSettings = mergeSettings(loadedSettings);
|
||||||
|
store.dispatch(setProductionChanges(mergedSettings));
|
||||||
|
// Avoid an immediate rewrite of the same production snapshot after load.
|
||||||
|
lastSettings = store.getState().settings.production;
|
||||||
|
getLogger().debug('settings loaded');
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
// load failed, ignore.
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
unsubscribe();
|
||||||
|
};
|
||||||
}
|
}
|
||||||
+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 { TypedUseSelectorHook } from 'react-redux';
|
||||||
import type { RootState, AppDispatch } from './store';
|
import type { RootState, AppDispatch, AppStore } from './store';
|
||||||
|
|
||||||
export const useAppDispatch: () => AppDispatch = useDispatch;
|
export const useAppDispatch: () => AppDispatch = useDispatch;
|
||||||
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
||||||
|
export const useAppStore: () => AppStore = useStore;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { createContext, useContext, type PropsWithChildren } from 'react';
|
||||||
|
import type { PlatformProvider } from './PlatformProvider';
|
||||||
|
|
||||||
|
const PlatformReactContext = createContext<PlatformProvider | null>(null);
|
||||||
|
|
||||||
|
export function PlatformProviderHost({
|
||||||
|
provider,
|
||||||
|
children,
|
||||||
|
}: PropsWithChildren<{ provider: PlatformProvider }>): React.JSX.Element {
|
||||||
|
return <PlatformReactContext.Provider value={provider}>{children}</PlatformReactContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line react-refresh/only-export-components -- hook colocated with context host
|
||||||
|
export function usePlatform(): PlatformProvider {
|
||||||
|
const provider = useContext(PlatformReactContext);
|
||||||
|
if (!provider) {
|
||||||
|
throw new Error('usePlatform() must be used within PlatformProviderHost');
|
||||||
|
}
|
||||||
|
return provider;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import type { WorkerActionMap, WorkerActionName } from '~/decrypt-worker/actions';
|
||||||
|
import type { DecryptionResult } from '~/decrypt-worker/constants';
|
||||||
|
import type { DecryptCommandPayload } from '~/decrypt-worker/types';
|
||||||
|
import type { ProductionSettings } from '~/features/settings/settingsSlice';
|
||||||
|
import type { BatchDownloadType, NativeImportType } from './capabilities';
|
||||||
|
import type {
|
||||||
|
AndroidAdbImportOptions,
|
||||||
|
DownloadManyInput,
|
||||||
|
DownloadManyResult,
|
||||||
|
DownloadOneInput,
|
||||||
|
NativeImportResult,
|
||||||
|
PlatformCapabilities,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Platform backend for crypto, settings IO, download, and native key import.
|
||||||
|
*
|
||||||
|
* Conventions:
|
||||||
|
* - 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).
|
||||||
|
*/
|
||||||
|
export interface PlatformProvider {
|
||||||
|
readonly id: 'browser' | 'tauri';
|
||||||
|
readonly capabilities: PlatformCapabilities;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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,
|
||||||
|
payload: WorkerActionMap[K]['req'],
|
||||||
|
): Promise<WorkerActionMap[K]['res']>;
|
||||||
|
enqueueDecrypt(payload: DecryptCommandPayload, onPreProcess?: () => void): Promise<DecryptionResult>;
|
||||||
|
};
|
||||||
|
|
||||||
|
settings: {
|
||||||
|
load(): Promise<ProductionSettings | null>;
|
||||||
|
save(settings: ProductionSettings): Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
download: {
|
||||||
|
/** Single file; no suitable download capability → `NotSupportedMethod`. */
|
||||||
|
saveOne(input: DownloadOneInput): Promise<void>;
|
||||||
|
/**
|
||||||
|
* Batch; `type` ∉ `capabilities.downloadTypes` → `NotSupportedMethod`.
|
||||||
|
* Declared type not wired yet → `NotImplementedError`.
|
||||||
|
*/
|
||||||
|
saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult>;
|
||||||
|
};
|
||||||
|
|
||||||
|
keys: {
|
||||||
|
/** Empty / unsupported `nativeKeyAccess` → `NotSupportedMethod`. */
|
||||||
|
importNative(targets: readonly NativeImportType[]): Promise<NativeImportResult>;
|
||||||
|
/** `androidKeyAccess !== Adb` → `NotSupportedMethod`. */
|
||||||
|
importAndroidAdb(opts: AndroidAdbImportOptions): Promise<NativeImportResult>;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
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 { 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', () => {
|
||||||
|
expect(typeof window.showDirectoryPicker).toBe('undefined');
|
||||||
|
expect(typeof window.showSaveFilePicker).toBe('undefined');
|
||||||
|
|
||||||
|
const provider = createBrowserProvider();
|
||||||
|
|
||||||
|
expect(provider.id).toBe('browser');
|
||||||
|
expect(provider.capabilities).toEqual({
|
||||||
|
downloadTypes: [BatchDownloadType.PackZip],
|
||||||
|
directFsAccess: false,
|
||||||
|
androidKeyAccess: AndroidImportType.None,
|
||||||
|
nativeKeyAccess: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('keys.importNative throws NotSupportedMethod', async () => {
|
||||||
|
const provider = createBrowserProvider();
|
||||||
|
|
||||||
|
await expect(provider.keys.importNative([])).rejects.toSatisfy((err: unknown) => {
|
||||||
|
return (
|
||||||
|
err instanceof NotSupportedMethod && err.code === 'NOT_SUPPORTED' && err.capability === 'keys.importNative'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('keys.importAndroidAdb throws NotSupportedMethod', async () => {
|
||||||
|
const provider = createBrowserProvider();
|
||||||
|
|
||||||
|
await expect(provider.keys.importAndroidAdb({})).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||||
|
});
|
||||||
|
|
||||||
|
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('download.saveMany rejects types outside downloadTypes', async () => {
|
||||||
|
const provider = createBrowserProvider({
|
||||||
|
crypto: createMockCrypto(),
|
||||||
|
downloadTypes: [BatchDownloadType.PackZip],
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
provider.download.saveMany(BatchDownloadType.SelectDirectory, {
|
||||||
|
files: [{ url: 'blob:x', fileName: 'a.flac' }],
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('download.saveOne works when PackZip is available', async () => {
|
||||||
|
const saveOne = vi.fn().mockResolvedValue(undefined);
|
||||||
|
const provider = createBrowserProvider({
|
||||||
|
crypto: createMockCrypto(),
|
||||||
|
download: {
|
||||||
|
saveOne,
|
||||||
|
saveMany: vi.fn(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await provider.download.saveOne({ url: 'blob:x', fileName: 'a.flac' });
|
||||||
|
expect(saveOne).toHaveBeenCalledWith({ url: 'blob:x', fileName: 'a.flac' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('settings.load returns null when storage is empty', async () => {
|
||||||
|
const provider = createBrowserProvider({
|
||||||
|
settingsStorage: {
|
||||||
|
getItem: () => null,
|
||||||
|
setItem: () => undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(provider.settings.load()).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('createPlatformProvider defaults to browser', () => {
|
||||||
|
const provider = createPlatformProvider();
|
||||||
|
expect(provider.id).toBe('browser');
|
||||||
|
expect(provider.capabilities.nativeKeyAccess).toEqual([]);
|
||||||
|
expect(provider.capabilities.androidKeyAccess).toBe(AndroidImportType.None);
|
||||||
|
expect(provider.capabilities.directFsAccess).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { createBrowserDownload } from '~/platform/browser/browserDownload';
|
||||||
|
import { NotSupportedMethod } from '~/platform/errors';
|
||||||
|
import * as triggerDownload from '~/util/triggerDownload';
|
||||||
|
|
||||||
|
describe('createBrowserDownload', () => {
|
||||||
|
test('saveOne triggers anchor download when any type is available', async () => {
|
||||||
|
const spy = vi.spyOn(triggerDownload, 'triggerAnchorDownload').mockImplementation(() => undefined);
|
||||||
|
const download = createBrowserDownload([BatchDownloadType.PackZip]);
|
||||||
|
|
||||||
|
await download.saveOne({ url: 'blob:x', fileName: 'a.flac' });
|
||||||
|
|
||||||
|
expect(spy).toHaveBeenCalledWith('blob:x', 'a.flac');
|
||||||
|
spy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saveOne throws NotSupportedMethod when downloadTypes is empty', async () => {
|
||||||
|
const download = createBrowserDownload([]);
|
||||||
|
|
||||||
|
await expect(download.saveOne({ url: 'blob:x', fileName: 'a.flac' })).rejects.toSatisfy((err: unknown) => {
|
||||||
|
return err instanceof NotSupportedMethod && err.capability === 'download.saveOne';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saveMany rejects types outside downloadTypes', async () => {
|
||||||
|
const download = createBrowserDownload([BatchDownloadType.PackZip]);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
download.saveMany(BatchDownloadType.SelectDirectory, { files: [{ url: 'blob:x', fileName: 'a.flac' }] }),
|
||||||
|
).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
download.saveMany(BatchDownloadType.StreamZip, { files: [{ url: 'blob:x', fileName: 'a.flac' }] }),
|
||||||
|
).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import {
|
||||||
|
createBrowserSettingsIo,
|
||||||
|
DEFAULT_SETTINGS_STORAGE_KEY,
|
||||||
|
type SettingsStorage,
|
||||||
|
} from '~/platform/browser/browserSettingsIo';
|
||||||
|
import { settingsSlice, type ProductionSettings } from '~/features/settings/settingsSlice';
|
||||||
|
|
||||||
|
function createMemoryStorage(initial: Record<string, string> = {}): SettingsStorage & { data: Record<string, string> } {
|
||||||
|
const data = { ...initial };
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
getItem(key: string) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : null;
|
||||||
|
},
|
||||||
|
setItem(key: string, value: string) {
|
||||||
|
data[key] = value;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sampleProduction(): ProductionSettings {
|
||||||
|
const production = structuredClone(settingsSlice.getInitialState().production);
|
||||||
|
production.qmc2.keys['demo.mflac'] = 'ekey-demo';
|
||||||
|
production.qmc2.allowFuzzyNameSearch = false;
|
||||||
|
production.general.batchDownload.blobZip = false;
|
||||||
|
return production;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('createBrowserSettingsIo', () => {
|
||||||
|
test('load returns null when key is missing or empty', async () => {
|
||||||
|
const storage = createMemoryStorage();
|
||||||
|
const io = createBrowserSettingsIo(storage);
|
||||||
|
|
||||||
|
await expect(io.load()).resolves.toBeNull();
|
||||||
|
|
||||||
|
storage.setItem(DEFAULT_SETTINGS_STORAGE_KEY, '');
|
||||||
|
await expect(io.load()).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('save then load round-trips production settings', async () => {
|
||||||
|
const storage = createMemoryStorage();
|
||||||
|
const io = createBrowserSettingsIo(storage, 'test-settings');
|
||||||
|
const settings = sampleProduction();
|
||||||
|
|
||||||
|
await io.save(settings);
|
||||||
|
|
||||||
|
expect(storage.data['test-settings']).toBe(JSON.stringify(settings));
|
||||||
|
await expect(io.load()).resolves.toEqual(settings);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('load rejects on invalid JSON', async () => {
|
||||||
|
const storage = createMemoryStorage({ [DEFAULT_SETTINGS_STORAGE_KEY]: '{not-json' });
|
||||||
|
const io = createBrowserSettingsIo(storage);
|
||||||
|
|
||||||
|
await expect(io.load()).rejects.toBeInstanceOf(SyntaxError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('BrowserProvider.settings', () => {
|
||||||
|
test('round-trips through injected storage', async () => {
|
||||||
|
const storage = createMemoryStorage();
|
||||||
|
const provider = createBrowserProvider({ settingsStorage: storage, settingsStorageKey: 'um-test' });
|
||||||
|
const settings = sampleProduction();
|
||||||
|
|
||||||
|
await provider.settings.save(settings);
|
||||||
|
await expect(provider.settings.load()).resolves.toEqual(settings);
|
||||||
|
expect(JSON.parse(storage.data['um-test'])).toEqual(settings);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes';
|
||||||
|
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
||||||
|
|
||||||
|
const allOn: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'> = {
|
||||||
|
directoryPicker: true,
|
||||||
|
streamingZip: true,
|
||||||
|
blobZip: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const allOff: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'> = {
|
||||||
|
directoryPicker: false,
|
||||||
|
streamingZip: false,
|
||||||
|
blobZip: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('buildEnabledDownloadModes', () => {
|
||||||
|
test('intersects settings with capabilities in fallback order', () => {
|
||||||
|
expect(
|
||||||
|
buildEnabledDownloadModes(allOn, [
|
||||||
|
BatchDownloadType.SelectDirectory,
|
||||||
|
BatchDownloadType.StreamZip,
|
||||||
|
BatchDownloadType.PackZip,
|
||||||
|
]),
|
||||||
|
).toEqual([BatchDownloadType.SelectDirectory, BatchDownloadType.StreamZip, BatchDownloadType.PackZip]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('omits modes disabled in settings even when capable', () => {
|
||||||
|
expect(
|
||||||
|
buildEnabledDownloadModes({ directoryPicker: false, streamingZip: true, blobZip: true }, [
|
||||||
|
BatchDownloadType.SelectDirectory,
|
||||||
|
BatchDownloadType.StreamZip,
|
||||||
|
BatchDownloadType.PackZip,
|
||||||
|
]),
|
||||||
|
).toEqual([BatchDownloadType.StreamZip, BatchDownloadType.PackZip]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('omits modes missing from capabilities even when enabled in settings', () => {
|
||||||
|
expect(buildEnabledDownloadModes(allOn, [BatchDownloadType.PackZip])).toEqual([BatchDownloadType.PackZip]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns empty when no overlap', () => {
|
||||||
|
expect(buildEnabledDownloadModes(allOff, [BatchDownloadType.PackZip])).toEqual([]);
|
||||||
|
expect(buildEnabledDownloadModes(allOn, [])).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||||
|
import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||||
|
|
||||||
|
describe('platform capabilities enums', () => {
|
||||||
|
test('BatchDownloadType members stay stable', () => {
|
||||||
|
expect(BatchDownloadType).toEqual({
|
||||||
|
SelectDirectory: 'SelectDirectory',
|
||||||
|
StreamZip: 'StreamZip',
|
||||||
|
PackZip: 'PackZip',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('AndroidImportType members stay stable', () => {
|
||||||
|
expect(AndroidImportType).toEqual({
|
||||||
|
None: 'none',
|
||||||
|
Adb: 'adb',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('NativeImportType members stay stable', () => {
|
||||||
|
expect(NativeImportType).toEqual({
|
||||||
|
QQMusic: 'qqmusic',
|
||||||
|
Kuwo: 'kuwo',
|
||||||
|
Kugou: 'kugou',
|
||||||
|
QingTing: 'qtfm',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('NotImplementedError', () => {
|
||||||
|
test('exposes code, capability, and default message', () => {
|
||||||
|
const err = new NotImplementedError('crypto.request');
|
||||||
|
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err).toBeInstanceOf(NotImplementedError);
|
||||||
|
expect(err.code).toBe('NOT_IMPLEMENTED');
|
||||||
|
expect(err.capability).toBe('crypto.request');
|
||||||
|
expect(err.name).toBe('NotImplementedError');
|
||||||
|
expect(err.message).toBe('Capability not implemented: crypto.request');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a custom message', () => {
|
||||||
|
const err = new NotImplementedError('settings.save', 'storage backend pending');
|
||||||
|
expect(err.message).toBe('storage backend pending');
|
||||||
|
expect(err.capability).toBe('settings.save');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('NotSupportedMethod', () => {
|
||||||
|
test('exposes code, capability, and default message', () => {
|
||||||
|
const err = new NotSupportedMethod('keys.importNative');
|
||||||
|
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err).toBeInstanceOf(NotSupportedMethod);
|
||||||
|
expect(err.code).toBe('NOT_SUPPORTED');
|
||||||
|
expect(err.capability).toBe('keys.importNative');
|
||||||
|
expect(err.name).toBe('NotSupportedMethod');
|
||||||
|
expect(err.message).toBe('Capability not supported: keys.importNative');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a custom message', () => {
|
||||||
|
const err = new NotSupportedMethod('download.saveMany', 'SelectDirectory unavailable on this platform');
|
||||||
|
expect(err.message).toBe('SelectDirectory unavailable on this platform');
|
||||||
|
expect(err.capability).toBe('download.saveMany');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is distinct from NotImplementedError', () => {
|
||||||
|
const unsupported = new NotSupportedMethod('keys.importNative');
|
||||||
|
const unimplemented = new NotImplementedError('keys.importNative');
|
||||||
|
|
||||||
|
expect(unsupported).not.toBeInstanceOf(NotImplementedError);
|
||||||
|
expect(unimplemented).not.toBeInstanceOf(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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { AndroidImportType, type NativeImportType } from '~/platform/capabilities';
|
||||||
|
import { NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||||
|
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||||
|
import type { AndroidAdbImportOptions, NativeImportResult, PlatformCapabilities } from '~/platform/types';
|
||||||
|
import { createBrowserDownload, type BrowserDownload } from './browserDownload';
|
||||||
|
import { loadDecryptWorkerCrypto, type BrowserCrypto } from './browserCrypto';
|
||||||
|
import { createBrowserSettingsIo, DEFAULT_SETTINGS_STORAGE_KEY, type SettingsStorage } from './browserSettingsIo';
|
||||||
|
import { detectBrowserDownloadTypes } from './detectDownloadCapabilities';
|
||||||
|
|
||||||
|
function notSupported(capability: string): Promise<never> {
|
||||||
|
return Promise.reject(new NotSupportedMethod(capability));
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BrowserProviderOptions {
|
||||||
|
/** Defaults to `localStorage`. Injected in tests. */
|
||||||
|
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>;
|
||||||
|
/** Override download backend (tests). Defaults to FS Access / ZIP helpers. */
|
||||||
|
download?: BrowserDownload;
|
||||||
|
/** Override detected `downloadTypes` (tests). */
|
||||||
|
downloadTypes?: PlatformCapabilities['downloadTypes'];
|
||||||
|
/** Override `directFsAccess` (tests). Browser default is `false`. */
|
||||||
|
directFsAccess?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In-browser `PlatformProvider`.
|
||||||
|
* Capabilities follow runtime File System Access / save-picker probing (`directFsAccess: false`).
|
||||||
|
* `settings` persists production settings via localStorage (or injected storage).
|
||||||
|
* `crypto` binds to the decrypt worker only inside `init()` (dynamic import; no construct-time Worker).
|
||||||
|
* `download` delegates to anchor / directory picker / streaming ZIP / pack ZIP helpers.
|
||||||
|
* Native and ADB key import throw `NotSupportedMethod` (`nativeKeyAccess` empty, `androidKeyAccess` None).
|
||||||
|
*/
|
||||||
|
export function createBrowserProvider(options: BrowserProviderOptions = {}): PlatformProvider {
|
||||||
|
const downloadTypes = Object.freeze(
|
||||||
|
options.downloadTypes ? [...options.downloadTypes] : detectBrowserDownloadTypes(),
|
||||||
|
);
|
||||||
|
const capabilities: PlatformCapabilities = Object.freeze({
|
||||||
|
downloadTypes,
|
||||||
|
directFsAccess: options.directFsAccess ?? false,
|
||||||
|
androidKeyAccess: AndroidImportType.None,
|
||||||
|
nativeKeyAccess: Object.freeze([] as NativeImportType[]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const settingsIo = createBrowserSettingsIo(
|
||||||
|
options.settingsStorage ?? localStorage,
|
||||||
|
options.settingsStorageKey ?? DEFAULT_SETTINGS_STORAGE_KEY,
|
||||||
|
);
|
||||||
|
|
||||||
|
const download = options.download ?? createBrowserDownload(downloadTypes);
|
||||||
|
|
||||||
|
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,
|
||||||
|
|
||||||
|
init(): Promise<void> {
|
||||||
|
if (!initPromise) {
|
||||||
|
initPromise = loadCrypto().then((loaded) => {
|
||||||
|
backend = loaded;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return initPromise;
|
||||||
|
},
|
||||||
|
|
||||||
|
crypto,
|
||||||
|
|
||||||
|
settings: {
|
||||||
|
load: () => settingsIo.load(),
|
||||||
|
save: (settings) => settingsIo.save(settings),
|
||||||
|
},
|
||||||
|
|
||||||
|
download,
|
||||||
|
|
||||||
|
keys: {
|
||||||
|
importNative: (_targets: readonly NativeImportType[]): Promise<NativeImportResult> =>
|
||||||
|
notSupported('keys.importNative'),
|
||||||
|
importAndroidAdb: (_opts: AndroidAdbImportOptions): Promise<NativeImportResult> =>
|
||||||
|
notSupported('keys.importAndroidAdb'),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { toast } from 'react-toastify';
|
||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { NotSupportedMethod } from '~/platform/errors';
|
||||||
|
import type { DownloadManyInput, DownloadManyResult, DownloadOneInput } from '~/platform/types';
|
||||||
|
import { resolveWritableDirectory } from '~/util/downloadDirectoryHandle';
|
||||||
|
import { SimpleQueue } from '~/util/SimpleQueue';
|
||||||
|
import { downloadZipAsBlob, downloadZipViaSavePicker, type ZipSourceFile } from '~/util/streamZip';
|
||||||
|
import { triggerAnchorDownload } from '~/util/triggerDownload';
|
||||||
|
|
||||||
|
export interface BrowserDownload {
|
||||||
|
saveOne(input: DownloadOneInput): Promise<void>;
|
||||||
|
saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Browser download backend: single-file anchor download plus batch directory / ZIP modes.
|
||||||
|
* Modes not listed in `downloadTypes` reject with `NotSupportedMethod`.
|
||||||
|
*/
|
||||||
|
export function createBrowserDownload(downloadTypes: readonly BatchDownloadType[]): BrowserDownload {
|
||||||
|
const supported = new Set(downloadTypes);
|
||||||
|
|
||||||
|
return {
|
||||||
|
saveOne(input: DownloadOneInput): Promise<void> {
|
||||||
|
if (supported.size === 0) {
|
||||||
|
return Promise.reject(new NotSupportedMethod('download.saveOne'));
|
||||||
|
}
|
||||||
|
triggerAnchorDownload(input.url, input.fileName);
|
||||||
|
return Promise.resolve();
|
||||||
|
},
|
||||||
|
|
||||||
|
async saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult> {
|
||||||
|
if (!supported.has(type)) {
|
||||||
|
throw new NotSupportedMethod('download.saveMany', `${type} unavailable on this platform`);
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case BatchDownloadType.SelectDirectory:
|
||||||
|
return downloadToDirectory(input.files, input.rememberDirectory ?? false);
|
||||||
|
case BatchDownloadType.StreamZip:
|
||||||
|
return downloadStreamingZip(input.files);
|
||||||
|
case BatchDownloadType.PackZip:
|
||||||
|
await downloadBlobZip(input.files);
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadToDirectory(files: DownloadManyInput['files'], remember: boolean): Promise<DownloadManyResult> {
|
||||||
|
const dir = await resolveWritableDirectory(remember);
|
||||||
|
if (!dir) {
|
||||||
|
return 'cancelled';
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileCount = files.length;
|
||||||
|
const queue = new SimpleQueue(8);
|
||||||
|
const promises = files.map(async (file) => {
|
||||||
|
try {
|
||||||
|
await queue.enter();
|
||||||
|
await writeFileToDirectory(file.url, file.fileName, dir);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`下载失败: ${file.fileName}`, e);
|
||||||
|
toast.error(`出现错误: ${e instanceof Error ? e.message : String(e)}`);
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
queue.leave();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const promiseResults = await Promise.allSettled(promises);
|
||||||
|
const success = promiseResults.filter((result) => result.status === 'fulfilled').length;
|
||||||
|
const level = success === fileCount ? 'success' : success === 0 ? 'error' : 'warning';
|
||||||
|
toast[level](`成功下载: ${success}/${fileCount}首`);
|
||||||
|
|
||||||
|
if (success === 0) {
|
||||||
|
throw new Error('未能写入任何文件到所选目录');
|
||||||
|
}
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeFileToDirectory(url: string, fileName: string, dir: FileSystemDirectoryHandle) {
|
||||||
|
const fileHandle = await dir.getFileHandle(fileName, { create: true });
|
||||||
|
const fileStream = await fileHandle.createWritable();
|
||||||
|
try {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`无法读取文件: ${fileName} (${res.status})`);
|
||||||
|
}
|
||||||
|
if (!res.body) {
|
||||||
|
await fileStream.write(await res.arrayBuffer());
|
||||||
|
await fileStream.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await res.body.pipeTo(fileStream);
|
||||||
|
} catch (e) {
|
||||||
|
await fileStream.abort();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toZipSources(files: DownloadManyInput['files']): ZipSourceFile[] {
|
||||||
|
return files.map((file) => ({
|
||||||
|
name: file.fileName,
|
||||||
|
url: file.url,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadStreamingZip(files: DownloadManyInput['files']): Promise<DownloadManyResult> {
|
||||||
|
const result = await downloadZipViaSavePicker(toZipSources(files));
|
||||||
|
if (result === 'ok') {
|
||||||
|
toast.success(`已导出 ZIP(${files.length} 首)`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadBlobZip(files: DownloadManyInput['files']): Promise<void> {
|
||||||
|
await downloadZipAsBlob(toZipSources(files));
|
||||||
|
toast.success(`已开始下载 ZIP(${files.length} 首)`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import type { ProductionSettings } from '~/features/settings/settingsSlice';
|
||||||
|
|
||||||
|
export const DEFAULT_SETTINGS_STORAGE_KEY = 'um-react-settings';
|
||||||
|
|
||||||
|
/** Minimal storage surface used by browser settings persistence. */
|
||||||
|
export type SettingsStorage = Pick<Storage, 'getItem' | 'setItem'>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* localStorage-backed settings IO for the browser provider.
|
||||||
|
* `load` returns `null` when the key is missing or empty; invalid JSON rejects.
|
||||||
|
*/
|
||||||
|
export function createBrowserSettingsIo(
|
||||||
|
storage: SettingsStorage = localStorage,
|
||||||
|
storageKey = DEFAULT_SETTINGS_STORAGE_KEY,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
// async: matches PlatformProvider.settings.load(): Promise<...> (sync localStorage).
|
||||||
|
// eslint-disable-next-line @typescript-eslint/require-await -- interface requires Promise
|
||||||
|
async load(): Promise<ProductionSettings | null> {
|
||||||
|
const raw = storage.getItem(storageKey);
|
||||||
|
if (raw == null || raw === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return JSON.parse(raw) as ProductionSettings;
|
||||||
|
},
|
||||||
|
|
||||||
|
// async: matches PlatformProvider.settings.save(): Promise<void> (sync localStorage).
|
||||||
|
// eslint-disable-next-line @typescript-eslint/require-await -- interface requires Promise
|
||||||
|
async save(settings: ProductionSettings): Promise<void> {
|
||||||
|
storage.setItem(storageKey, JSON.stringify(settings));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runtime download modes for the browser provider.
|
||||||
|
* Order: directory picker → streaming ZIP → pack ZIP.
|
||||||
|
* UI must read `capabilities.downloadTypes` rather than calling these probes directly.
|
||||||
|
*/
|
||||||
|
export function detectBrowserDownloadTypes(): BatchDownloadType[] {
|
||||||
|
const types: BatchDownloadType[] = [];
|
||||||
|
if (supportsDirectoryPicker()) {
|
||||||
|
types.push(BatchDownloadType.SelectDirectory);
|
||||||
|
}
|
||||||
|
if (supportsStreamingZipDownload()) {
|
||||||
|
types.push(BatchDownloadType.StreamZip);
|
||||||
|
}
|
||||||
|
types.push(BatchDownloadType.PackZip);
|
||||||
|
return types;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Intersect user batch-download settings with platform `downloadTypes`.
|
||||||
|
* Order matches browser fallback: SelectDirectory → StreamZip → PackZip.
|
||||||
|
* Native direct-disk write is gated by `capabilities.directFsAccess`, not these modes.
|
||||||
|
*/
|
||||||
|
export function buildEnabledDownloadModes(
|
||||||
|
settings: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'>,
|
||||||
|
downloadTypes: readonly BatchDownloadType[],
|
||||||
|
): BatchDownloadType[] {
|
||||||
|
const available = new Set(downloadTypes);
|
||||||
|
const modes: BatchDownloadType[] = [];
|
||||||
|
|
||||||
|
if (settings.directoryPicker && available.has(BatchDownloadType.SelectDirectory)) {
|
||||||
|
modes.push(BatchDownloadType.SelectDirectory);
|
||||||
|
}
|
||||||
|
if (settings.streamingZip && available.has(BatchDownloadType.StreamZip)) {
|
||||||
|
modes.push(BatchDownloadType.StreamZip);
|
||||||
|
}
|
||||||
|
if (settings.blobZip && available.has(BatchDownloadType.PackZip)) {
|
||||||
|
modes.push(BatchDownloadType.PackZip);
|
||||||
|
}
|
||||||
|
|
||||||
|
return modes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/** Batch download modes a platform may expose via `capabilities.downloadTypes`. */
|
||||||
|
export enum BatchDownloadType {
|
||||||
|
/** Existing File System Access directory picker. */
|
||||||
|
SelectDirectory = 'SelectDirectory',
|
||||||
|
/** Existing streaming ZIP via `showSaveFilePicker`. */
|
||||||
|
StreamZip = 'StreamZip',
|
||||||
|
/** Existing in-memory ZIP blob download. */
|
||||||
|
PackZip = 'PackZip',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Android-side key import path (single value on capabilities). */
|
||||||
|
export enum AndroidImportType {
|
||||||
|
None = 'none',
|
||||||
|
Adb = 'adb',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One-click native client import targets (settings checkboxes). */
|
||||||
|
export enum NativeImportType {
|
||||||
|
QQMusic = 'qqmusic',
|
||||||
|
Kuwo = 'kuwo',
|
||||||
|
Kugou = 'kugou',
|
||||||
|
QingTing = 'qtfm',
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { createBrowserProvider } from './browser/BrowserProvider';
|
||||||
|
import type { PlatformProvider } from './PlatformProvider';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the active platform backend.
|
||||||
|
* Currently always returns the browser provider; native (e.g. Tauri) switching can be added here later.
|
||||||
|
*/
|
||||||
|
export function createPlatformProvider(): PlatformProvider {
|
||||||
|
return createBrowserProvider();
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/**
|
||||||
|
* Thrown when a provider method is declared or expected but not wired yet.
|
||||||
|
* Distinct from {@link NotSupportedMethod} (platform does not support this call).
|
||||||
|
*/
|
||||||
|
export class NotImplementedError extends Error {
|
||||||
|
readonly code = 'NOT_IMPLEMENTED' as const;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly capability: string,
|
||||||
|
message?: string,
|
||||||
|
) {
|
||||||
|
super(message ?? `Capability not implemented: ${capability}`);
|
||||||
|
this.name = 'NotImplementedError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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(type)` when `type` ∉ `downloadTypes`).
|
||||||
|
* Callers should use `instanceof` / `code` — never treat as a silent no-op.
|
||||||
|
*/
|
||||||
|
export class NotSupportedMethod extends Error {
|
||||||
|
readonly code = 'NOT_SUPPORTED' as const;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly capability: string,
|
||||||
|
message?: string,
|
||||||
|
) {
|
||||||
|
super(message ?? `Capability not supported: ${capability}`);
|
||||||
|
this.name = 'NotSupportedMethod';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import type { PlatformProvider } from './PlatformProvider';
|
||||||
|
|
||||||
|
/** Non-React callers (thunks / modules) after AppRoot finishes `init()` and publishes the singleton. */
|
||||||
|
let platformSingleton: PlatformProvider | null = null;
|
||||||
|
|
||||||
|
export function setPlatform(provider: PlatformProvider): void {
|
||||||
|
platformSingleton = provider;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPlatform(): PlatformProvider {
|
||||||
|
if (!platformSingleton) {
|
||||||
|
throw new Error('Platform provider is not ready. Call setPlatform() after provider.init() completes.');
|
||||||
|
}
|
||||||
|
return platformSingleton;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import type { StagingKugouKey } from '~/features/kugou/types';
|
||||||
|
import type { StagingKWMv2Key } from '~/features/kwm/types';
|
||||||
|
import type { StagingQMCv2Key } from '~/features/qmc/types';
|
||||||
|
import type { StagingQtfmSettings } from '~/features/qtfm/types';
|
||||||
|
import type { AndroidImportType, BatchDownloadType, NativeImportType } from './capabilities';
|
||||||
|
|
||||||
|
export interface PlatformCapabilities {
|
||||||
|
/** Supported batch/single download modes (array). */
|
||||||
|
downloadTypes: readonly BatchDownloadType[];
|
||||||
|
/**
|
||||||
|
* Whether the platform can write decrypted files directly to the local filesystem
|
||||||
|
* (e.g. beside source or a fixed output directory). Gates DirectWrite-related settings UI.
|
||||||
|
*/
|
||||||
|
directFsAccess: boolean;
|
||||||
|
/** Android key import path (single value). */
|
||||||
|
androidKeyAccess: AndroidImportType;
|
||||||
|
/** One-click native import targets (array; empty = unsupported). */
|
||||||
|
nativeKeyAccess: readonly NativeImportType[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadOneInput {
|
||||||
|
/** Object URL of the decrypted content. */
|
||||||
|
url: string;
|
||||||
|
/** Suggested download file name (including extension). */
|
||||||
|
fileName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadManyFile {
|
||||||
|
url: string;
|
||||||
|
fileName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadManyInput {
|
||||||
|
files: readonly DownloadManyFile[];
|
||||||
|
/** Remember FS Access directory handle when using SelectDirectory. */
|
||||||
|
rememberDirectory?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DownloadManyResult = 'ok' | 'cancelled';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Native / ADB import payload shaped for existing Redux `*ImportKeys` / qtfm staging updates.
|
||||||
|
* Rows omit `id` (reducers assign ids).
|
||||||
|
*/
|
||||||
|
export interface NativeImportResult {
|
||||||
|
qmc2?: Omit<StagingQMCv2Key, 'id'>[];
|
||||||
|
kwm2?: Omit<StagingKWMv2Key, 'id'>[];
|
||||||
|
kugou?: Omit<StagingKugouKey, 'id'>[];
|
||||||
|
qtfm?: Partial<StagingQtfmSettings>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AndroidAdbImportOptions {
|
||||||
|
/** Optional subset of formats to pull; omit = all declared android targets. */
|
||||||
|
targets?: readonly NativeImportType[];
|
||||||
|
}
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
import { RenderOptions, render } from '@testing-library/react';
|
import { RenderOptions, render } from '@testing-library/react';
|
||||||
import { PropsWithChildren } from 'react';
|
import { PropsWithChildren } from 'react';
|
||||||
import { Provider } from 'react-redux';
|
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';
|
import { AppStore, RootState, setupStore } from '~/store';
|
||||||
|
|
||||||
// Adapted from: https://redux.js.org/usage/writing-tests
|
// Adapted from: https://redux.js.org/usage/writing-tests
|
||||||
@@ -8,18 +13,40 @@ import { AppStore, RootState, setupStore } from '~/store';
|
|||||||
// eslint-disable-next-line react-refresh/only-export-components
|
// eslint-disable-next-line react-refresh/only-export-components
|
||||||
export * from '@testing-library/react';
|
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 {
|
export interface ExtendedRenderOptions extends RenderOptions {
|
||||||
preloadedState?: Partial<RootState>;
|
preloadedState?: Partial<RootState>;
|
||||||
store?: AppStore;
|
store?: AppStore;
|
||||||
|
/** Override platform backend (defaults to BrowserProvider with stub crypto). */
|
||||||
|
platform?: PlatformProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderWithProviders(
|
export function renderWithProviders(
|
||||||
ui: React.ReactElement,
|
ui: React.ReactElement,
|
||||||
{ preloadedState = {}, store = setupStore(preloadedState), ...renderOptions }: ExtendedRenderOptions = {},
|
{
|
||||||
|
preloadedState = {},
|
||||||
|
store = setupStore(preloadedState),
|
||||||
|
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 {
|
function Wrapper({ children }: PropsWithChildren<unknown>): React.JSX.Element {
|
||||||
return <Provider store={store}>{children}</Provider>;
|
return (
|
||||||
|
<Provider store={store}>
|
||||||
|
<PlatformProviderHost provider={platform}>{children}</PlatformProviderHost>
|
||||||
|
</Provider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
|
return { store, platform, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
|
||||||
}
|
}
|
||||||
Vendored
-4
@@ -17,7 +17,3 @@ declare module '*&mac-command' {
|
|||||||
export const commandName: string;
|
export const commandName: string;
|
||||||
export const tarName: string;
|
export const tarName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
declare interface Window {
|
|
||||||
BASE_URL: string;
|
|
||||||
}
|
|
||||||
+2
-1
@@ -22,7 +22,7 @@ const version = `${pkg.version} (${shortCommit})`;
|
|||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
base: './',
|
base: '/',
|
||||||
worker: {
|
worker: {
|
||||||
format: 'es',
|
format: 'es',
|
||||||
},
|
},
|
||||||
@@ -97,6 +97,7 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
build: {
|
build: {
|
||||||
|
assetsDir: 'um-react.assets',
|
||||||
minify: true,
|
minify: true,
|
||||||
rolldownOptions: {
|
rolldownOptions: {
|
||||||
output: {
|
output: {
|
||||||
|
|||||||
Reference in new issue
Block a user