Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

chore: optimization audit batch (ICO, BaseBuilder, CLI errors, CI lanes)

Tw93e87bea44f443
diff --git a/.github/workflows/quality-and-test.yml b/.github/workflows/quality-and-test.yml
index 6800dedb..b537e4d0 100644
--- a/.github/workflows/quality-and-test.yml
+++ b/.github/workflows/quality-and-test.yml
@@ -79,18 +79,10 @@ jobs:
- uses: rui314/setup-mold@v1
- - name: Cache cargo-hack
- uses: actions/cache@v5
- id: cargo-hack-cache
- with:
- path: ~/.cargo/bin/cargo-hack
- key: ${{ runner.os }}-cargo-hack-${{ hashFiles('~/.cargo/bin/cargo-hack') }}
- restore-keys: |
- ${{ runner.os }}-cargo-hack-
-
- name: Install cargo-hack
- if: steps.cargo-hack-cache.outputs.cache-hit != 'true'
- run: cargo install cargo-hack --force
+ uses: taiki-e/install-action@v2
+ with:
+ tool: cargo-hack
- name: Check Rust formatting
run: cargo fmt --all -- --color=always --check
@@ -98,8 +90,11 @@ jobs:
- name: Run Clippy lints
run: cargo hack --feature-powerset --exclude-features cli-build --no-dev-deps clippy # cspell:disable-line
- validation:
- name: CLI & Build Validation (${{ matrix.os }})
+ # Fast lane: runs on every PR and push. Skips the heavy real Tauri build
+ # (kept under tests/index.js) but still covers Vitest + integration suites
+ # so feedback stays under ~5 minutes per OS instead of 20+.
+ validation-fast:
+ name: CLI Fast Validation (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
matrix:
@@ -117,14 +112,15 @@ jobs:
- name: Build CLI
run: pnpm run cli:build
- - name: Run CI Test Suite
- run: pnpm test
- timeout-minutes: 30
+ - name: Run Fast Test Suite
+ shell: bash
+ run: PAKE_CREATE_APP=1 node tests/index.js --no-build
+ timeout-minutes: 15
env:
CI: true
NODE_ENV: test
- - name: Test CLI Integration
+ - name: Test CLI Integration (smoke)
shell: bash
run: |
echo "Testing CLI integration..."
@@ -134,10 +130,36 @@ jobs:
timeout 30s PAKE_CREATE_APP=1 node dist/cli.js https://weekly.tw93.fun --name "CITest" --debug --iterative-build || true
fi
+ # Full lane: only runs after merge to main (push event) or manual dispatch.
+ # Keeps the real Tauri build coverage off the PR critical path.
+ validation-full:
+ name: Full Tauri Build (${{ matrix.os }})
+ if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ fail-fast: false
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v6
+
+ - name: Setup Build Environment
+ uses: ./.github/actions/setup-env
+ with:
+ mode: build
+
+ - name: Run Full Test Suite (with real build)
+ run: pnpm test
+ timeout-minutes: 30
+ env:
+ CI: true
+ NODE_ENV: test
+
summary:
name: Quality Summary
runs-on: ubuntu-latest
- needs: [auto-format, rust-quality, validation]
+ needs: [auto-format, rust-quality, validation-fast, validation-full]
if: always()
steps:
- name: Generate Summary
@@ -149,5 +171,6 @@ jobs:
echo "|-------|--------|"
echo "| Auto Formatting | ${{ needs.auto-format.result == 'success' && 'PASSED' || needs.auto-format.result == 'skipped' && 'SKIPPED' || 'FAILED' }} |"
echo "| Rust Quality | ${{ needs.rust-quality.result == 'success' && 'PASSED' || 'FAILED' }} |"
- echo "| CLI & Build Validation | ${{ needs.validation.result == 'success' && 'PASSED' || 'FAILED' }} |"
+ echo "| CLI Fast Validation | ${{ needs.validation-fast.result == 'success' && 'PASSED' || 'FAILED' }} |"
+ echo "| Full Tauri Build | ${{ needs.validation-full.result == 'success' && 'PASSED' || needs.validation-full.result == 'skipped' && 'SKIPPED (PR fast lane)' || 'FAILED' }} |"
} >> $GITHUB_STEP_SUMMARY
diff --git a/README.md b/README.md
index 7d1889e7..2e421e12 100644
--- a/README.md
+++ b/README.md
@@ -177,7 +177,7 @@ First-time packaging requires environment setup and may be slower, subsequent bu
## Development
-Requires Rust `>=1.85` and Node `>=22`. For detailed installation guide, see [Tauri documentation](https://v2.tauri.app/start/prerequisites/). If unfamiliar with development environment, use the CLI tool instead.
+Requires Rust `>=1.85` and Node `>=22` (recommended LTS; `>=18` also works). For detailed installation guide, see [Tauri documentation](https://v2.tauri.app/start/prerequisites/). If unfamiliar with development environment, use the CLI tool instead.
```bash
# Install dependencies
diff --git a/README_CN.md b/README_CN.md
index 5562c139..4f4ddfa3 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -178,7 +178,7 @@ pake https://weekly.tw93.fun --name Weekly --icon https://cdn.tw93.fun/pake/week
## 定制开发
-需要 Rust `>=1.85` 和 Node `>=22`,详细安装指南参考 [Tauri 文档](https://tauri.app/start/prerequisites/)。不熟悉开发环境建议直接使用命令行工具。
+需要 Rust `>=1.85` 和 Node `>=22`(推荐 LTS,较旧的 `>=18` 也可使用),详细安装指南参考 [Tauri 文档](https://tauri.app/start/prerequisites/)。不熟悉开发环境建议直接使用命令行工具。
```bash
# 安装依赖
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.ts
index d416557c..c8a6f27c 100644
--- a/bin/builders/BaseBuilder.ts
+++ b/bin/builders/BaseBuilder.ts
@@ -17,146 +17,23 @@ import { shellExec } from '@/utils/shell';
import { CN_MIRROR_ENV, isCnMirrorEnabled } from '@/utils/mirror';
import { IS_MAC } from '@/utils/platform';
import logger from '@/options/logger';
+import {
+ configureCargoRegistry,
+ detectPackageManager,
+ getBuildEnvironment,
+ getBuildTimeout,
+ getInstallCommand,
+ getInstallTimeout,
+ isLinuxDeployStripError,
+} from './env';
export default abstract class BaseBuilder {
protected options: PakeAppOptions;
- private static packageManagerCache: string | null = null;
protected constructor(options: PakeAppOptions) {
this.options = options;
}
- private getBuildEnvironment() {
- if (!IS_MAC) {
- return undefined;
- }
-
- const currentPath = process.env.PATH || '';
- const systemToolsPath = '/usr/bin';
- const buildPath = currentPath.startsWith(`${systemToolsPath}:`)
- ? currentPath
- : `${systemToolsPath}:${currentPath}`;
-
- return {
- CFLAGS: '-fno-modules',
- CXXFLAGS: '-fno-modules',
- MACOSX_DEPLOYMENT_TARGET: '14.0',
- PATH: buildPath,
- };
- }
-
- private getInstallTimeout(): number {
- // Windows needs more time due to native compilation and antivirus scanning
- return process.platform === 'win32' ? 900000 : 600000;
- }
-
- private getBuildTimeout(): number {
- return 900000;
- }
-
- private async detectPackageManager(): Promise<string> {
- if (BaseBuilder.packageManagerCache) {
- return BaseBuilder.packageManagerCache;
- }
-
- const { execa } = await import('execa');
-
- try {
- await execa('pnpm', ['--version'], { stdio: 'ignore' });
- logger.info('✺ Using pnpm for package management.');
- BaseBuilder.packageManagerCache = 'pnpm';
- return 'pnpm';
- } catch {
- try {
- await execa('npm', ['--version'], { stdio: 'ignore' });
- logger.info('✺ pnpm not available, using npm for package management.');
- BaseBuilder.packageManagerCache = 'npm';
- return 'npm';
- } catch {
- throw new Error(
- 'Neither pnpm nor npm is available. Please install a package manager.',
- );
- }
- }
- }
-
- private async copyFileWithSamePathGuard(
- sourcePath: string,
- destinationPath: string,
- ): Promise<void> {
- if (path.resolve(sourcePath) === path.resolve(destinationPath)) {
- return;
- }
-
- try {
- await fsExtra.copy(sourcePath, destinationPath, { overwrite: true });
- } catch (error) {
- if (
- error instanceof Error &&
- error.message.includes('Source and destination must not be the same')
- ) {
- return;
- }
-
- throw error;
- }
- }
-
- private getInstallCommand(
- packageManager: string,
- useCnMirror: boolean,
- ): string {
- const registryOption = useCnMirror
- ? ' --registry=https://registry.npmmirror.com'
- : '';
- const peerDepsOption =
- packageManager === 'npm' ? ' --legacy-peer-deps' : '';
-
- return `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`;
- }
-
- private isGeneratedCnMirrorConfig(
- projectConfig: string,
- cnMirrorConfig: string,
- ): boolean {
- return projectConfig.trim() === cnMirrorConfig.trim();
- }
-
- private async configureCargoRegistry(
- tauriSrcPath: string,
- useCnMirror: boolean,
- ): Promise<void> {
- const rustProjectDir = path.join(tauriSrcPath, '.cargo');
- const projectConf = path.join(rustProjectDir, 'config.toml');
- const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
-
- if (useCnMirror) {
- await fsExtra.ensureDir(rustProjectDir);
- await this.copyFileWithSamePathGuard(projectCnConf, projectConf);
- return;
- }
-
- if (!(await fsExtra.pathExists(projectConf))) {
- return;
- }
-
- const [projectConfig, cnMirrorConfig] = await Promise.all([
- fsExtra.readFile(projectConf, 'utf8'),
- fsExtra.readFile(projectCnConf, 'utf8'),
- ]);
-
- if (this.isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig)) {
- await fsExtra.remove(projectConf);
- return;
- }
-
- if (projectConfig.includes('rsproxy.cn')) {
- logger.warn(
- `✼ ${projectConf} still references rsproxy.cn. Remove it or set ${CN_MIRROR_ENV}=1 if you want to use the CN mirror.`,
- );
- }
- }
-
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
const tauriTargetPath = path.join(tauriSrcPath, 'target');
@@ -186,13 +63,11 @@ export default abstract class BaseBuilder {
const spinner = getSpinner('Installing package...');
const useCnMirror = isCnMirrorEnabled();
- await this.configureCargoRegistry(tauriSrcPath, useCnMirror);
-
- // Detect available package manager
- const packageManager = await this.detectPackageManager();
+ await configureCargoRegistry(tauriSrcPath, useCnMirror);
- const timeout = this.getInstallTimeout();
- const buildEnv = this.getBuildEnvironment();
+ const packageManager = await detectPackageManager();
+ const timeout = getInstallTimeout();
+ const buildEnv = getBuildEnvironment();
// Show helpful message for first-time users
if (!tauriTargetPathExists) {
@@ -210,14 +85,10 @@ export default abstract class BaseBuilder {
}
try {
- await shellExec(
- this.getInstallCommand(packageManager, useCnMirror),
- timeout,
- {
- ...buildEnv,
- CI: 'true',
- },
- );
+ await shellExec(getInstallCommand(packageManager, useCnMirror), timeout, {
+ ...buildEnv,
+ CI: 'true',
+ });
spinner.succeed(chalk.green('Package installed!'));
} catch (error) {
spinner.fail(chalk.red('Installation failed'));
@@ -244,7 +115,7 @@ export default abstract class BaseBuilder {
logger.info('Pake dev server starting...');
await mergeConfig(url, this.options, tauriConfig);
- const packageManager = await this.detectPackageManager();
+ const packageManager = await detectPackageManager();
const configPath = path.join(
npmDirectory,
'src-tauri',
@@ -266,8 +137,7 @@ export default abstract class BaseBuilder {
const { name = 'pake-app' } = this.options;
await mergeConfig(url, this.options, tauriConfig);
- // Detect available package manager
- const packageManager = await this.detectPackageManager();
+ const packageManager = await detectPackageManager();
// Build app
const buildSpinner = getSpinner('Building app...');
@@ -277,7 +147,7 @@ export default abstract class BaseBuilder {
// Show static message to keep the status visible
logger.warn('✸ Building app...');
- const baseEnv = this.getBuildEnvironment();
+ const baseEnv = getBuildEnvironment();
let buildEnv: Record<string, string> = {
...(baseEnv ?? {}),
...(process.env.NO_STRIP ? { NO_STRIP: process.env.NO_STRIP } : {}),
@@ -301,7 +171,7 @@ export default abstract class BaseBuilder {
}
const buildCommand = `cd "${npmDirectory}" && ${this.getBuildCommand(packageManager)}`;
- const buildTimeout = this.getBuildTimeout();
+ const buildTimeout = getBuildTimeout();
try {
await shellExec(buildCommand, buildTimeout, resolveExecEnv());
@@ -310,7 +180,7 @@ export default abstract class BaseBuilder {
process.platform === 'linux' &&
target === 'appimage' &&
!buildEnv.NO_STRIP &&
- this.isLinuxDeployStripError(error);
+ isLinuxDeployStripError(error);
if (shouldRetryWithoutStrip) {
logger.warn(
@@ -388,21 +258,6 @@ export default abstract class BaseBuilder {
abstract getFileName(): string;
- private isLinuxDeployStripError(error: unknown): boolean {
- if (!(error instanceof Error) || !error.message) {
- return false;
- }
- const message = error.message.toLowerCase();
- return (
- message.includes('linuxdeploy') ||
- message.includes('failed to run linuxdeploy') ||
- message.includes('strip:') ||
- message.includes('unable to recognise the format of the input file') ||
- message.includes('appimage tool failed') ||
- message.includes('strip tool')
- );
- }
-
protected static readonly ARCH_MAPPINGS: Record<
string,
Record<string, string>
diff --git a/bin/builders/env.ts b/bin/builders/env.ts
new file mode 100644
index 00000000..bb400007
--- /dev/null
+++ b/bin/builders/env.ts
@@ -0,0 +1,175 @@
+import path from 'path';
+import fsExtra from 'fs-extra';
+
+import { CN_MIRROR_ENV } from '@/utils/mirror';
+import { IS_MAC } from '@/utils/platform';
+import { npmDirectory } from '@/utils/dir';
+import logger from '@/options/logger';
+
+/**
+ * Returns build environment variables overrides for macOS, where Rust crates
+ * sometimes need explicit C/C++ flags and a deterministic SDK target. Other
+ * platforms inherit `process.env` unchanged.
+ */
+export function getBuildEnvironment(): Record<string, string> | undefined {
+ if (!IS_MAC) {
+ return undefined;
+ }
+
+ const currentPath = process.env.PATH || '';
+ const systemToolsPath = '/usr/bin';
+ const buildPath = currentPath.startsWith(`${systemToolsPath}:`)
+ ? currentPath
+ : `${systemToolsPath}:${currentPath}`;
+
+ return {
+ CFLAGS: '-fno-modules',
+ CXXFLAGS: '-fno-modules',
+ MACOSX_DEPLOYMENT_TARGET: '14.0',
+ PATH: buildPath,
+ };
+}
+
+/**
+ * Windows needs more time due to native compilation and antivirus scanning.
+ */
+export function getInstallTimeout(): number {
+ return process.platform === 'win32' ? 900_000 : 600_000;
+}
+
+export function getBuildTimeout(): number {
+ return 900_000;
+}
+
+let packageManagerCache: 'pnpm' | 'npm' | null = null;
+
+/** Resets the cached package manager. Exported for tests. */
+export function _resetPackageManagerCache(): void {
+ packageManagerCache = null;
+}
+
+/**
+ * Returns 'pnpm' when available, otherwise 'npm'. Throws if neither is found.
+ * Cached after the first successful detection so tests can call repeatedly.
+ */
+export async function detectPackageManager(): Promise<'pnpm' | 'npm'> {
+ if (packageManagerCache) {
+ return packageManagerCache;
+ }
+
+ const { execa } = await import('execa');
+ try {
+ await execa('pnpm', ['--version'], { stdio: 'ignore' });
+ logger.info('✺ Using pnpm for package management.');
+ packageManagerCache = 'pnpm';
+ return 'pnpm';
+ } catch {
+ try {
+ await execa('npm', ['--version'], { stdio: 'ignore' });
+ logger.info('✺ pnpm not available, using npm for package management.');
+ packageManagerCache = 'npm';
+ return 'npm';
+ } catch {
+ throw new Error(
+ 'Neither pnpm nor npm is available. Please install a package manager.',
+ );
+ }
+ }
+}
+
+export function getInstallCommand(
+ packageManager: string,
+ useCnMirror: boolean,
+): string {
+ const registryOption = useCnMirror
+ ? ' --registry=https://registry.npmmirror.com'
+ : '';
+ const peerDepsOption = packageManager === 'npm' ? ' --legacy-peer-deps' : '';
+ return `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`;
+}
+
+async function copyFileWithSamePathGuard(
+ sourcePath: string,
+ destinationPath: string,
+): Promise<void> {
+ if (path.resolve(sourcePath) === path.resolve(destinationPath)) {
+ return;
+ }
+ try {
+ await fsExtra.copy(sourcePath, destinationPath, { overwrite: true });
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ error.message.includes('Source and destination must not be the same')
+ ) {
+ return;
+ }
+ throw error;
+ }
+}
+
+function isGeneratedCnMirrorConfig(
+ projectConfig: string,
+ cnMirrorConfig: string,
+): boolean {
+ return projectConfig.trim() === cnMirrorConfig.trim();
+}
+
+/**
+ * Toggles `.cargo/config.toml` to point at rsproxy.cn when the user opts in
+ * via `PAKE_USE_CN_MIRROR=1`, and removes the auto-generated mirror config
+ * (or warns about a manual one) when they opt out.
+ */
+export async function configureCargoRegistry(
+ tauriSrcPath: string,
+ useCnMirror: boolean,
+): Promise<void> {
+ const rustProjectDir = path.join(tauriSrcPath, '.cargo');
+ const projectConf = path.join(rustProjectDir, 'config.toml');
+ const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
+
+ if (useCnMirror) {
+ await fsExtra.ensureDir(rustProjectDir);
+ await copyFileWithSamePathGuard(projectCnConf, projectConf);
+ return;
+ }
+
+ if (!(await fsExtra.pathExists(projectConf))) {
+ return;
+ }
+
+ const [projectConfig, cnMirrorConfig] = await Promise.all([
+ fsExtra.readFile(projectConf, 'utf8'),
+ fsExtra.readFile(projectCnConf, 'utf8'),
+ ]);
+
+ if (isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig)) {
+ await fsExtra.remove(projectConf);
+ return;
+ }
+
+ if (projectConfig.includes('rsproxy.cn')) {
+ logger.warn(
+ `✼ ${projectConf} still references rsproxy.cn. Remove it or set ${CN_MIRROR_ENV}=1 if you want to use the CN mirror.`,
+ );
+ }
+}
+
+/**
+ * Returns true when an error string looks like the well-known Tauri+linuxdeploy
+ * strip failure that we automatically retry with NO_STRIP=1.
+ */
+export function isLinuxDeployStripError(error: unknown): boolean {
+ if (!(error instanceof Error) || !error.message) {
+ return false;
+ }
+ const message = error.message.toLowerCase();
+ return (
+ message.includes('linuxdeploy') ||
+ message.includes('failed to run linuxdeploy') ||
+ message.includes('strip:') ||
+ message.includes('unable to recognise the format of the input file') ||
+ message.includes('appimage tool failed') ||
+ message.includes('strip tool')
+ );
+}
diff --git a/bin/cli.ts b/bin/cli.ts
index 69f42381..8fe6738c 100644
--- a/bin/cli.ts
+++ b/bin/cli.ts
@@ -1,9 +1,11 @@
import log from 'loglevel';
+import chalk from 'chalk';
import updateNotifier from 'update-notifier';
import packageJson from '../package.json';
import BuilderProvider from './builders/BuilderProvider';
import handleInputOptions from './options/index';
import { getCliProgram } from './helpers/cli-program';
+import { isPakeError } from './utils/error';
import { PakeCliOptions } from './types';
const program = getCliProgram();
@@ -15,26 +17,47 @@ async function checkUpdateTips() {
}
program.action(async (url: string, options: PakeCliOptions) => {
- await checkUpdateTips();
-
- if (!url) {
- program.help({
- error: false,
- });
- return;
+ try {
+ await checkUpdateTips();
+
+ if (!url) {
+ program.help({
+ error: false,
+ });
+ return;
+ }
+
+ log.setDefaultLevel('info');
+ log.setLevel('info');
+ if (options.debug) {
+ log.setLevel('debug');
+ }
+
+ const appOptions = await handleInputOptions(options, url);
+
+ const builder = BuilderProvider.create(appOptions);
+ await builder.prepare();
+ await builder.build(url);
+ } catch (error) {
+ if (isPakeError(error)) {
+ console.error(chalk.red(error.message));
+ } else if (error instanceof Error) {
+ console.error(chalk.red(`✕ ${error.message}`));
+ if (options?.debug && error.stack) {
+ console.error(chalk.gray(error.stack));
+ }
+ } else {
+ console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));
+ }
+ process.exit(1);
}
+});
- log.setDefaultLevel('info');
- log.setLevel('info');
- if (options.debug) {
- log.setLevel('debug');
+program.parseAsync().catch((error: unknown) => {
+ if (error instanceof Error) {
+ console.error(chalk.red(`✕ ${error.message}`));
+ } else {
+ console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));
}
-
- const appOptions = await handleInputOptions(options, url);
-
- const builder = BuilderProvider.create(appOptions);
- await builder.prepare();
- await builder.build(url);
+ process.exit(1);
});
-
-program.parse();
diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.ts
index fa650378..0425e9d8 100644
--- a/bin/helpers/merge.ts
+++ b/bin/helpers/merge.ts
@@ -18,6 +18,45 @@ import {
} from '@/types';
import { tauriConfigDirectory, npmDirectory } from '@/utils/dir';
+/**
+ * Pure transform from CLI options to the window-config slice that gets
+ * merged into pake.json. Exposed for snapshot testing so option drift
+ * (e.g. a new flag added in cli-program.ts but forgotten here) is caught.
+ *
+ * Keep this function side-effect free.
+ */
+export function buildWindowConfigOverrides(
+ options: PakeAppOptions,
+ platform: SupportedPlatform = asSupportedPlatform(process.platform),
+): Partial<WindowConfig> {
+ const platformHideOnClose = options.hideOnClose ?? platform === 'darwin';
+ return {
+ width: options.width,
+ height: options.height,
+ fullscreen: options.fullscreen,
+ maximize: options.maximize,
+ resizable: options.resizable ?? true,
+ hide_title_bar: options.hideTitleBar,
+ activation_shortcut: options.activationShortcut,
+ always_on_top: options.alwaysOnTop,
+ dark_mode: options.darkMode,
+ disabled_web_shortcuts: options.disabledWebShortcuts,
+ hide_on_close: platformHideOnClose,
+ incognito: options.incognito,
+ title: options.title,
+ enable_wasm: options.wasm,
+ enable_drag_drop: options.enableDragDrop,
+ start_to_tray: options.startToTray && options.showSystemTray,
+ force_internal_navigation: options.forceInternalNavigation,
+ internal_url_regex: options.internalUrlRegex,
+ zoom: options.zoom,
+ min_width: options.minWidth,
+ min_height: options.minHeight,
+ ignore_certificate_errors: options.ignoreCertificateErrors,
+ new_window: options.newWindow,
+ };
+}
+
type PlatformIconInfo = {
fileExt: string;
path: string;
@@ -388,68 +427,20 @@ export async function mergeConfig(
await copyTemplateConfigs();
const {
- width,
- height,
- fullscreen,
- maximize,
- hideTitleBar,
- alwaysOnTop,
appVersion,
- darkMode,
- disabledWebShortcuts,
- activationShortcut,
userAgent,
showSystemTray,
useLocalFile,
identifier,
name = 'pake-app',
- resizable = true,
installerLanguage,
- hideOnClose,
- incognito,
- title,
wasm,
- enableDragDrop,
- startToTray,
- forceInternalNavigation,
- internalUrlRegex,
- zoom,
- minWidth,
- minHeight,
- ignoreCertificateErrors,
- newWindow,
camera,
microphone,
} = options;
const platform = asSupportedPlatform(process.platform);
- const platformHideOnClose = hideOnClose ?? platform === 'darwin';
-
- const tauriConfWindowOptions: Partial<WindowConfig> = {
- width,
- height,
- fullscreen,
- maximize,
- resizable,
- hide_title_bar: hideTitleBar,
- activation_shortcut: activationShortcut,
- always_on_top: alwaysOnTop,
- dark_mode: darkMode,
- disabled_web_shortcuts: disabledWebShortcuts,
- hide_on_close: platformHideOnClose,
- incognito,
- title,
- enable_wasm: wasm,
- enable_drag_drop: enableDragDrop,
- start_to_tray: startToTray && showSystemTray,
- force_internal_navigation: forceInternalNavigation,
- internal_url_regex: internalUrlRegex,
- zoom,
- min_width: minWidth,
- min_height: minHeight,
- ignore_certificate_errors: ignoreCertificateErrors,
- new_window: newWindow,
- };
+ const tauriConfWindowOptions = buildWindowConfigOverrides(options, platform);
Object.assign(tauriConf.pake.windows[0], { url, ...tauriConfWindowOptions });
tauriConf.productName = name;
diff --git a/bin/options/icon.ts b/bin/options/icon.ts
index a068fb87..ca0c2966 100644
--- a/bin/options/icon.ts
+++ b/bin/options/icon.ts
@@ -17,7 +17,12 @@ import {
} from '@/utils/icon-source';
import { generateLinuxPackageName, getSafeAppName } from '@/utils/name';
import { PakeAppOptions } from '@/types';
-import { writeIcoWithPreferredSize, buildIcoFromPngBuffers } from '@/utils/ico';
+import {
+ ensureMultiResolutionIco,
+ writeIcoWithPreferredSize,
+ buildIcoFromPngBuffers,
+ WIN_STANDARD_ICO_SIZES,
+} from '@/utils/ico';
type PlatformIconConfig = {
format: string;
@@ -43,7 +48,7 @@ const ICON_CONFIG = {
} as const;
const PLATFORM_CONFIG: Record<'win' | 'linux' | 'macos', PlatformIconConfig> = {
- win: { format: '.ico', sizes: [16, 32, 48, 64, 128, 256] },
+ win: { format: '.ico', sizes: [...WIN_STANDARD_ICO_SIZES] },
linux: { format: '.png', size: 512 },
macos: { format: '.icns', sizes: [16, 32, 64, 128, 256, 512, 1024] },
};
@@ -89,14 +94,23 @@ async function copyWindowsIconIfNeeded(
try {
const finalIconPath = generateIconPath(appName);
await fsExtra.ensureDir(path.dirname(finalIconPath));
- // Reorder ICO to prioritize 256px icons for better Windows display
- const reordered = await writeIcoWithPreferredSize(
+ // Re-render ICO so every Windows standard size is present and prefer the
+ // 256px frame as the leading entry; falls back to plain reordering if the
+ // ICO is non-decodable, then to a raw copy. (Issue #1190)
+ const upgraded = await ensureMultiResolutionIco(
convertedPath,
finalIconPath,
256,
);
- if (!reordered) {
- await fsExtra.copy(convertedPath, finalIconPath);
+ if (!upgraded) {
+ const reordered = await writeIcoWithPreferredSize(
+ convertedPath,
+ finalIconPath,
+ 256,
+ );
+ if (!reordered) {
+ await fsExtra.copy(convertedPath, finalIconPath);
+ }
}
return finalIconPath;
} catch (error) {
diff --git a/bin/options/index.ts b/bin/options/index.ts
index 43618aae..63945874 100644
--- a/bin/options/index.ts
+++ b/bin/options/index.ts
@@ -10,6 +10,7 @@ import {
resolveIdentifier,
} from '@/utils/info';
import { generateLinuxPackageName } from '@/utils/name';
+import { PakeError } from '@/utils/error';
import { PakeAppOptions, PakeCliOptions } from '@/types';
function resolveAppName(name: string, platform: NodeJS.Platform): string {
@@ -68,12 +69,12 @@ export default async function handleOptions(
const DEFAULT_NAME_ERROR = `✕ Name should only include letters, numbers, dashes, and spaces (not leading dashes and spaces). Examples: 123pan, 123Pan, Pan123, weread, WeRead, WERead, we-read, We Read, 123.`;
const errorMsg =
platform === 'linux' ? LINUX_NAME_ERROR : DEFAULT_NAME_ERROR;
- logger.error(errorMsg);
if (isActions) {
+ logger.error(errorMsg);
name = resolveAppName(url, platform);
logger.warn(`✼ Inside github actions, use the default name: ${name}`);
} else {
- process.exit(1);
+ throw new PakeError(errorMsg);
}
}
diff --git a/bin/utils/error.ts b/bin/utils/error.ts
new file mode 100644
index 00000000..db641206
--- /dev/null
+++ b/bin/utils/error.ts
@@ -0,0 +1,25 @@
+/**
+ * Error class used for user-facing CLI errors.
+ *
+ * The top-level catch in `bin/cli.ts` prints `message` directly without a
+ * stack trace and exits with code 1. Use this for predictable failures
+ * (invalid names, missing files, etc.) so users see a clean message instead
+ * of a Node.js stack dump.
+ */
+export class PakeError extends Error {
+ readonly isUserError = true;
+
+ constructor(message: string) {
+ super(message);
+ this.name = 'PakeError';
+ }
+}
+
+export function isPakeError(error: unknown): error is PakeError {
+ return (
+ error instanceof PakeError ||
+ (typeof error === 'object' &&
+ error !== null &&
+ (error as { isUserError?: boolean }).isUserError === true)
+ );
+}
diff --git a/bin/utils/ico.ts b/bin/utils/ico.ts
index c082cba8..182d51cf 100644
--- a/bin/utils/ico.ts
+++ b/bin/utils/ico.ts
@@ -1,9 +1,13 @@
import path from 'path';
import fsExtra from 'fs-extra';
+import sharp from 'sharp';
const ICO_HEADER_SIZE = 6;
const ICO_DIR_ENTRY_SIZE = 16;
const ICO_TYPE_ICON = 1;
+// Standard Windows icon sizes covering tray (16/24/32), taskbar (32/48),
+// shell (48/256) and high-DPI (128/256). Issue #1190.
+export const WIN_STANDARD_ICO_SIZES = [16, 24, 32, 48, 64, 128, 256] as const;
type IcoEntry = {
index: number;
@@ -142,6 +146,122 @@ export async function writeIcoWithPreferredSize(
}
}
+/**
+ * PNG signature `\x89PNG`. ICO frames may carry either a BMP DIB or an
+ * embedded PNG payload (PNG-in-ICO, supported since Windows Vista).
+ */
+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
+
+function frameLooksLikePng(entry: IcoEntry): boolean {
+ return (
+ entry.data.length >= PNG_SIGNATURE.length &&
+ entry.data.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)
+ );
+}
+
+async function decodeFrameToPng(entry: IcoEntry): Promise<Buffer | null> {
+ if (frameLooksLikePng(entry)) {
+ return Buffer.from(entry.data);
+ }
+ // BMP DIB frames need to go through sharp's ico-to-PNG path, which only
+ // works on the full ICO container. Fall back to letting the caller use a
+ // sharp pipeline against the original ICO for the missing source.
+ return null;
+}
+
+async function pickLargestFrameAsPng(
+ buffer: Buffer,
+ entries: IcoEntry[],
+): Promise<Buffer | null> {
+ const largest = [...entries].sort(
+ (a, b) => Math.max(b.width, b.height) - Math.max(a.width, a.height),
+ )[0];
+ if (largest) {
+ const decoded = await decodeFrameToPng(largest);
+ if (decoded) {
+ return decoded;
+ }
+ }
+
+ // Fallback: let sharp render directly from the ICO buffer. sharp picks the
+ // largest embedded frame on its own.
+ try {
+ return await sharp(buffer).png().toBuffer();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Ensures the produced ICO carries every Windows standard size so the OS
+ * never has to downsample a 256x256 frame to 16x16 for the tray.
+ * Falls back to `writeIcoWithPreferredSize` if rendering fails.
+ *
+ * Issue #1190.
+ */
+export async function ensureMultiResolutionIco(
+ sourcePath: string,
+ outputPath: string,
+ preferredSize: number = 256,
+ desiredSizes: readonly number[] = WIN_STANDARD_ICO_SIZES,
+): Promise<boolean> {
+ try {
+ const sourceBuffer = await fsExtra.readFile(sourcePath);
+ const entries = parseIcoBuffer(sourceBuffer);
+
+ const sourcePng = await pickLargestFrameAsPng(sourceBuffer, entries);
+ if (!sourcePng) {
+ return await writeIcoWithPreferredSize(
+ sourcePath,
+ outputPath,
+ preferredSize,
+ );
+ }
+
+ const frames = await Promise.all(
+ desiredSizes.map(async (size) => {
+ // Reuse an existing exact-size PNG frame when possible to keep any
+ // hand-tuned small icon (e.g. a 16x16 with deliberate pixel hinting).
+ const exact = entries.find(
+ (entry) => entry.width === size && entry.height === size,
+ );
+ if (exact && frameLooksLikePng(exact)) {
+ return { size, png: Buffer.from(exact.data) };
+ }
+ const png = await sharp(sourcePng)
+ .resize(size, size, {
+ fit: 'contain',
+ background: { r: 0, g: 0, b: 0, alpha: 0 },
+ })
+ .ensureAlpha()
+ .png()
+ .toBuffer();
+ return { size, png };
+ }),
+ );
+
+ // Order frames so the preferred size lands first (Windows shell uses the
+ // first-listed frame as a quality hint when choosing which to display).
+ frames.sort((a, b) => {
+ const aExact = a.size === preferredSize ? 0 : 1;
+ const bExact = b.size === preferredSize ? 0 : 1;
+ if (aExact !== bExact) return aExact - bExact;
+ return b.size - a.size;
+ });
+
+ const icoBuffer = buildIcoFromPngBuffers(frames);
+ await fsExtra.ensureDir(path.dirname(outputPath));
+ await fsExtra.outputFile(outputPath, icoBuffer);
+ return true;
+ } catch {
+ return await writeIcoWithPreferredSize(
+ sourcePath,
+ outputPath,
+ preferredSize,
+ );
+ }
+}
+
/**
* Builds an ICO file from an array of PNG buffers using the PNG-in-ICO format
* (supported since Windows Vista). This preserves alpha transparency.
diff --git a/dist/cli.js b/dist/cli.js
index 076d2e4a..82e1a1c3 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -1,10 +1,10 @@
#!/usr/bin/env node
import log from 'loglevel';
+import chalk from 'chalk';
import updateNotifier from 'update-notifier';
import path from 'path';
import fsExtra from 'fs-extra';
import { fileURLToPath } from 'url';
-import chalk from 'chalk';
import prompts from 'prompts';
import os from 'os';
import { execa, execaSync } from 'execa';
@@ -436,6 +436,41 @@ function generateIdentifierSafeName(name) {
return cleaned;
}
+/**
+ * Pure transform from CLI options to the window-config slice that gets
+ * merged into pake.json. Exposed for snapshot testing so option drift
+ * (e.g. a new flag added in cli-program.ts but forgotten here) is caught.
+ *
+ * Keep this function side-effect free.
+ */
+function buildWindowConfigOverrides(options, platform = asSupportedPlatform(process.platform)) {
+ const platformHideOnClose = options.hideOnClose ?? platform === 'darwin';
+ return {
+ width: options.width,
+ height: options.height,
+ fullscreen: options.fullscreen,
+ maximize: options.maximize,
+ resizable: options.resizable ?? true,
+ hide_title_bar: options.hideTitleBar,
+ activation_shortcut: options.activationShortcut,
+ always_on_top: options.alwaysOnTop,
+ dark_mode: options.darkMode,
+ disabled_web_shortcuts: options.disabledWebShortcuts,
+ hide_on_close: platformHideOnClose,
+ incognito: options.incognito,
+ title: options.title,
+ enable_wasm: options.wasm,
+ enable_drag_drop: options.enableDragDrop,
+ start_to_tray: options.startToTray && options.showSystemTray,
+ force_internal_navigation: options.forceInternalNavigation,
+ internal_url_regex: options.internalUrlRegex,
+ zoom: options.zoom,
+ min_width: options.minWidth,
+ min_height: options.minHeight,
+ ignore_certificate_errors: options.ignoreCertificateErrors,
+ new_window: options.newWindow,
+ };
+}
function asSupportedPlatform(platform) {
if (platform !== 'win32' && platform !== 'darwin' && platform !== 'linux') {
throw new Error(`Pake only supports win32, darwin, and linux; detected '${platform}'.`);
@@ -691,34 +726,9 @@ async function writeAllConfigs(tauriConf, platform) {
}
async function mergeConfig(url, options, tauriConf) {
await copyTemplateConfigs();
- const { width, height, fullscreen, maximize, hideTitleBar, alwaysOnTop, appVersion, darkMode, disabledWebShortcuts, activationShortcut, userAgent, showSystemTray, useLocalFile, identifier, name = 'pake-app', resizable = true, installerLanguage, hideOnClose, incognito, title, wasm, enableDragDrop, startToTray, forceInternalNavigation, internalUrlRegex, zoom, minWidth, minHeight, ignoreCertificateErrors, newWindow, camera, microphone, } = options;
+ const { appVersion, userAgent, showSystemTray, useLocalFile, identifier, name = 'pake-app', installerLanguage, wasm, camera, microphone, } = options;
const platform = asSupportedPlatform(process.platform);
- const platformHideOnClose = hideOnClose ?? platform === 'darwin';
- const tauriConfWindowOptions = {
- width,
- height,
- fullscreen,
- maximize,
- resizable,
- hide_title_bar: hideTitleBar,
- activation_shortcut: activationShortcut,
- always_on_top: alwaysOnTop,
- dark_mode: darkMode,
- disabled_web_shortcuts: disabledWebShortcuts,
- hide_on_close: platformHideOnClose,
- incognito,
- title,
- enable_wasm: wasm,
- enable_drag_drop: enableDragDrop,
- start_to_tray: startToTray && showSystemTray,
- force_internal_navigation: forceInternalNavigation,
- internal_url_regex: internalUrlRegex,
- zoom,
- min_width: minWidth,
- min_height: minHeight,
- ignore_certificate_errors: ignoreCertificateErrors,
- new_window: newWindow,
- };
+ const tauriConfWindowOptions = buildWindowConfigOverrides(options, platform);
Object.assign(tauriConf.pake.windows[0], { url, ...tauriConfWindowOptions });
tauriConf.productName = name;
tauriConf.identifier = identifier;
@@ -764,104 +774,138 @@ async function mergeConfig(url, options, tauriConf) {
await writeAllConfigs(tauriConf, platform);
}
-class BaseBuilder {
- constructor(options) {
- this.options = options;
- }
- getBuildEnvironment() {
- if (!IS_MAC) {
- return undefined;
- }
- const currentPath = process.env.PATH || '';
- const systemToolsPath = '/usr/bin';
- const buildPath = currentPath.startsWith(`${systemToolsPath}:`)
- ? currentPath
- : `${systemToolsPath}:${currentPath}`;
- return {
- CFLAGS: '-fno-modules',
- CXXFLAGS: '-fno-modules',
- MACOSX_DEPLOYMENT_TARGET: '14.0',
- PATH: buildPath,
- };
+/**
+ * Returns build environment variables overrides for macOS, where Rust crates
+ * sometimes need explicit C/C++ flags and a deterministic SDK target. Other
+ * platforms inherit `process.env` unchanged.
+ */
+function getBuildEnvironment() {
+ if (!IS_MAC) {
+ return undefined;
}
- getInstallTimeout() {
- // Windows needs more time due to native compilation and antivirus scanning
- return process.platform === 'win32' ? 900000 : 600000;
+ const currentPath = process.env.PATH || '';
+ const systemToolsPath = '/usr/bin';
+ const buildPath = currentPath.startsWith(`${systemToolsPath}:`)
+ ? currentPath
+ : `${systemToolsPath}:${currentPath}`;
+ return {
+ CFLAGS: '-fno-modules',
+ CXXFLAGS: '-fno-modules',
+ MACOSX_DEPLOYMENT_TARGET: '14.0',
+ PATH: buildPath,
+ };
+}
+/**
+ * Windows needs more time due to native compilation and antivirus scanning.
+ */
+function getInstallTimeout() {
+ return process.platform === 'win32' ? 900000 : 600000;
+}
+function getBuildTimeout() {
+ return 900000;
+}
+let packageManagerCache = null;
+/**
+ * Returns 'pnpm' when available, otherwise 'npm'. Throws if neither is found.
+ * Cached after the first successful detection so tests can call repeatedly.
+ */
+async function detectPackageManager() {
+ if (packageManagerCache) {
+ return packageManagerCache;
}
- getBuildTimeout() {
- return 900000;
+ const { execa } = await import('execa');
+ try {
+ await execa('pnpm', ['--version'], { stdio: 'ignore' });
+ logger.info('✺ Using pnpm for package management.');
+ packageManagerCache = 'pnpm';
+ return 'pnpm';
}
- async detectPackageManager() {
- if (BaseBuilder.packageManagerCache) {
- return BaseBuilder.packageManagerCache;
- }
- const { execa } = await import('execa');
+ catch {
try {
- await execa('pnpm', ['--version'], { stdio: 'ignore' });
- logger.info('✺ Using pnpm for package management.');
- BaseBuilder.packageManagerCache = 'pnpm';
- return 'pnpm';
+ await execa('npm', ['--version'], { stdio: 'ignore' });
+ logger.info('✺ pnpm not available, using npm for package management.');
+ packageManagerCache = 'npm';
+ return 'npm';
}
catch {
- try {
- await execa('npm', ['--version'], { stdio: 'ignore' });
- logger.info('✺ pnpm not available, using npm for package management.');
- BaseBuilder.packageManagerCache = 'npm';
- return 'npm';
- }
- catch {
- throw new Error('Neither pnpm nor npm is available. Please install a package manager.');
- }
+ throw new Error('Neither pnpm nor npm is available. Please install a package manager.');
}
}
- async copyFileWithSamePathGuard(sourcePath, destinationPath) {
- if (path.resolve(sourcePath) === path.resolve(destinationPath)) {
+}
+function getInstallCommand(packageManager, useCnMirror) {
+ const registryOption = useCnMirror
+ ? ' --registry=https://registry.npmmirror.com'
+ : '';
+ const peerDepsOption = packageManager === 'npm' ? ' --legacy-peer-deps' : '';
+ return `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`;
+}
+async function copyFileWithSamePathGuard(sourcePath, destinationPath) {
+ if (path.resolve(sourcePath) === path.resolve(destinationPath)) {
+ return;
+ }
+ try {
+ await fsExtra.copy(sourcePath, destinationPath, { overwrite: true });
+ }
+ catch (error) {
+ if (error instanceof Error &&
+ error.message.includes('Source and destination must not be the same')) {
return;
}
- try {
- await fsExtra.copy(sourcePath, destinationPath, { overwrite: true });
- }
- catch (error) {
- if (error instanceof Error &&
- error.message.includes('Source and destination must not be the same')) {
- return;
- }
- throw error;
- }
+ throw error;
}
- getInstallCommand(packageManager, useCnMirror) {
- const registryOption = useCnMirror
- ? ' --registry=https://registry.npmmirror.com'
- : '';
- const peerDepsOption = packageManager === 'npm' ? ' --legacy-peer-deps' : '';
- return `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`;
+}
+function isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig) {
+ return projectConfig.trim() === cnMirrorConfig.trim();
+}
+/**
+ * Toggles `.cargo/config.toml` to point at rsproxy.cn when the user opts in
+ * via `PAKE_USE_CN_MIRROR=1`, and removes the auto-generated mirror config
+ * (or warns about a manual one) when they opt out.
+ */
+async function configureCargoRegistry(tauriSrcPath, useCnMirror) {
+ const rustProjectDir = path.join(tauriSrcPath, '.cargo');
+ const projectConf = path.join(rustProjectDir, 'config.toml');
+ const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
+ if (useCnMirror) {
+ await fsExtra.ensureDir(rustProjectDir);
+ await copyFileWithSamePathGuard(projectCnConf, projectConf);
+ return;
}
- isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig) {
- return projectConfig.trim() === cnMirrorConfig.trim();
+ if (!(await fsExtra.pathExists(projectConf))) {
+ return;
}
- async configureCargoRegistry(tauriSrcPath, useCnMirror) {
- const rustProjectDir = path.join(tauriSrcPath, '.cargo');
- const projectConf = path.join(rustProjectDir, 'config.toml');
- const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
- if (useCnMirror) {
- await fsExtra.ensureDir(rustProjectDir);
- await this.copyFileWithSamePathGuard(projectCnConf, projectConf);
- return;
- }
- if (!(await fsExtra.pathExists(projectConf))) {
- return;
- }
- const [projectConfig, cnMirrorConfig] = await Promise.all([
- fsExtra.readFile(projectConf, 'utf8'),
- fsExtra.readFile(projectCnConf, 'utf8'),
- ]);
- if (this.isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig)) {
- await fsExtra.remove(projectConf);
- return;
- }
- if (projectConfig.includes('rsproxy.cn')) {
- logger.warn(`✼ ${projectConf} still references rsproxy.cn. Remove it or set ${CN_MIRROR_ENV}=1 if you want to use the CN mirror.`);
- }
+ const [projectConfig, cnMirrorConfig] = await Promise.all([
+ fsExtra.readFile(projectConf, 'utf8'),
+ fsExtra.readFile(projectCnConf, 'utf8'),
+ ]);
+ if (isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig)) {
+ await fsExtra.remove(projectConf);
+ return;
+ }
+ if (projectConfig.includes('rsproxy.cn')) {
+ logger.warn(`✼ ${projectConf} still references rsproxy.cn. Remove it or set ${CN_MIRROR_ENV}=1 if you want to use the CN mirror.`);
+ }
+}
+/**
+ * Returns true when an error string looks like the well-known Tauri+linuxdeploy
+ * strip failure that we automatically retry with NO_STRIP=1.
+ */
+function isLinuxDeployStripError(error) {
+ if (!(error instanceof Error) || !error.message) {
+ return false;
+ }
+ const message = error.message.toLowerCase();
+ return (message.includes('linuxdeploy') ||
+ message.includes('failed to run linuxdeploy') ||
+ message.includes('strip:') ||
+ message.includes('unable to recognise the format of the input file') ||
+ message.includes('appimage tool failed') ||
+ message.includes('strip tool'));
+}
+
+class BaseBuilder {
+ constructor(options) {
+ this.options = options;
}
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
@@ -888,11 +932,10 @@ class BaseBuilder {
}
const spinner = getSpinner('Installing package...');
const useCnMirror = isCnMirrorEnabled();
- await this.configureCargoRegistry(tauriSrcPath, useCnMirror);
- // Detect available package manager
- const packageManager = await this.detectPackageManager();
- const timeout = this.getInstallTimeout();
- const buildEnv = this.getBuildEnvironment();
+ await configureCargoRegistry(tauriSrcPath, useCnMirror);
+ const packageManager = await detectPackageManager();
+ const timeout = getInstallTimeout();
+ const buildEnv = getBuildEnvironment();
// Show helpful message for first-time users
if (!tauriTargetPathExists) {
logger.info(process.platform === 'win32'
@@ -903,7 +946,7 @@ class BaseBuilder {
logger.info(`✺ ${CN_MIRROR_ENV}=1 detected, using ${packageManager}/rsProxy CN mirror.`);
}
try {
- await shellExec(this.getInstallCommand(packageManager, useCnMirror), timeout, {
+ await shellExec(getInstallCommand(packageManager, useCnMirror), timeout, {
...buildEnv,
CI: 'true',
});
@@ -926,7 +969,7 @@ class BaseBuilder {
async start(url) {
logger.info('Pake dev server starting...');
await mergeConfig(url, this.options, tauriConfig);
- const packageManager = await this.detectPackageManager();
+ const packageManager = await detectPackageManager();
const configPath = path.join(npmDirectory, 'src-tauri', '.pake', 'tauri.conf.json');
const features = this.getBuildFeatures();
const featureArgs = features.length > 0 ? `--features ${features.join(',')}` : '';
@@ -937,8 +980,7 @@ class BaseBuilder {
async buildAndCopy(url, target) {
const { name = 'pake-app' } = this.options;
await mergeConfig(url, this.options, tauriConfig);
- // Detect available package manager
- const packageManager = await this.detectPackageManager();
+ const packageManager = await detectPackageManager();
// Build app
const buildSpinner = getSpinner('Building app...');
// Let spinner run for a moment so user can see it, then stop before package manager command
@@ -946,7 +988,7 @@ class BaseBuilder {
buildSpinner.stop();
// Show static message to keep the status visible
logger.warn('✸ Building app...');
- const baseEnv = this.getBuildEnvironment();
+ const baseEnv = getBuildEnvironment();
let buildEnv = {
...(baseEnv ?? {}),
...(process.env.NO_STRIP ? { NO_STRIP: process.env.NO_STRIP } : {}),
@@ -962,7 +1004,7 @@ class BaseBuilder {
}
}
const buildCommand = `cd "${npmDirectory}" && ${this.getBuildCommand(packageManager)}`;
- const buildTimeout = this.getBuildTimeout();
+ const buildTimeout = getBuildTimeout();
try {
await shellExec(buildCommand, buildTimeout, resolveExecEnv());
}
@@ -970,7 +1012,7 @@ class BaseBuilder {
const shouldRetryWithoutStrip = process.platform === 'linux' &&
target === 'appimage' &&
!buildEnv.NO_STRIP &&
- this.isLinuxDeployStripError(error);
+ isLinuxDeployStripError(error);
if (shouldRetryWithoutStrip) {
logger.warn('⚠ AppImage build failed during linuxdeploy strip step, retrying with NO_STRIP=1 automatically.');
buildEnv = {
@@ -1026,18 +1068,6 @@ class BaseBuilder {
getFileType(target) {
return target;
}
- isLinuxDeployStripError(error) {
- if (!(error instanceof Error) || !error.message) {
- return false;
- }
- const message = error.message.toLowerCase();
- return (message.includes('linuxdeploy') ||
- message.includes('failed to run linuxdeploy') ||
- message.includes('strip:') ||
- message.includes('unable to recognise the format of the input file') ||
- message.includes('appimage tool failed') ||
- message.includes('strip tool'));
- }
resolveTargetArch(requestedArch) {
if (requestedArch === 'auto' || !requestedArch) {
return process.arch;
@@ -1175,7 +1205,6 @@ class BaseBuilder {
return 'src-tauri/target'; // Override in subclasses if needed
}
}
-BaseBuilder.packageManagerCache = null;
BaseBuilder.ARCH_MAPPINGS = {
darwin: {
arm64: 'aarch64-apple-darwin',
@@ -1511,6 +1540,9 @@ function getIconSourcePriority(url, appName) {
const ICO_HEADER_SIZE = 6;
const ICO_DIR_ENTRY_SIZE = 16;
const ICO_TYPE_ICON = 1;
+// Standard Windows icon sizes covering tray (16/24/32), taskbar (32/48),
+// shell (48/256) and high-DPI (128/256). Issue #1190.
+const WIN_STANDARD_ICO_SIZES = [16, 24, 32, 48, 64, 128, 256];
function decodeDimension(value) {
return value === 0 ? 256 : value;
}
@@ -1609,6 +1641,91 @@ async function writeIcoWithPreferredSize(sourcePath, outputPath, preferredSize)
return false;
}
}
+/**
+ * PNG signature `\x89PNG`. ICO frames may carry either a BMP DIB or an
+ * embedded PNG payload (PNG-in-ICO, supported since Windows Vista).
+ */
+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
+function frameLooksLikePng(entry) {
+ return (entry.data.length >= PNG_SIGNATURE.length &&
+ entry.data.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE));
+}
+async function decodeFrameToPng(entry) {
+ if (frameLooksLikePng(entry)) {
+ return Buffer.from(entry.data);
+ }
+ // BMP DIB frames need to go through sharp's ico-to-PNG path, which only
+ // works on the full ICO container. Fall back to letting the caller use a
+ // sharp pipeline against the original ICO for the missing source.
+ return null;
+}
+async function pickLargestFrameAsPng(buffer, entries) {
+ const largest = [...entries].sort((a, b) => Math.max(b.width, b.height) - Math.max(a.width, a.height))[0];
+ if (largest) {
+ const decoded = await decodeFrameToPng(largest);
+ if (decoded) {
+ return decoded;
+ }
+ }
+ // Fallback: let sharp render directly from the ICO buffer. sharp picks the
+ // largest embedded frame on its own.
+ try {
+ return await sharp(buffer).png().toBuffer();
+ }
+ catch {
+ return null;
+ }
+}
+/**
+ * Ensures the produced ICO carries every Windows standard size so the OS
+ * never has to downsample a 256x256 frame to 16x16 for the tray.
+ * Falls back to `writeIcoWithPreferredSize` if rendering fails.
+ *
+ * Issue #1190.
+ */
+async function ensureMultiResolutionIco(sourcePath, outputPath, preferredSize = 256, desiredSizes = WIN_STANDARD_ICO_SIZES) {
+ try {
+ const sourceBuffer = await fsExtra.readFile(sourcePath);
+ const entries = parseIcoBuffer(sourceBuffer);
+ const sourcePng = await pickLargestFrameAsPng(sourceBuffer, entries);
+ if (!sourcePng) {
+ return await writeIcoWithPreferredSize(sourcePath, outputPath, preferredSize);
+ }
+ const frames = await Promise.all(desiredSizes.map(async (size) => {
+ // Reuse an existing exact-size PNG frame when possible to keep any
+ // hand-tuned small icon (e.g. a 16x16 with deliberate pixel hinting).
+ const exact = entries.find((entry) => entry.width === size && entry.height === size);
+ if (exact && frameLooksLikePng(exact)) {
+ return { size, png: Buffer.from(exact.data) };
+ }
+ const png = await sharp(sourcePng)
+ .resize(size, size, {
+ fit: 'contain',
+ background: { r: 0, g: 0, b: 0, alpha: 0 },
+ })
+ .ensureAlpha()
+ .png()
+ .toBuffer();
+ return { size, png };
+ }));
+ // Order frames so the preferred size lands first (Windows shell uses the
+ // first-listed frame as a quality hint when choosing which to display).
+ frames.sort((a, b) => {
+ const aExact = a.size === preferredSize ? 0 : 1;
+ const bExact = b.size === preferredSize ? 0 : 1;
+ if (aExact !== bExact)
+ return aExact - bExact;
+ return b.size - a.size;
+ });
+ const icoBuffer = buildIcoFromPngBuffers(frames);
+ await fsExtra.ensureDir(path.dirname(outputPath));
+ await fsExtra.outputFile(outputPath, icoBuffer);
+ return true;
+ }
+ catch {
+ return await writeIcoWithPreferredSize(sourcePath, outputPath, preferredSize);
+ }
+}
/**
* Builds an ICO file from an array of PNG buffers using the PNG-in-ICO format
* (supported since Windows Vista). This preserves alpha transparency.
@@ -1658,7 +1775,7 @@ const ICON_CONFIG = {
},
};
const PLATFORM_CONFIG = {
- win: { format: '.ico', sizes: [16, 32, 48, 64, 128, 256] },
+ win: { format: '.ico', sizes: [...WIN_STANDARD_ICO_SIZES] },
linux: { format: '.png', size: 512 },
macos: { format: '.icns', sizes: [16, 32, 64, 128, 256, 512, 1024] },
};
@@ -1693,10 +1810,15 @@ async function copyWindowsIconIfNeeded(convertedPath, appName) {
try {
const finalIconPath = generateIconPath(appName);
await fsExtra.ensureDir(path.dirname(finalIconPath));
- // Reorder ICO to prioritize 256px icons for better Windows display
- const reordered = await writeIcoWithPreferredSize(convertedPath, finalIconPath, 256);
- if (!reordered) {
- await fsExtra.copy(convertedPath, finalIconPath);
+ // Re-render ICO so every Windows standard size is present and prefer the
+ // 256px frame as the leading entry; falls back to plain reordering if the
+ // ICO is non-decodable, then to a raw copy. (Issue #1190)
+ const upgraded = await ensureMultiResolutionIco(convertedPath, finalIconPath, 256);
+ if (!upgraded) {
+ const reordered = await writeIcoWithPreferredSize(convertedPath, finalIconPath, 256);
+ if (!reordered) {
+ await fsExtra.copy(convertedPath, finalIconPath);
+ }
}
return finalIconPath;
}
@@ -2153,6 +2275,28 @@ function normalizeUrl(urlToNormalize) {
}
}
+/**
+ * Error class used for user-facing CLI errors.
+ *
+ * The top-level catch in `bin/cli.ts` prints `message` directly without a
+ * stack trace and exits with code 1. Use this for predictable failures
+ * (invalid names, missing files, etc.) so users see a clean message instead
+ * of a Node.js stack dump.
+ */
+class PakeError extends Error {
+ constructor(message) {
+ super(message);
+ this.isUserError = true;
+ this.name = 'PakeError';
+ }
+}
+function isPakeError(error) {
+ return (error instanceof PakeError ||
+ (typeof error === 'object' &&
+ error !== null &&
+ error.isUserError === true));
+}
+
function resolveAppName(name, platform) {
const domain = getDomain(name) || 'pake';
return platform !== 'linux' ? capitalizeFirstLetter(domain) : domain;
@@ -2195,13 +2339,13 @@ async function handleOptions(options, url) {
const LINUX_NAME_ERROR = `✕ Name should only include lowercase letters, numbers, and dashes (not leading dashes). Examples: com-123-xxx, 123pan, pan123, weread, we-read, 123.`;
const DEFAULT_NAME_ERROR = `✕ Name should only include letters, numbers, dashes, and spaces (not leading dashes and spaces). Examples: 123pan, 123Pan, Pan123, weread, WeRead, WERead, we-read, We Read, 123.`;
const errorMsg = platform === 'linux' ? LINUX_NAME_ERROR : DEFAULT_NAME_ERROR;
- logger.error(errorMsg);
if (isActions) {
+ logger.error(errorMsg);
name = resolveAppName(url, platform);
logger.warn(`✼ Inside github actions, use the default name: ${name}`);
}
else {
- process.exit(1);
+ throw new PakeError(errorMsg);
}
}
const resolvedName = name || 'pake-app';
@@ -2459,21 +2603,46 @@ async function checkUpdateTips() {
});
}
program.action(async (url, options) => {
- await checkUpdateTips();
- if (!url) {
- program.help({
- error: false,
- });
- return;
+ try {
+ await checkUpdateTips();
+ if (!url) {
+ program.help({
+ error: false,
+ });
+ return;
+ }
+ log.setDefaultLevel('info');
+ log.setLevel('info');
+ if (options.debug) {
+ log.setLevel('debug');
+ }
+ const appOptions = await handleOptions(options, url);
+ const builder = BuilderProvider.create(appOptions);
+ await builder.prepare();
+ await builder.build(url);
+ }
+ catch (error) {
+ if (isPakeError(error)) {
+ console.error(chalk.red(error.message));
+ }
+ else if (error instanceof Error) {
+ console.error(chalk.red(`✕ ${error.message}`));
+ if (options?.debug && error.stack) {
+ console.error(chalk.gray(error.stack));
+ }
+ }
+ else {
+ console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));
+ }
+ process.exit(1);
+ }
+});
+program.parseAsync().catch((error) => {
+ if (error instanceof Error) {
+ console.error(chalk.red(`✕ ${error.message}`));
}
- log.setDefaultLevel('info');
- log.setLevel('info');
- if (options.debug) {
- log.setLevel('debug');
+ else {
+ console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));
}
- const appOptions = await handleOptions(options, url);
- const builder = BuilderProvider.create(appOptions);
- await builder.prepare();
- await builder.build(url);
+ process.exit(1);
});
-program.parse();
diff --git a/rollup.config.js b/rollup.config.js
index 8cc8cc3e..d5fa2b75 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -49,7 +49,7 @@ export default {
tsconfig: "./tsconfig.json",
sourceMap: !isProduction,
inlineSources: !isProduction,
- noEmitOnError: false,
+ noEmitOnError: isProduction,
compilerOptions: {
target: "es2020",
module: "esnext",
@@ -77,7 +77,6 @@ function pakeCliDevPlugin() {
let devHasStarted = false;
- // 智能检测包管理器
const detectPackageManager = () => {
if (fs.existsSync("pnpm-lock.yaml")) return "pnpm";
if (fs.existsSync("yarn.lock")) return "yarn";
diff --git a/tests/unit/__snapshots__/merge-window-options.test.ts.snap b/tests/unit/__snapshots__/merge-window-options.test.ts.snap
new file mode 100644
index 00000000..ca9f8e9d
--- /dev/null
+++ b/tests/unit/__snapshots__/merge-window-options.test.ts.snap
@@ -0,0 +1,85 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`buildWindowConfigOverrides > matches the default snapshot on Linux 1`] = `
+{
+ "activation_shortcut": "",
+ "always_on_top": false,
+ "dark_mode": false,
+ "disabled_web_shortcuts": false,
+ "enable_drag_drop": false,
+ "enable_wasm": false,
+ "force_internal_navigation": false,
+ "fullscreen": false,
+ "height": 780,
+ "hide_on_close": false,
+ "hide_title_bar": false,
+ "ignore_certificate_errors": false,
+ "incognito": false,
+ "internal_url_regex": "",
+ "maximize": false,
+ "min_height": 0,
+ "min_width": 0,
+ "new_window": false,
+ "resizable": true,
+ "start_to_tray": false,
+ "title": undefined,
+ "width": 1200,
+ "zoom": 100,
+}
+`;
+
+exports[`buildWindowConfigOverrides > matches the default snapshot on Windows 1`] = `
+{
+ "activation_shortcut": "",
+ "always_on_top": false,
+ "dark_mode": false,
+ "disabled_web_shortcuts": false,
+ "enable_drag_drop": false,
+ "enable_wasm": false,
+ "force_internal_navigation": false,
+ "fullscreen": false,
+ "height": 780,
+ "hide_on_close": false,
+ "hide_title_bar": false,
+ "ignore_certificate_errors": false,
+ "incognito": false,
+ "internal_url_regex": "",
+ "maximize": false,
+ "min_height": 0,
+ "min_width": 0,
+ "new_window": false,
+ "resizable": true,
+ "start_to_tray": false,
+ "title": undefined,
+ "width": 1200,
+ "zoom": 100,
+}
+`;
+
+exports[`buildWindowConfigOverrides > matches the default snapshot on macOS 1`] = `
+{
+ "activation_shortcut": "",
+ "always_on_top": false,
+ "dark_mode": false,
+ "disabled_web_shortcuts": false,
+ "enable_drag_drop": false,
+ "enable_wasm": false,
+ "force_internal_navigation": false,
+ "fullscreen": false,
+ "height": 780,
+ "hide_on_close": true,
+ "hide_title_bar": false,
+ "ignore_certificate_errors": false,
+ "incognito": false,
+ "internal_url_regex": "",
+ "maximize": false,
+ "min_height": 0,
+ "min_width": 0,
+ "new_window": false,
+ "resizable": true,
+ "start_to_tray": false,
+ "title": undefined,
+ "width": 1200,
+ "zoom": 100,
+}
+`;
diff --git a/tests/unit/base-builder.test.ts b/tests/unit/base-builder.test.ts
index 6f70a26b..bf9742fa 100644
--- a/tests/unit/base-builder.test.ts
+++ b/tests/unit/base-builder.test.ts
@@ -9,6 +9,11 @@ vi.mock('@/utils/dir', () => ({
}));
import BaseBuilder from '@/builders/BaseBuilder';
+import {
+ configureCargoRegistry,
+ getBuildEnvironment,
+ getInstallCommand,
+} from '@/builders/env';
import logger from '@/options/logger';
import { CN_MIRROR_ENV, isCnMirrorEnabled } from '@/utils/mirror';
@@ -65,16 +70,15 @@ describe('BaseBuilder guards', () => {
});
it('prepends /usr/bin to PATH for macOS build environment', () => {
- const builder = new TestBuilder({} as any);
const originalPath = process.env.PATH;
process.env.PATH = '/opt/homebrew/bin:/usr/local/bin';
try {
- const env = (builder as any).getBuildEnvironment();
+ const env = getBuildEnvironment();
if (process.platform === 'darwin') {
expect(env).toBeDefined();
- expect(env.PATH.startsWith('/usr/bin:')).toBe(true);
+ expect(env!.PATH.startsWith('/usr/bin:')).toBe(true);
} else {
expect(env).toBeUndefined();
}
@@ -83,38 +87,25 @@ describe('BaseBuilder guards', () => {
}
});
- it('skips copy when source and destination are the same path', async () => {
- const builder = new TestBuilder({} as any);
- const copySpy = vi
- .spyOn(fsExtra, 'copy')
- .mockResolvedValue(undefined as any);
-
- await expect(
- (builder as any).copyFileWithSamePathGuard('/tmp/same', '/tmp/same'),
- ).resolves.toBeUndefined();
- expect(copySpy).not.toHaveBeenCalled();
- });
-
- it('suppresses same-path fs-extra copy errors', async () => {
- const builder = new TestBuilder({} as any);
- vi.spyOn(fsExtra, 'copy').mockRejectedValue(
- new Error('Source and destination must not be the same.'),
+ it('skips Cargo registry copy when source and destination resolve to the same path', async () => {
+ // configureCargoRegistry uses a same-path guard internally; if the
+ // CN-mirror file and the project config end up identical we should not
+ // crash with "source and destination must not be the same".
+ const tempDir = await fsExtra.mkdtemp(
+ path.join(os.tmpdir(), 'pake-base-builder-same-'),
);
+ tempDirs.push(tempDir);
+ const tauriSrcPath = path.join(tempDir, 'src-tauri');
+ const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
+ const projectConf = path.join(tauriSrcPath, '.cargo', 'config.toml');
+ await fsExtra.outputFile(projectCnConf, GENERATED_MIRROR_CONFIG);
+ await fsExtra.outputFile(projectConf, GENERATED_MIRROR_CONFIG);
await expect(
- (builder as any).copyFileWithSamePathGuard('/tmp/a', '/tmp/b'),
+ configureCargoRegistry(tauriSrcPath, true),
).resolves.toBeUndefined();
});
- it('rethrows non-same-path copy errors', async () => {
- const builder = new TestBuilder({} as any);
- vi.spyOn(fsExtra, 'copy').mockRejectedValue(new Error('permission denied'));
-
- await expect(
- (builder as any).copyFileWithSamePathGuard('/tmp/a', '/tmp/b'),
- ).rejects.toThrow('permission denied');
- });
-
it('does not enable CN mirror by default', () => {
delete process.env[CN_MIRROR_ENV];
@@ -133,16 +124,14 @@ describe('BaseBuilder guards', () => {
);
it('uses official npm registry by default', () => {
- const builder = new TestBuilder({} as any);
- const command = (builder as any).getInstallCommand('pnpm', false);
+ const command = getInstallCommand('pnpm', false);
expect(command).toContain('pnpm install');
expect(command).not.toContain('registry.npmmirror.com');
});
it('uses npmmirror only when CN mirror is enabled', () => {
- const builder = new TestBuilder({} as any);
- const command = (builder as any).getInstallCommand('npm', true);
+ const command = getInstallCommand('npm', true);
expect(command).toContain(
'npm install --registry=https://registry.npmmirror.com --legacy-peer-deps',
@@ -150,11 +139,10 @@ describe('BaseBuilder guards', () => {
});
it('copies Cargo mirror config only when CN mirror is enabled', async () => {
- const builder = new TestBuilder({} as any);
const { tauriSrcPath, projectConf, projectCnConf } =
await createCargoFixture();
- await (builder as any).configureCargoRegistry(tauriSrcPath, true);
+ await configureCargoRegistry(tauriSrcPath, true);
expect(await fsExtra.readFile(projectConf, 'utf8')).toBe(
await fsExtra.readFile(projectCnConf, 'utf8'),
@@ -162,18 +150,16 @@ describe('BaseBuilder guards', () => {
});
it('removes generated Cargo mirror config when CN mirror is disabled', async () => {
- const builder = new TestBuilder({} as any);
const { tauriSrcPath, projectConf } = await createCargoFixture(
GENERATED_MIRROR_CONFIG,
);
- await (builder as any).configureCargoRegistry(tauriSrcPath, false);
+ await configureCargoRegistry(tauriSrcPath, false);
expect(await fsExtra.pathExists(projectConf)).toBe(false);
});
it('keeps custom Cargo config when CN mirror is disabled', async () => {
- const builder = new TestBuilder({} as any);
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});
const customConfig = `${GENERATED_MIRROR_CONFIG}
# custom user setting
@@ -181,11 +167,19 @@ describe('BaseBuilder guards', () => {
const { tauriSrcPath, projectConf } =
await createCargoFixture(customConfig);
- await (builder as any).configureCargoRegistry(tauriSrcPath, false);
+ await configureCargoRegistry(tauriSrcPath, false);
expect(await fsExtra.readFile(projectConf, 'utf8')).toBe(customConfig);
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('still references rsproxy.cn'),
);
});
+
+ it('keeps the BaseBuilder hierarchy intact', () => {
+ // Sanity check that subclasses can still construct against the slimmer
+ // BaseBuilder after env helpers were extracted.
+ const builder = new TestBuilder({} as any);
+ expect(builder).toBeInstanceOf(BaseBuilder);
+ expect(builder.getFileName()).toBe('test-app');
+ });
});
diff --git a/tests/unit/ico.test.ts b/tests/unit/ico.test.ts
index 318f0831..c473c415 100644
--- a/tests/unit/ico.test.ts
+++ b/tests/unit/ico.test.ts
@@ -2,8 +2,14 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { afterEach, describe, expect, it } from 'vitest';
+import sharp from 'sharp';
-import { buildIcoFromPngBuffers, writeIcoWithPreferredSize } from '@/utils/ico';
+import {
+ buildIcoFromPngBuffers,
+ ensureMultiResolutionIco,
+ writeIcoWithPreferredSize,
+ WIN_STANDARD_ICO_SIZES,
+} from '@/utils/ico';
const ICO_HEADER_SIZE = 6;
const ICO_DIR_ENTRY_SIZE = 16;
@@ -166,3 +172,90 @@ describe('writeIcoWithPreferredSize', () => {
expect(ok).toBe(false);
});
});
+
+describe('ensureMultiResolutionIco', () => {
+ async function realPng(size: number, fillColor = 'red'): Promise<Buffer> {
+ return sharp({
+ create: {
+ width: size,
+ height: size,
+ channels: 4,
+ background: fillColor,
+ },
+ })
+ .png()
+ .toBuffer();
+ }
+
+ it('expands a single-frame 256x256 ICO into every Windows standard size (#1190)', async () => {
+ const dir = makeTempDir();
+ const source = path.join(dir, 'source.ico');
+ const output = path.join(dir, 'multi.ico');
+
+ const big = await realPng(256, 'blue');
+ fs.writeFileSync(source, buildIcoFromPngBuffers([{ size: 256, png: big }]));
+
+ const ok = await ensureMultiResolutionIco(source, output);
+ expect(ok).toBe(true);
+
+ const entries = parseIcoHeader(fs.readFileSync(output));
+ const sizes = entries.map((entry) => Math.max(entry.width, entry.height));
+ for (const expected of WIN_STANDARD_ICO_SIZES) {
+ expect(sizes).toContain(expected);
+ }
+ });
+
+ it('places the preferred size as the first directory entry', async () => {
+ const dir = makeTempDir();
+ const source = path.join(dir, 'source.ico');
+ const output = path.join(dir, 'multi.ico');
+
+ const big = await realPng(256, 'green');
+ fs.writeFileSync(source, buildIcoFromPngBuffers([{ size: 256, png: big }]));
+
+ const ok = await ensureMultiResolutionIco(source, output, 32);
+ expect(ok).toBe(true);
+
+ const entries = parseIcoHeader(fs.readFileSync(output));
+ expect(entries[0].width).toBe(32);
+ expect(entries[0].height).toBe(32);
+ });
+
+ it('preserves any exact-size PNG frame already in the ICO', async () => {
+ const dir = makeTempDir();
+ const source = path.join(dir, 'source.ico');
+ const output = path.join(dir, 'multi.ico');
+
+ const tiny = await realPng(16, 'magenta');
+ const big = await realPng(256, 'cyan');
+ fs.writeFileSync(
+ source,
+ buildIcoFromPngBuffers([
+ { size: 16, png: tiny },
+ { size: 256, png: big },
+ ]),
+ );
+
+ const ok = await ensureMultiResolutionIco(source, output);
+ expect(ok).toBe(true);
+
+ const entries = parseIcoHeader(fs.readFileSync(output));
+ const sixteen = entries.find(
+ (entry) => entry.width === 16 && entry.height === 16,
+ );
+ expect(sixteen).toBeDefined();
+ expect(sixteen!.data.equals(tiny)).toBe(true);
+ });
+
+ it('falls back gracefully when the source ICO is malformed', async () => {
+ const dir = makeTempDir();
+ const source = path.join(dir, 'bad.ico');
+ fs.writeFileSync(source, Buffer.from([0, 0]));
+
+ const ok = await ensureMultiResolutionIco(
+ source,
+ path.join(dir, 'out.ico'),
+ );
+ expect(ok).toBe(false);
+ });
+});
diff --git a/tests/unit/merge-window-options.test.ts b/tests/unit/merge-window-options.test.ts
new file mode 100644
index 00000000..2e2f98cd
--- /dev/null
+++ b/tests/unit/merge-window-options.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest';
+import { buildWindowConfigOverrides } from '../../bin/helpers/merge';
+import { DEFAULT_PAKE_OPTIONS } from '../../bin/defaults';
+import type { PakeAppOptions } from '../../bin/types';
+
+function makeOptions(overrides: Partial<PakeAppOptions> = {}): PakeAppOptions {
+ return {
+ ...DEFAULT_PAKE_OPTIONS,
+ identifier: 'com.pake.test',
+ ...overrides,
+ };
+}
+
+describe('buildWindowConfigOverrides', () => {
+ it('matches the default snapshot on macOS', () => {
+ const result = buildWindowConfigOverrides(makeOptions(), 'darwin');
+ expect(result).toMatchSnapshot();
+ });
+
+ it('matches the default snapshot on Windows', () => {
+ const result = buildWindowConfigOverrides(makeOptions(), 'win32');
+ expect(result).toMatchSnapshot();
+ });
+
+ it('matches the default snapshot on Linux', () => {
+ const result = buildWindowConfigOverrides(makeOptions(), 'linux');
+ expect(result).toMatchSnapshot();
+ });
+
+ it('respects explicit hideOnClose=false on macOS', () => {
+ const result = buildWindowConfigOverrides(
+ makeOptions({ hideOnClose: false }),
+ 'darwin',
+ );
+ expect(result.hide_on_close).toBe(false);
+ });
+
+ it('defaults hideOnClose to true on macOS when undefined', () => {
+ const result = buildWindowConfigOverrides(
+ makeOptions({ hideOnClose: undefined }),
+ 'darwin',
+ );
+ expect(result.hide_on_close).toBe(true);
+ });
+
+ it('defaults hideOnClose to false on Linux/Windows when undefined', () => {
+ expect(
+ buildWindowConfigOverrides(
+ makeOptions({ hideOnClose: undefined }),
+ 'linux',
+ ).hide_on_close,
+ ).toBe(false);
+ expect(
+ buildWindowConfigOverrides(
+ makeOptions({ hideOnClose: undefined }),
+ 'win32',
+ ).hide_on_close,
+ ).toBe(false);
+ });
+
+ it('only enables start_to_tray when both flag and tray are on', () => {
+ expect(
+ buildWindowConfigOverrides(
+ makeOptions({ startToTray: true, showSystemTray: false }),
+ 'darwin',
+ ).start_to_tray,
+ ).toBe(false);
+ expect(
+ buildWindowConfigOverrides(
+ makeOptions({ startToTray: true, showSystemTray: true }),
+ 'darwin',
+ ).start_to_tray,
+ ).toBe(true);
+ });
+
+ it('forwards window/zoom/wasm/new_window flags verbatim', () => {
+ const result = buildWindowConfigOverrides(
+ makeOptions({
+ width: 1400,
+ height: 900,
+ zoom: 120,
+ minWidth: 800,
+ minHeight: 600,
+ wasm: true,
+ enableDragDrop: true,
+ ignoreCertificateErrors: true,
+ newWindow: true,
+ forceInternalNavigation: true,
+ internalUrlRegex: '^https://example\\.com',
+ }),
+ 'darwin',
+ );
+ expect(result).toMatchObject({
+ width: 1400,
+ height: 900,
+ zoom: 120,
+ min_width: 800,
+ min_height: 600,
+ enable_wasm: true,
+ enable_drag_drop: true,
+ ignore_certificate_errors: true,
+ new_window: true,
+ force_internal_navigation: true,
+ internal_url_regex: '^https://example\\.com',
+ });
+ });
+});