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.

perf: streamline packaging and prepare V3.16.3

Tw93110fbc2934e0
diff --git a/.github/workflows/quality-and-test.yml b/.github/workflows/quality-and-test.yml
index 7df7c0bc..ff25e156 100644
--- a/.github/workflows/quality-and-test.yml
+++ b/.github/workflows/quality-and-test.yml
@@ -168,10 +168,39 @@ jobs:
CI: true
NODE_ENV: test
+ docker-validation:
+ name: Docker Build and Packaging
+ timeout-minutes: 30
+ if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ - uses: docker/setup-buildx-action@v3
+ - name: Build validation image
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ load: true
+ tags: pake-validation:local
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ - name: Verify CLI and Linux installers
+ shell: bash
+ run: |
+ set -euo pipefail
+ docker run --rm pake-validation:local --version
+ mkdir -p "$RUNNER_TEMP/pake-docker-output"
+ docker run --rm --privileged --device /dev/fuse \
+ -v "$RUNNER_TEMP/pake-docker-output:/output" \
+ pake-validation:local https://example.com --name dockersmoke \
+ --icon /pake/src-tauri/icons/icon.png --targets deb,appimage --json
+ test -s "$RUNNER_TEMP/pake-docker-output/dockersmoke.deb"
+ test -s "$RUNNER_TEMP/pake-docker-output/dockersmoke.AppImage"
+
summary:
name: Quality Summary
runs-on: ubuntu-latest
- needs: [auto-format, rust-quality, validation-fast, validation-full]
+ needs: [auto-format, rust-quality, validation-fast, validation-full, docker-validation]
if: always()
steps:
- name: Generate Summary
@@ -185,4 +214,5 @@ jobs:
echo "| Rust Quality | ${{ needs.rust-quality.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' }} |"
+ echo "| Docker Packaging | ${{ needs.docker-validation.result == 'success' && 'PASSED' || needs.docker-validation.result == 'skipped' && 'SKIPPED (PR fast lane)' || 'FAILED' }} |"
} >> $GITHUB_STEP_SUMMARY
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 80df602d..2ac46bf1 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -130,7 +130,7 @@ jobs:
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
- type=raw,value=latest,enable={{is_default_branch}}
+ type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/V') || github.ref == 'refs/heads/main' }}
type=ref,event=tag
type=sha
diff --git a/.github/workflows/single-app.yaml b/.github/workflows/single-app.yaml
index a3b0c5e6..5c6f2018 100644
--- a/.github/workflows/single-app.yaml
+++ b/.github/workflows/single-app.yaml
@@ -124,11 +124,6 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v6
- - name: Install Rust
- uses: dtolnay/rust-toolchain@stable
- with:
- toolchain: ${{ matrix.rust }}
-
- name: Setup Node.js Environment
uses: ./.github/actions/setup-env
with:
@@ -221,7 +216,7 @@ jobs:
ARGS+=("--width" "${{ inputs.width }}")
ARGS+=("--height" "${{ inputs.height }}")
- # Build once with multiple targets (faster than separate builds)
+ # Compile once, then bundle each requested format independently.
node dist/cli.js "${ARGS[@]}" --targets deb,appimage
mkdir -p output/linux
diff --git a/AGENTS.md b/AGENTS.md
index 80ca7586..6edf2498 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -95,6 +95,9 @@ Proactive latent-bug sweeps use `.agents/skills/bugs/SKILL.md`. Pick one row and
- CLI options are user-facing and must stay synchronized across `bin/helpers/cli-program.ts`, `bin/types.ts`, `bin/defaults.ts`, `bin/helpers/merge.ts`, generated `dist/cli.js`, `schema/pake.schema.json`, and `docs/cli-usage*.md`. Schema-to-CLI sync is enforced by `tests/unit/config-file.test.ts`; the rest is manual discipline.
- The `--json` machine contract is public API for agents: stdout carries exactly one JSON result (nothing else may write to stdout in machine mode), and the exit codes (0/2/3/4/1) plus error codes (`INVALID_INPUT`, `ENV_MISSING`, `BUILD_FAILED`, `UNEXPECTED`, plus `NETWORK` which is reserved and currently unused, since network failures report under the phase code) must stay stable. `logger.warn` feeds the JSON `warnings` array, so warn is for real warnings only, not status lines. Owners: `bin/utils/output.ts`, `bin/cli.ts`, `bin/utils/shell.ts`.
- Packaging CLI builds use a private temporary workspace for configs, injected code, icons, entitlements, and local content. The installed package is the template, not a writable staging area. Complete installed Tauri dependencies are reused without reinstalling; incomplete dependencies are installed only in the private workspace. Owners: `bin/utils/build-workspace.ts`, `bin/utils/dir.ts`, and `bin/helpers/merge.ts`. `restoreLocalTree()` at CLI startup remains only to recover a `dist_bak` left by the published 3.15.7 implementation. The repository's `bin/dev.ts` intentionally retains source-based Tauri development/watch behavior.
+- Linux multi-format builds compile once with `--no-bundle`, then use `tauri bundle` for each format with the same config, features, target, and debug profile. Keep per-format failure isolation and AppImage `NO_STRIP` retries on bundling only. Single-format builds retain the combined build path.
+- Build preparation uses private workspaces before acquiring the shared compilation cache lock. Cancellation while waiting must clean only that workspace and leave the active owner's lock intact.
+- Native build gates use a fresh output directory, require exit code zero and the CLI JSON's exact output path, and verify macOS executable architectures from `CFBundleExecutable`. Old bundles, empty directories, or timeout artifacts never prove a successful build.
- Shared Cargo caches are locked until artifact copying finishes; Cargo's own compilation lock alone does not protect that interval. Never reclaim a stale PID lock with read-then-delete, which can delete a new owner's lock. An abandoned lock fails with a recovery hint rather than risking concurrent artifacts. Cancellation and failed subprocesses must stop the compiler tree before releasing the lock; preserve the workspace and lock if termination cannot be confirmed. Ordinary success and failure discard the workspace, with cleanup warnings included before the JSON result. Verify with `node tests/integration/build-workspace.mjs` on macOS and the cross-platform workspace unit tests.
- Build workspaces preserve an existing root `rust-toolchain.toml` or legacy `rust-toolchain`; otherwise rustup may select a different default without the installed cross-compilation targets. Keep full stderr in real-build tests so compilation success cannot conceal a later target or bundling failure.
- New user-visible CLI surface (a new flag, alias, subcommand, or extra help variant) needs a stated justification before implementation: name the user problem and why an existing flag, config key, or default cannot cover it, then get maintainer sign-off. Prefer quieter defaults over new options; never split help output into parallel variants.
@@ -113,6 +116,7 @@ Proactive latent-bug sweeps use `.agents/skills/bugs/SKILL.md`. Pick one row and
- Notification flows cross injected JS, Tauri invokes, capabilities, and native notification plugins. Verify the Rust capability and JS caller together.
- WebKit compositing behavior is platform-sensitive on Linux/Wayland. Runtime flag decisions live in `src-tauri/src/lib.rs`; keep the default conservative, cover compositor exceptions with unit tests, and document user-facing fallbacks in `docs/faq*.md`.
- Linux AppImage reports often include harmless GTK, appindicator, or GStreamer warnings. Separate optional runtime warnings from the actual symptom before changing code; input/click failures on pure Wayland compositors are not the same class as blank-window failures.
+- Stable `V*` Docker publication updates both the version tag and `latest`; checking only the version tag does not prove the documented default Docker command receives the new image. Quality validates the actual image CLI and both DEB/AppImage artifacts before a release tag is pushed.
- Release state can be split. npm Trusted Publishing can succeed before the popular-app release workflow finishes, and GitHub Release assets can exist while a workflow run still shows queued or in progress. Report each surface explicitly.
- Local app builds and test runs mutate tracked files as build state: `src-tauri/pake.json`, `src-tauri/tauri.conf.json`, `src-tauri/tauri.macos.conf.json`, and regenerated icons under `src-tauri/png/` and `src-tauri/icons/`. Record `git status --short` for these paths before running the command. Afterwards, restore only paths that were clean in that baseline and whose new diff is provably generated by this run. If a path was already dirty or ownership is ambiguous, leave it untouched and rerun verification in an isolated worktree; never let a feature or release commit absorb this churn.
- Per-app optional fields in `default_app_list.json` currently take their defaults in Actions expressions in `release.yml` (`matrix.config.x || false` and the numeric ones), which works because every field so far is default-false or numeric. The first default-true field cannot use that path and must move its default into the jq read step: GitHub expressions cast both `null` and `false` to `0`, so `matrix.config.x != false` cannot express "default true" and would silently flip every app missing the field.
diff --git a/Dockerfile b/Dockerfile
index b6496133..773fc197 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1.4
# Cargo build stage - Updated to latest Rust for edition2024 support
-FROM rust:latest AS cargo-builder
+FROM rust:latest AS base
# Update Rust to ensure we have the latest version with edition2024 support
RUN rustup update stable && rustup default stable
@@ -24,6 +24,8 @@ ENV PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/share/pkgconfig:/usr/lib/x86_64-linu
# Verify Rust version
RUN rustc --version && echo "Rust version verified"
+# Share the system toolchain layer between compilation and the final image.
+FROM base AS cargo-builder
COPY . /pake
WORKDIR /pake/src-tauri
# Build cargo packages and store cache
@@ -38,34 +40,20 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \
RUN ls -la /cargo-cache/registry && ls -la /cargo-cache/git && rm -rfd /cargo-cache/registry/src
# Main build stage
-FROM rust:latest AS builder
+FROM node:22-bookworm AS node-runtime
-# Update Rust to ensure we have the latest version with edition2024 support
-RUN rustup update stable && rustup default stable
-
-# Install Rust dependencies
-RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
- rm -f /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/cache/apt/archives/lock && \
- apt-get update && apt-get install -y --no-install-recommends \
- libdbus-1-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev \
- libwebkit2gtk-4.1-dev build-essential curl wget file libxdo-dev libssl-dev \
- libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev \
- gnome-video-effects && \
- apt-get clean && rm -rf /var/lib/apt/lists/*
-
-# Set PKG_CONFIG_PATH for GLib detection
-ENV PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/share/pkgconfig:/usr/lib/x86_64-linux-gnu/pkgconfig
-
-# Verify Rust version in builder stage
-RUN rustc --version && echo "Builder stage Rust version verified"
+FROM base AS builder
+COPY --from=node-runtime /usr/local/bin/node /usr/local/bin/node
+COPY --from=node-runtime /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/npm
+RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
+ ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx && \
+ npm install -g [email protected]
-# Install Node.js 22.x and pnpm
-RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
- rm -f /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/cache/apt/archives/lock && \
- curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
- apt-get update && apt-get install -y nodejs && \
- npm install -g pnpm && \
- apt-get clean && rm -rf /var/lib/apt/lists/*
+# Install Node dependencies before copying frequently changing app sources.
+WORKDIR /pake
+COPY package.json pnpm-lock.yaml ./
+RUN --mount=type=cache,target=/root/.local/share/pnpm \
+ pnpm install --frozen-lockfile
# Copy project files
COPY . /pake
@@ -77,9 +65,7 @@ COPY --from=cargo-builder /cargo-cache/git /usr/local/cargo/git
COPY --from=cargo-builder /cargo-cache/registry /usr/local/cargo/registry
# Install dependencies and build pake-cli
-RUN --mount=type=cache,target=/root/.local/share/pnpm \
- pnpm install --frozen-lockfile && \
- pnpm run cli:build
+RUN pnpm run cli:build
# Set up the entrypoint
WORKDIR /output
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.ts
index 771ea5cc..5495f905 100644
--- a/bin/builders/BaseBuilder.ts
+++ b/bin/builders/BaseBuilder.ts
@@ -245,11 +245,19 @@ export default abstract class BaseBuilder {
}
async buildAndCopy(url: string, target: string, logSuccess = true) {
- const { name = 'pake-app' } = this.options;
- await mergeConfig(url, this.options, structuredClone(tauriConfig));
+ await this.prepareBuild(url);
+ await this.runBuildCommand(
+ this.getBuildCommand(await detectPackageManager()),
+ target,
+ );
+ await this.copyBuildArtifacts(target, logSuccess);
+ }
- const packageManager = await detectPackageManager();
+ protected async prepareBuild(url: string) {
+ await mergeConfig(url, this.options, structuredClone(tauriConfig));
+ }
+ protected async runBuildCommand(buildCommand: ShellCommand, target: string) {
// Build app
const buildSpinner = getSpinner('Building app...');
buildSpinner.stop();
@@ -277,7 +285,6 @@ export default abstract class BaseBuilder {
);
}
- const buildCommand = this.getBuildCommand(packageManager);
const buildTimeout = getBuildTimeout();
try {
@@ -307,7 +314,10 @@ export default abstract class BaseBuilder {
throw retryError;
}
}
+ }
+ protected async copyBuildArtifacts(target: string, logSuccess = true) {
+ const { name = 'pake-app' } = this.options;
// With --no-bundle there is no installer to copy; surface the raw
// executable the build produced instead.
if (this.options.bundle === false) {
diff --git a/bin/builders/LinuxBuilder.ts b/bin/builders/LinuxBuilder.ts
index 9ec09f21..b13de7fc 100644
--- a/bin/builders/LinuxBuilder.ts
+++ b/bin/builders/LinuxBuilder.ts
@@ -12,11 +12,13 @@ import {
needsTemporaryDebForZst,
} from '@/utils/targets';
import logger from '@/options/logger';
+import { detectPackageManager } from './env';
export default class LinuxBuilder extends BaseBuilder {
private buildFormat: string;
private buildArch: string;
private currentBuildType: string = '';
+ private compiled = false;
constructor(options: PakeAppOptions) {
super(options);
@@ -61,6 +63,8 @@ export default class LinuxBuilder extends BaseBuilder {
}
async build(url: string) {
+ this.compiled = false;
+ this.currentBuildType = '';
// --no-bundle: build the executable once with no per-format packaging loop.
if (this.options.bundle === false) {
await this.buildAndCopy(url, 'deb');
@@ -75,6 +79,14 @@ export default class LinuxBuilder extends BaseBuilder {
}
const useTemporaryDebForZst = needsTemporaryDebForZst(targets);
+ if (targets.length > 1) {
+ await this.prepareBuild(url);
+ const command = this.getBuildCommand(await detectPackageManager());
+ command.args.push('--no-bundle');
+ await this.runBuildCommand(command, 'compile');
+ this.compiled = true;
+ }
+
// With a single explicit target, fail fast. With multiple targets (the
// distro-aware default, or an explicit comma list) keep building the rest
// when one fails, so a usable installer is still produced, e.g. AppImage
@@ -270,7 +282,31 @@ post_remove() {
// Override buildAndCopy to ensure currentBuildType is synced if called directly, though the loop above handles it most of the time.
async buildAndCopy(url: string, target: string, logSuccess = true) {
this.currentBuildType = target;
- await super.buildAndCopy(url, target, logSuccess);
+ if (!this.compiled) {
+ await super.buildAndCopy(url, target, logSuccess);
+ return;
+ }
+ const packageManager = await detectPackageManager();
+ const args = ['run', 'tauri'];
+ if (packageManager === 'npm') args.push('--');
+ args.push(
+ 'bundle',
+ '--config',
+ path.join('src-tauri', '.pake', 'tauri.conf.json'),
+ );
+ args.push(
+ '--bundles',
+ target,
+ '--features',
+ this.getBuildFeatures().join(','),
+ );
+ if (this.options.debug) args.push('--debug');
+ if (this.options.debug || target === 'appimage' || process.env.PAKE_VERBOSE)
+ args.push('--verbose');
+ if (this.buildArch === 'arm64')
+ args.push('--target', this.getTauriTarget('arm64', 'linux')!);
+ await this.runBuildCommand({ executable: packageManager, args }, target);
+ await this.copyBuildArtifacts(target, logSuccess);
}
protected getBuildCommand(packageManager: string = 'pnpm'): ShellCommand {
diff --git a/bin/cli.ts b/bin/cli.ts
index 8edd68b2..685d62cf 100644
--- a/bin/cli.ts
+++ b/bin/cli.ts
@@ -150,7 +150,8 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {
endCancellation = beginBuildCancellation();
phase = 'prepare';
- leaveWorkspace = await enterBuildWorkspace();
+ const workspace = await enterBuildWorkspace();
+ leaveWorkspace = workspace;
phase = 'input';
const appOptions = await handleInputOptions(options, url);
throwIfBuildCancelled();
@@ -161,6 +162,8 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {
await builder.prepare();
throwIfBuildCancelled();
phase = 'build';
+ await workspace.lockCache();
+ throwIfBuildCancelled();
await builder.build(url);
throwIfBuildCancelled();
diff --git a/bin/utils/build-workspace.ts b/bin/utils/build-workspace.ts
index bd0781e4..598667f3 100644
--- a/bin/utils/build-workspace.ts
+++ b/bin/utils/build-workspace.ts
@@ -153,20 +153,14 @@ export async function acquireBuildCache(
}
}
-export async function enterBuildWorkspace(): Promise<() => Promise<void>> {
+export async function enterBuildWorkspace() {
const previousTarget = process.env.CARGO_TARGET_DIR;
const targetDirectory = path.resolve(
packageDirectory,
previousTarget || 'src-tauri/target',
);
- const release = await acquireBuildCache(targetDirectory);
- let directory: string;
- try {
- directory = await createBuildWorkspace(packageDirectory);
- } catch (error) {
- await release();
- throw error;
- }
+ const directory = await createBuildWorkspace(packageDirectory);
+ let release: (() => Promise<void>) | undefined;
setBuildDirectory(directory);
process.env.CARGO_TARGET_DIR = targetDirectory;
const leave = async () => {
@@ -187,7 +181,7 @@ export async function enterBuildWorkspace(): Promise<() => Promise<void>> {
);
} finally {
try {
- await release();
+ await release?.();
} catch (error) {
logger.warn(
`Could not release the compilation cache lock: ${String(error)}`,
@@ -199,5 +193,9 @@ export async function enterBuildWorkspace(): Promise<() => Promise<void>> {
await leave();
throwIfBuildCancelled();
}
- return leave;
+ return Object.assign(leave, {
+ async lockCache() {
+ release = await acquireBuildCache(targetDirectory);
+ },
+ });
}
diff --git a/dist/cli.js b/dist/cli.js
index 3e2eef85..7aa015e1 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -19,7 +19,7 @@ import * as psl from 'psl';
import { InvalidArgumentError, program as program$1, Option } from 'commander';
var name = "pake-cli";
-var version = "3.16.2";
+var version = "3.16.3";
var description = "🤱🏻 Turn any webpage into a desktop app with one command. 🤱🏻 一键打包网页生成轻量桌面应用。";
var engines = {
node: ">=20.9.0"
@@ -538,15 +538,8 @@ async function acquireBuildCache(targetDirectory) {
async function enterBuildWorkspace() {
const previousTarget = process.env.CARGO_TARGET_DIR;
const targetDirectory = path.resolve(packageDirectory, previousTarget || 'src-tauri/target');
- const release = await acquireBuildCache(targetDirectory);
- let directory;
- try {
- directory = await createBuildWorkspace(packageDirectory);
- }
- catch (error) {
- await release();
- throw error;
- }
+ const directory = await createBuildWorkspace(packageDirectory);
+ let release;
setBuildDirectory(directory);
process.env.CARGO_TARGET_DIR = targetDirectory;
const leave = async () => {
@@ -567,7 +560,7 @@ async function enterBuildWorkspace() {
}
finally {
try {
- await release();
+ await release?.();
}
catch (error) {
logger.warn(`Could not release the compilation cache lock: ${String(error)}`);
@@ -578,7 +571,11 @@ async function enterBuildWorkspace() {
await leave();
throwIfBuildCancelled();
}
- return leave;
+ return Object.assign(leave, {
+ async lockCache() {
+ release = await acquireBuildCache(targetDirectory);
+ },
+ });
}
async function terminateBuildTree(pid) {
@@ -1663,9 +1660,14 @@ class BaseBuilder {
await shellExec({ executable: packageManager, args });
}
async buildAndCopy(url, target, logSuccess = true) {
- const { name = 'pake-app' } = this.options;
+ await this.prepareBuild(url);
+ await this.runBuildCommand(this.getBuildCommand(await detectPackageManager()), target);
+ await this.copyBuildArtifacts(target, logSuccess);
+ }
+ async prepareBuild(url) {
await mergeConfig(url, this.options, structuredClone(tauriConfig));
- const packageManager = await detectPackageManager();
+ }
+ async runBuildCommand(buildCommand, target) {
// Build app
const buildSpinner = getSpinner('Building app...');
buildSpinner.stop();
@@ -1684,7 +1686,6 @@ class BaseBuilder {
if (isLinuxAppImage && !buildEnv.NO_STRIP && this.options.debug) {
logger.warn('⚠ AppImage strip step can fail on glibc 2.38+; Pake will auto-retry with NO_STRIP=1.');
}
- const buildCommand = this.getBuildCommand(packageManager);
const buildTimeout = getBuildTimeout();
try {
await shellExec(buildCommand, buildTimeout, resolveExecEnv());
@@ -1711,6 +1712,9 @@ class BaseBuilder {
throw retryError;
}
}
+ }
+ async copyBuildArtifacts(target, logSuccess = true) {
+ const { name = 'pake-app' } = this.options;
// With --no-bundle there is no installer to copy; surface the raw
// executable the build produced instead.
if (this.options.bundle === false) {
@@ -2083,6 +2087,7 @@ class LinuxBuilder extends BaseBuilder {
constructor(options) {
super(options);
this.currentBuildType = '';
+ this.compiled = false;
const target = options.targets || 'deb';
if (target.includes('-arm64')) {
this.buildFormat = target.replace('-arm64', '');
@@ -2118,6 +2123,8 @@ class LinuxBuilder extends BaseBuilder {
return `${name}_${version}_${arch}`;
}
async build(url) {
+ this.compiled = false;
+ this.currentBuildType = '';
// --no-bundle: build the executable once with no per-format packaging loop.
if (this.options.bundle === false) {
await this.buildAndCopy(url, 'deb');
@@ -2128,6 +2135,13 @@ class LinuxBuilder extends BaseBuilder {
throw new Error(`No valid Linux target in "${this.options.targets}". Valid targets: ${LINUX_TARGET_TYPES.join(', ')}.`);
}
const useTemporaryDebForZst = needsTemporaryDebForZst(targets);
+ if (targets.length > 1) {
+ await this.prepareBuild(url);
+ const command = this.getBuildCommand(await detectPackageManager());
+ command.args.push('--no-bundle');
+ await this.runBuildCommand(command, 'compile');
+ this.compiled = true;
+ }
// With a single explicit target, fail fast. With multiple targets (the
// distro-aware default, or an explicit comma list) keep building the rest
// when one fails, so a usable installer is still produced, e.g. AppImage
@@ -2293,7 +2307,24 @@ post_remove() {
// Override buildAndCopy to ensure currentBuildType is synced if called directly, though the loop above handles it most of the time.
async buildAndCopy(url, target, logSuccess = true) {
this.currentBuildType = target;
- await super.buildAndCopy(url, target, logSuccess);
+ if (!this.compiled) {
+ await super.buildAndCopy(url, target, logSuccess);
+ return;
+ }
+ const packageManager = await detectPackageManager();
+ const args = ['run', 'tauri'];
+ if (packageManager === 'npm')
+ args.push('--');
+ args.push('bundle', '--config', path.join('src-tauri', '.pake', 'tauri.conf.json'));
+ args.push('--bundles', target, '--features', this.getBuildFeatures().join(','));
+ if (this.options.debug)
+ args.push('--debug');
+ if (this.options.debug || target === 'appimage' || process.env.PAKE_VERBOSE)
+ args.push('--verbose');
+ if (this.buildArch === 'arm64')
+ args.push('--target', this.getTauriTarget('arm64', 'linux'));
+ await this.runBuildCommand({ executable: packageManager, args }, target);
+ await this.copyBuildArtifacts(target, logSuccess);
}
getBuildCommand(packageManager = 'pnpm') {
const configPath = path.join('src-tauri', '.pake', 'tauri.conf.json');
@@ -3847,7 +3878,8 @@ program.action(async (urlArg, options) => {
}
endCancellation = beginBuildCancellation();
phase = 'prepare';
- leaveWorkspace = await enterBuildWorkspace();
+ const workspace = await enterBuildWorkspace();
+ leaveWorkspace = workspace;
phase = 'input';
const appOptions = await handleOptions(options, url);
throwIfBuildCancelled();
@@ -3857,6 +3889,8 @@ program.action(async (urlArg, options) => {
await builder.prepare();
throwIfBuildCancelled();
phase = 'build';
+ await workspace.lockCache();
+ throwIfBuildCancelled();
await builder.build(url);
throwIfBuildCancelled();
await leaveWorkspace();
diff --git a/package.json b/package.json
index 3e759f26..6f872295 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pake-cli",
- "version": "3.16.2",
+ "version": "3.16.3",
"description": "🤱🏻 Turn any webpage into a desktop app with one command. 🤱🏻 一键打包网页生成轻量桌面应用。",
"engines": {
"node": ">=20.9.0"
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index abfc9047..6f321d7f 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2564,7 +2564,7 @@ dependencies = [
[[package]]
name = "pake"
-version = "3.16.2"
+version = "3.16.3"
dependencies = [
"block2",
"dispatch",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 955784be..3451e247 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pake"
-version = "3.16.2"
+version = "3.16.3"
description = "🤱🏻 Turn any webpage into a desktop app with Rust."
authors = ["Tw93"]
license = "GPL-3.0-or-later"
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 096e3978..a783e814 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"productName": "Weekly",
"identifier": "com.pake.weekly",
- "version": "3.16.2",
+ "version": "3.16.3",
"app": {
"withGlobalTauri": true,
"trayIcon": {
diff --git a/tests/integration/build-workspace.mjs b/tests/integration/build-workspace.mjs
index 32100db7..078d6f4e 100644
--- a/tests/integration/build-workspace.mjs
+++ b/tests/integration/build-workspace.mjs
@@ -108,7 +108,19 @@ try {
timeout: 30_000,
},
);
- if (signal) {
+ if (signal === "WAIT") {
+ running.catch(() => {});
+ let waiting = false;
+ running.child.stderr.on("data", (data) => {
+ if (data.toString().includes("Waiting for another Pake build"))
+ waiting = true;
+ });
+ const deadline = Date.now() + 10000;
+ while (!waiting && Date.now() < deadline)
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ assert.ok(waiting, "CLI did not reach cache wait");
+ running.child.kill("SIGINT");
+ } else if (signal) {
running.catch(() => {});
const ready = path.join(root, name + "-ready.json");
const started = Date.now();
@@ -136,6 +148,22 @@ try {
}
return running;
}
+ await fs.mkdir(cache, { recursive: true });
+ const ownedLock = path.join(cache, ".pake-build.lock");
+ await fs.writeFile(ownedLock, String(process.pid));
+ try {
+ await assert.rejects(build("Waiting", "WAIT"), (error) => {
+ assert.equal(JSON.parse(error.stdout).error.code, "BUILD_FAILED");
+ return true;
+ });
+ assert.equal(
+ await fs.readFile(ownedLock, "utf8"),
+ String(process.pid),
+ "A cancelled waiter must not remove the owner's lock",
+ );
+ } finally {
+ await fs.unlink(ownedLock);
+ }
const outcomes = await Promise.all([build("Alpha"), build("Beta")]);
for (const [index, name] of ["Alpha", "Beta"].entries()) {
const result = JSON.parse(outcomes[index].stdout);
diff --git a/tests/unit/build-workspace.test.ts b/tests/unit/build-workspace.test.ts
index bcb5850e..90086c1a 100644
--- a/tests/unit/build-workspace.test.ts
+++ b/tests/unit/build-workspace.test.ts
@@ -1,7 +1,11 @@
import fs from 'fs-extra';
import path from 'path';
import os from 'os';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+vi.mock('@/utils/dir', () => ({
+ packageDirectory: process.cwd(),
+ setBuildDirectory: vi.fn(),
+}));
import {
createBuildWorkspace,
acquireBuildCache,
@@ -193,3 +197,35 @@ describe('build workspace', () => {
expect(await fs.readFile(lock, 'utf8')).toBe(owner);
});
});
+
+it('prepares private inputs without taking a busy compilation cache and leaves its owner intact', async () => {
+ const { enterBuildWorkspace } = await import('@/utils/build-workspace');
+ const source = await fixture();
+ const target = path.join(source, 'cache');
+ const original = process.env.CARGO_TARGET_DIR;
+ process.env.CARGO_TARGET_DIR = target;
+ const release = await acquireBuildCache(target);
+ const pending = enterBuildWorkspace();
+ let timer: ReturnType<typeof setTimeout>;
+ try {
+ const workspace = await Promise.race([
+ pending,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('Preparation blocked by compilation lock')),
+ 2000,
+ );
+ }),
+ ]);
+ await workspace();
+ expect(
+ await fs.readFile(path.join(target, '.pake-build.lock'), 'utf8'),
+ ).toBe(String(process.pid));
+ } finally {
+ clearTimeout(timer!);
+ await release();
+ await pending.then((workspace) => workspace());
+ if (original === undefined) delete process.env.CARGO_TARGET_DIR;
+ else process.env.CARGO_TARGET_DIR = original;
+ }
+});
diff --git a/tests/unit/linux-multi-target.test.ts b/tests/unit/linux-multi-target.test.ts
new file mode 100644
index 00000000..d5b896ec
--- /dev/null
+++ b/tests/unit/linux-multi-target.test.ts
@@ -0,0 +1,109 @@
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('@/utils/dir', () => ({
+ npmDirectory: process.cwd(),
+ tauriConfigDirectory: path.join(process.cwd(), 'src-tauri', '.pake'),
+}));
+vi.mock('@/utils/shell', () => ({ shellExec: vi.fn() }));
+vi.mock('@/utils/platform', () => ({
+ IS_MAC: false,
+ IS_WIN: false,
+ IS_LINUX: true,
+}));
+vi.mock('@/builders/env', async (original) => ({
+ ...(await original<object>()),
+ detectPackageManager: vi.fn(async () => 'pnpm'),
+ getBuildEnvironment: () => undefined,
+}));
+import LinuxBuilder from '@/builders/LinuxBuilder';
+import { shellExec } from '@/utils/shell';
+import { DEFAULT_PAKE_OPTIONS } from '@/defaults';
+const realProcess = process;
+beforeEach(() => {
+ vi.stubGlobal('process', { ...realProcess, platform: 'linux' });
+ vi.mocked(shellExec).mockReset().mockResolvedValue(0);
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+function fixture(targets = 'deb,appimage', debug = false) {
+ const b = new LinuxBuilder({
+ ...DEFAULT_PAKE_OPTIONS,
+ name: 'Demo',
+ targets,
+ debug,
+ } as any);
+ const prepare = vi
+ .spyOn(b as any, 'prepareBuild')
+ .mockResolvedValue(undefined);
+ const copy = vi
+ .spyOn(b as any, 'copyBuildArtifacts')
+ .mockResolvedValue(undefined);
+ return { b, prepare, copy };
+}
+describe('Linux compile once and independent bundles', () => {
+ it('compiles once then generates both installers without rewriting inputs', async () => {
+ const { b, prepare, copy } = fixture();
+ await b.build('https://example.com');
+ expect(prepare).toHaveBeenCalledTimes(1);
+ const commands = vi.mocked(shellExec).mock.calls.map(([c]) => c.args);
+ expect(commands).toHaveLength(3);
+ expect(commands[0]).toContain('--no-bundle');
+ expect(
+ commands
+ .slice(1)
+ .every((args) => args.includes('bundle') && !args.includes('build')),
+ ).toBe(true);
+ expect(copy.mock.calls.map((c) => c[0])).toEqual(['deb', 'appimage']);
+ });
+ it('does not bundle or copy after compilation fails', async () => {
+ const { b, copy } = fixture();
+ vi.mocked(shellExec).mockRejectedValue(new Error('compiler failed'));
+ await expect(b.build('https://example.com')).rejects.toThrow(
+ 'compiler failed',
+ );
+ expect(shellExec).toHaveBeenCalledTimes(1);
+ expect(copy).not.toHaveBeenCalled();
+ });
+ it('retries only AppImage bundling with NO_STRIP and preserves the successful DEB', async () => {
+ const { b, copy } = fixture();
+ let appImages = 0;
+ vi.mocked(shellExec).mockImplementation(async (c) => {
+ if (
+ c.args.includes('bundle') &&
+ c.args.includes('appimage') &&
+ ++appImages === 1
+ )
+ throw Error('strip failed');
+ return 0;
+ });
+ await b.build('https://example.com');
+ expect(shellExec).toHaveBeenCalledTimes(4);
+ expect(vi.mocked(shellExec).mock.calls[3][2]).toMatchObject({
+ NO_STRIP: '1',
+ });
+ expect(copy.mock.calls.map((c) => c[0])).toEqual(['deb', 'appimage']);
+ });
+ it('continues after a DEB failure without compiling again', async () => {
+ const { b, copy } = fixture();
+ vi.mocked(shellExec).mockImplementation(async (c) => {
+ if (c.args.includes('bundle') && c.args.includes('deb'))
+ throw Error('deb failed');
+ return 0;
+ });
+ await b.build('https://example.com');
+ expect(shellExec).toHaveBeenCalledTimes(3);
+ expect(copy.mock.calls.map((c) => c[0])).toEqual(['appimage']);
+ });
+ it('preserves target, features and debug settings in both stages', async () => {
+ const { b } = fixture('deb,appimage-arm64', true);
+ await b.build('https://example.com');
+ for (const [c] of vi.mocked(shellExec).mock.calls) {
+ expect(c.args).toContain('aarch64-unknown-linux-gnu');
+ expect(c.args).toContain('cli-build');
+ }
+ expect(vi.mocked(shellExec).mock.calls[0][0].args).toContain('build:debug');
+ expect(vi.mocked(shellExec).mock.calls[1][0].args).toContain('--debug');
+ });
+});