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.

feat: add a runtime-template build that reads its app config at launch

Tw93232469f862ac
diff --git a/AGENTS.md b/AGENTS.md
index ced60687..2c9d8131 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -107,6 +107,7 @@ Oracles per row live under `tests/unit/` (for example `event-link-guard.test.js`
- 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.
+- The `runtime-template` Cargo feature builds a prebuilt runtime that a separate builder customizes without a compiler: at launch it reads `pake-runtime/{pake.json, app.json, custom.js?, tray.png?}` from `Contents/Resources` on macOS or next to the executable elsewhere, and applies app.json's `identifier` and `productName` to the Tauri context before build. The CLI never enables the feature, so CLI-built apps keep their compiled configuration even if such a folder appears. A present but invalid override exits with a `[Pake]` message instead of falling back to the template's identity. Logic and tests live in `src-tauri/src/util.rs` (`apply_runtime_override`); keep `cargo clippy` and `cargo test --lib` green both with and without `--features runtime-template`.
- 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`. Compare existing artifact paths with `realpath`, since macOS `/var` and `/private/var` can identify the same file; retain a negative test for genuinely different files. Old bundles, empty directories, or timeout artifacts never prove a successful build.
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 433e8f5f..3eba30da 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -74,6 +74,9 @@ windows-core = "0.61.2"
[features]
# this feature is used for development builds from development cli
cli-build = []
+# Prebuilt template that reads a pake-runtime folder at launch: Contents/Resources
+# on macOS, next to the executable elsewhere. The CLI never enables it.
+runtime-template = []
# Tauri's macOS proxy APIs require macOS 14 or later. The CLI enables this
# feature only after checking the host Darwin version.
macos-proxy = ["tauri/macos-proxy"]
diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rs
index ed0b48e0..38e8f848 100644
--- a/src-tauri/src/app/config.rs
+++ b/src-tauri/src/app/config.rs
@@ -107,6 +107,9 @@ pub struct PakeConfig {
pub multi_instance: bool,
#[serde(default)]
pub multi_window: bool,
+ /// Replaces the compiled custom.js when a runtime override supplies one.
+ #[serde(skip)]
+ pub runtime_custom_js: Option<String>,
}
impl PakeConfig {
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 6e206e6a..af698c05 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -611,7 +611,12 @@ fn build_window(
.initialization_script(include_str!("../inject/event.js"))
.initialization_script(include_str!("../inject/style.js"))
.initialization_script(include_str!("../inject/theme_refresh.js"))
- .initialization_script(include_str!("../inject/custom.js"));
+ .initialization_script(
+ config
+ .runtime_custom_js
+ .as_deref()
+ .unwrap_or(include_str!("../inject/custom.js")),
+ );
#[cfg(target_os = "windows")]
let mut windows_browser_args = String::from("--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --disable-blink-features=AutomationControlled");
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 08aae763..8efd86cd 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -289,7 +289,15 @@ pub fn run_app() {
apply_linux_webkit_runtime_flags();
}
- let (pake_config, tauri_config) = get_pake_config();
+ let (pake_config, tauri_config, runtime_app) = get_pake_config();
+ let mut context = tauri::generate_context!();
+ // Paths, app data and the macOS menu derive from the context, so a runtime
+ // app must not share the template's identity.
+ if let Some(app) = runtime_app {
+ context.config_mut().identifier = app.identifier;
+ context.config_mut().product_name = Some(app.product_name.clone());
+ context.package_info_mut().name = app.product_name;
+ }
let tauri_app = tauri::Builder::default();
let show_system_tray = pake_config.show_system_tray();
@@ -504,7 +512,7 @@ pub fn run_app() {
// This lets tauri-plugin-window-state save the window position and size
}
})
- .build(tauri::generate_context!())
+ .build(context)
.unwrap_or_else(|error| {
eprintln!("[Pake] Fatal error while building Tauri application: {error}");
std::process::exit(1);
diff --git a/src-tauri/src/util.rs b/src-tauri/src/util.rs
index da78e3be..83d235f5 100644
--- a/src-tauri/src/util.rs
+++ b/src-tauri/src/util.rs
@@ -4,7 +4,7 @@ use std::env;
use std::path::{Path, PathBuf};
use tauri::{AppHandle, Config, Manager, WebviewWindow};
-pub fn get_pake_config() -> (PakeConfig, Config) {
+pub fn get_pake_config() -> (PakeConfig, Config, Option<RuntimeApp>) {
#[cfg(feature = "cli-build")]
let pake_config: PakeConfig = serde_json::from_str(include_str!("../.pake/pake.json"))
.expect("Failed to parse pake config");
@@ -21,7 +21,97 @@ pub fn get_pake_config() -> (PakeConfig, Config) {
let tauri_config: Config = serde_json::from_str(include_str!("../tauri.conf.json"))
.expect("Failed to parse tauri config");
- (pake_config, tauri_config)
+ // Only the prebuilt template reads a runtime override; CLI-built apps keep
+ // their compiled configuration even if a pake-runtime folder appears.
+ #[cfg(feature = "runtime-template")]
+ let runtime_dir = env::current_exe()
+ .ok()
+ .and_then(|exe| runtime_dir_for_exe(&exe));
+ #[cfg(not(feature = "runtime-template"))]
+ let runtime_dir: Option<PathBuf> = None;
+ match apply_runtime_override(pake_config, tauri_config, runtime_dir.as_deref()) {
+ Ok(configs) => configs,
+ Err(error) => {
+ eprintln!("[Pake] Invalid runtime configuration: {error}");
+ std::process::exit(1);
+ }
+ }
+}
+
+const RUNTIME_DIR: &str = "pake-runtime";
+
+/// App identity supplied next to a runtime `pake.json`.
+#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RuntimeApp {
+ pub identifier: String,
+ pub product_name: String,
+}
+
+/// macOS keeps overrides in `Contents/Resources/pake-runtime`; other platforms
+/// use `pake-runtime` next to the executable.
+#[cfg_attr(not(feature = "runtime-template"), allow(dead_code))]
+fn runtime_dir_for_exe(exe: &Path) -> Option<PathBuf> {
+ let exe_dir = exe.parent()?;
+ #[cfg(target_os = "macos")]
+ let base = exe_dir.parent()?.join("Resources");
+ #[cfg(not(target_os = "macos"))]
+ let base = exe_dir.to_path_buf();
+ Some(base.join(RUNTIME_DIR))
+}
+
+fn read_optional(path: &Path) -> Result<Option<String>, String> {
+ match std::fs::read_to_string(path) {
+ Ok(contents) => Ok(Some(contents)),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(format!("cannot read {}: {error}", path.display())),
+ }
+}
+
+/// Without `pake-runtime/pake.json` the compiled configuration is returned
+/// unchanged. When it exists, `app.json` is required and both must parse.
+fn apply_runtime_override(
+ mut pake_config: PakeConfig,
+ mut tauri_config: Config,
+ runtime_dir: Option<&Path>,
+) -> Result<(PakeConfig, Config, Option<RuntimeApp>), String> {
+ let Some(dir) = runtime_dir else {
+ return Ok((pake_config, tauri_config, None));
+ };
+ let pake_path = dir.join("pake.json");
+ let Some(pake_json) = read_optional(&pake_path)? else {
+ return Ok((pake_config, tauri_config, None));
+ };
+ let app_path = dir.join("app.json");
+ let app_json =
+ read_optional(&app_path)?.ok_or_else(|| format!("{} is missing", app_path.display()))?;
+
+ pake_config = serde_json::from_str(&pake_json)
+ .map_err(|error| format!("cannot parse {}: {error}", pake_path.display()))?;
+ if pake_config.windows.is_empty() {
+ return Err(format!("{} defines no windows", pake_path.display()));
+ }
+ let app: RuntimeApp = serde_json::from_str(&app_json)
+ .map_err(|error| format!("cannot parse {}: {error}", app_path.display()))?;
+ if app.identifier.trim().is_empty() || app.product_name.trim().is_empty() {
+ return Err(format!(
+ "{} needs a non-empty identifier and productName",
+ app_path.display()
+ ));
+ }
+
+ pake_config.runtime_custom_js = read_optional(&dir.join("custom.js"))?;
+ if !pake_config.system_tray_path.is_empty()
+ && Path::new(&pake_config.system_tray_path).is_relative()
+ {
+ pake_config.system_tray_path = dir
+ .join(&pake_config.system_tray_path)
+ .to_string_lossy()
+ .into_owned();
+ }
+ tauri_config.identifier = app.identifier.clone();
+ tauri_config.product_name = Some(app.product_name.clone());
+ Ok((pake_config, tauri_config, Some(app)))
}
pub fn get_data_dir(app: &AppHandle, package_name: String) -> std::io::Result<PathBuf> {
@@ -470,4 +560,152 @@ mod tests {
assert!(en.contains("Download failed"));
assert!(zh.contains("下载失败"));
}
+
+ fn compiled_configs() -> (PakeConfig, Config) {
+ (
+ serde_json::from_str(include_str!("../pake.json")).unwrap(),
+ serde_json::from_str(include_str!("../tauri.conf.json")).unwrap(),
+ )
+ }
+
+ fn snapshot(pake: &PakeConfig, tauri: &Config) -> (serde_json::Value, serde_json::Value) {
+ (
+ serde_json::to_value(pake).unwrap(),
+ serde_json::to_value(tauri).unwrap(),
+ )
+ }
+
+ fn runtime_dir(files: &[(&str, &str)]) -> PathBuf {
+ let dir = temp_path(RUNTIME_DIR);
+ fs::create_dir_all(&dir).unwrap();
+ for (name, contents) in files {
+ fs::write(dir.join(name), contents).unwrap();
+ }
+ dir
+ }
+
+ const RUNTIME_APP: &str = r#"{"identifier":"com.pake.a1b2c3","productName":"Runtime Probe"}"#;
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn runtime_dir_lives_in_bundle_resources_on_macos() {
+ assert_eq!(
+ runtime_dir_for_exe(Path::new("/Applications/Probe.app/Contents/MacOS/pake")),
+ Some(PathBuf::from(
+ "/Applications/Probe.app/Contents/Resources/pake-runtime"
+ ))
+ );
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ #[test]
+ fn runtime_dir_lives_next_to_executable() {
+ let exe = temp_path("pake");
+ assert_eq!(
+ runtime_dir_for_exe(&exe),
+ Some(exe.parent().unwrap().join("pake-runtime"))
+ );
+ }
+
+ #[test]
+ fn absent_runtime_override_keeps_compiled_configs() {
+ let (pake, tauri) = compiled_configs();
+ let expected = snapshot(&pake, &tauri);
+
+ let (pake, tauri, app) = apply_runtime_override(pake, tauri, None).unwrap();
+ assert!(app.is_none());
+ assert_eq!(snapshot(&pake, &tauri), expected);
+
+ // A directory without pake.json is not a runtime app, even with app.json.
+ let dir = runtime_dir(&[("app.json", RUNTIME_APP), ("custom.js", "x")]);
+ let (pake, tauri, app) = apply_runtime_override(pake, tauri, Some(&dir)).unwrap();
+ assert!(app.is_none());
+ assert!(pake.runtime_custom_js.is_none());
+ assert_eq!(snapshot(&pake, &tauri), expected);
+
+ let missing = dir.join("missing");
+ let (pake, tauri, app) = apply_runtime_override(pake, tauri, Some(&missing)).unwrap();
+ assert!(app.is_none());
+ assert_eq!(snapshot(&pake, &tauri), expected);
+ fs::remove_dir_all(dir.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn runtime_override_replaces_config_identity_script_and_tray() {
+ let mut runtime: serde_json::Value =
+ serde_json::from_str(include_str!("../pake.json")).unwrap();
+ runtime["windows"][0]["url"] = "https://example.com/app".into();
+ runtime["system_tray_path"] = "tray.png".into();
+ // Optional fields fall back to their serde defaults.
+ for key in ["password_autosave", "new_window", "enable_find"] {
+ runtime["windows"][0].as_object_mut().unwrap().remove(key);
+ }
+ runtime.as_object_mut().unwrap().remove("download_dir");
+ let dir = runtime_dir(&[
+ ("pake.json", &runtime.to_string()),
+ ("app.json", RUNTIME_APP),
+ ("custom.js", "document.documentElement.dataset.probe = '1';"),
+ ]);
+
+ let (pake, tauri) = compiled_configs();
+ let (pake, tauri, app) = apply_runtime_override(pake, tauri, Some(&dir)).unwrap();
+ assert_eq!(
+ app,
+ Some(RuntimeApp {
+ identifier: "com.pake.a1b2c3".into(),
+ product_name: "Runtime Probe".into(),
+ })
+ );
+ assert_eq!(tauri.identifier, "com.pake.a1b2c3");
+ assert_eq!(tauri.product_name.as_deref(), Some("Runtime Probe"));
+ assert_eq!(pake.windows[0].url, "https://example.com/app");
+ assert_eq!(pake.windows[0].zoom, 100);
+ assert!(!pake.windows[0].enable_find);
+ assert!(pake.download_dir.is_empty());
+ assert_eq!(
+ pake.runtime_custom_js.as_deref(),
+ Some("document.documentElement.dataset.probe = '1';")
+ );
+ assert_eq!(PathBuf::from(&pake.system_tray_path), dir.join("tray.png"));
+
+ // Absolute tray paths and a missing custom.js stay as written.
+ let absolute = dir.join("elsewhere.png");
+ runtime["system_tray_path"] = absolute.to_string_lossy().into_owned().into();
+ fs::write(dir.join("pake.json"), runtime.to_string()).unwrap();
+ fs::remove_file(dir.join("custom.js")).unwrap();
+ let (pake, tauri) = compiled_configs();
+ let (pake, _, _) = apply_runtime_override(pake, tauri, Some(&dir)).unwrap();
+ assert_eq!(PathBuf::from(&pake.system_tray_path), absolute);
+ assert!(pake.runtime_custom_js.is_none());
+ fs::remove_dir_all(dir.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn invalid_runtime_override_is_an_error() {
+ let pake_json = include_str!("../pake.json");
+ for files in [
+ vec![("pake.json", pake_json)],
+ vec![("pake.json", "{"), ("app.json", RUNTIME_APP)],
+ vec![
+ ("pake.json", r#"{"windows":[]}"#),
+ ("app.json", RUNTIME_APP),
+ ],
+ vec![
+ ("pake.json", pake_json),
+ ("app.json", r#"{"identifier":"x"}"#),
+ ],
+ vec![
+ ("pake.json", pake_json),
+ ("app.json", r#"{"identifier":" ","productName":"Probe"}"#),
+ ],
+ ] {
+ let dir = runtime_dir(&files);
+ let (pake, tauri) = compiled_configs();
+ assert!(
+ apply_runtime_override(pake, tauri, Some(&dir)).is_err(),
+ "expected an error for {files:?}"
+ );
+ fs::remove_dir_all(dir.parent().unwrap()).unwrap();
+ }
+ }
}