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 --json machine output, --config manifests, and local input packaging

Tw9369defaee010f
diff --git a/.claude/rules/rust.md b/.claude/rules/rust.md
index 873bb54b..3d018650 100644
--- a/.claude/rules/rust.md
+++ b/.claude/rules/rust.md
@@ -7,7 +7,9 @@
### Error handling
- No `panic!` / `.unwrap()` / `.expect()` on user-reachable paths: CLI options, config loading, event handlers, IPC commands. Use `?` and surface clear messages.
-- Silent `catch {}` in TS or `let _ = ...` in Rust must surface the real error through `logger.warn` at minimum.
+- Silent `catch {}` in TS or `let _ = ...` in Rust must surface the real error through `logger.warn` at minimum. Note `logger.warn` also feeds the `--json` warnings array; status lines belong in `logger.info`.
+- Predictable CLI failures throw `PakeError` with `{code, hint}` (`bin/utils/error.ts`); the code maps to a stable exit code and the `--json` error object. Plain `Error` gets classified by build phase in `bin/cli.ts`.
+- In machine mode (`--json`) stdout is reserved for the single JSON result. Never `console.log` / `process.stdout.write` in `bin/`; subprocess stdout is rerouted to stderr by `shellExec`.
- `shellExec` runs subprocesses with `stdio: 'inherit'`, so their output (linuxdeploy, cargo, npm) never reaches `error.message`; only the failed command line does. Do NOT classify a build failure by grepping `error.message`; you would be matching the command, not the diagnostics. Drive failure guidance off a structured fact the caller holds (e.g. `target === 'appimage'`). Owners: `bin/utils/shell.ts` + `bin/builders/BaseBuilder.ts`.
### IPC
@@ -19,7 +21,7 @@
### Config types
- No `tauriConf: any` or other untyped config bags. Use `PakeTauriConfig`.
-- Window options live in `bin/helpers/cli-program.ts`, `bin/types.ts`, `bin/defaults.ts`, `bin/helpers/merge.ts`. Adding an option means touching all four plus `docs/cli-usage*.md`. Forgetting any is a regression.
+- Window options live in `bin/helpers/cli-program.ts`, `bin/types.ts`, `bin/defaults.ts`, `bin/helpers/merge.ts`. Adding an option means touching all four plus `schema/pake.schema.json` and `docs/cli-usage*.md`. Forgetting any is a regression; the schema half is caught by `tests/unit/config-file.test.ts`.
### Network mirrors
diff --git a/README.md b/README.md
index 4d855525..223b3694 100644
--- a/README.md
+++ b/README.md
@@ -192,6 +192,8 @@ pake https://weekly.tw93.fun --name Weekly --icon https://cdn.tw93.fun/pake/week
First-time packaging requires environment setup and may be slower, subsequent builds are fast. For complete parameter documentation, see [CLI Usage Guide](docs/cli-usage.md). Don't want to use CLI? Try [GitHub Actions Online Building](docs/github-actions-usage.md).
+Using Pake from a script or AI agent? Pass `--json` for machine-readable results, describe apps declaratively with `--config app.json` ([schema](schema/pake.schema.json)), and package local build output directly with `pake ./dist --name MyTool`. See [llms.txt](llms.txt) for the full agent contract. Claude Code users can install the official skill with `/plugin marketplace add tw93/Pake` and `/plugin install pake@pake`.
+
## Development
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.
diff --git a/README_CN.md b/README_CN.md
index 368abc26..ee399aa3 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -193,6 +193,8 @@ pake https://weekly.tw93.fun --name Weekly --icon https://cdn.tw93.fun/pake/week
首次打包需要安装环境会比较慢,后续很快。完整参数说明查看 [CLI 使用指南](docs/cli-usage_CN.md),不想用命令行可以试试 [GitHub Actions 在线构建](docs/github-actions-usage_CN.md)。
+在脚本或 AI agent 里使用 Pake?加 `--json` 获得机器可读结果,用 `--config app.json` 声明式描述应用([schema](schema/pake.schema.json)),本地构建产物可直接 `pake ./dist --name MyTool` 打包。完整 agent 契约见 [llms.txt](llms.txt)。Claude Code 用户可通过 `/plugin marketplace add tw93/Pake` 和 `/plugin install pake@pake` 安装官方 skill。
+
## 定制开发
需要 Rust `>=1.85` 和 Node `>=22`(推荐 LTS,较旧的 `>=18` 也可使用),详细安装指南参考 [Tauri 文档](https://tauri.app/start/prerequisites/)。不熟悉开发环境建议直接使用命令行工具。
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.ts
index e8864ca7..26f72bed 100644
--- a/bin/builders/BaseBuilder.ts
+++ b/bin/builders/BaseBuilder.ts
@@ -12,7 +12,9 @@ import {
generateLinuxPackageName,
} from '@/utils/name';
import { npmDirectory } from '@/utils/dir';
+import { PakeError } from '@/utils/error';
import { getSpinner } from '@/utils/info';
+import { BuildArtifact, isInteractive } from '@/utils/output';
import { shellExec } from '@/utils/shell';
import { CN_MIRROR_ENV, isCnMirrorEnabled } from '@/utils/mirror';
import { IS_MAC } from '@/utils/platform';
@@ -52,11 +54,72 @@ const APPIMAGE_FAILURE_GUIDANCE =
export default abstract class BaseBuilder {
protected options: PakeAppOptions;
+ private artifacts: BuildArtifact[] = [];
protected constructor(options: PakeAppOptions) {
this.options = options;
}
+ /** Final artifacts produced by this build, for the `--json` result. */
+ getArtifacts(): BuildArtifact[] {
+ return [...this.artifacts];
+ }
+
+ /** Architecture reported in the `--json` result. */
+ getReportArch(): string {
+ return this.options.multiArch ? 'universal' : process.arch;
+ }
+
+ // Drop a recorded artifact whose file was later removed (e.g. the
+ // temporary .deb consumed by zst repacking), so --json never lists a
+ // path that no longer exists.
+ protected removeArtifact(artifactPath: string): void {
+ const resolved = path.resolve(artifactPath);
+ this.artifacts = this.artifacts.filter(
+ (artifact) => artifact.path !== resolved,
+ );
+ }
+
+ protected async recordArtifact(
+ artifactPath: string,
+ format: string,
+ ): Promise<void> {
+ try {
+ const stat = await fsExtra.stat(artifactPath);
+ let sizeBytes = stat.size;
+ if (stat.isDirectory()) {
+ sizeBytes = await BaseBuilder.getPathSize(artifactPath);
+ }
+ this.artifacts.push({
+ path: path.resolve(artifactPath),
+ sizeBytes,
+ format,
+ });
+ } catch {
+ // Never fail a finished build over size bookkeeping.
+ this.artifacts.push({
+ path: path.resolve(artifactPath),
+ sizeBytes: 0,
+ format,
+ });
+ }
+ }
+
+ private static async getPathSize(directory: string): Promise<number> {
+ let size = 0;
+ for (const entry of await fsExtra.readdir(directory, {
+ withFileTypes: true,
+ })) {
+ const entryPath = path.join(directory, entry.name);
+ if (entry.isDirectory()) {
+ size += await BaseBuilder.getPathSize(entryPath);
+ } else if (entry.isFile()) {
+ size += (await fsExtra.stat(entryPath)).size;
+ }
+ }
+ return size;
+ }
+
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
const tauriTargetPath = path.join(tauriSrcPath, 'target');
@@ -70,6 +133,13 @@ export default abstract class BaseBuilder {
ensureRustEnv();
if (!checkRustInstalled()) {
+ if (!isInteractive()) {
+ throw new PakeError('Rust required to package your webapp.', {
+ code: 'ENV_MISSING',
+ hint: 'Install Rust via https://rustup.rs, then rerun the same command.',
+ });
+ }
+
const res = await prompts({
type: 'confirm',
message: 'Rust not detected. Install now?',
@@ -79,8 +149,10 @@ export default abstract class BaseBuilder {
if (res.value) {
await installRust();
} else {
- logger.error('✕ Rust required to package your webapp.');
- process.exit(1);
+ throw new PakeError('Rust required to package your webapp.', {
+ code: 'ENV_MISSING',
+ hint: 'Install Rust via https://rustup.rs, then rerun the same command.',
+ });
}
}
@@ -167,8 +239,9 @@ export default abstract class BaseBuilder {
// Let spinner run for a moment so user can see it, then stop before package manager command
await new Promise((resolve) => setTimeout(resolve, 500));
buildSpinner.stop();
- // Show static message to keep the status visible
- logger.warn('✸ Building app...');
+ // Show static message to keep the status visible. Info, not warn: warn
+ // entries feed the --json warnings array and this is a status line.
+ logger.info('✸ Building app...');
const baseEnv = getBuildEnvironment();
let buildEnv: Record<string, string> = {
@@ -225,6 +298,7 @@ export default abstract class BaseBuilder {
// executable the build produced instead.
if (this.options.bundle === false) {
await this.copyRawBinary(npmDirectory, name);
+ await this.recordArtifact(this.getRawBinaryPath(name), 'binary');
if (logSuccess) {
logger.success('✔ Build success!');
logger.success(
@@ -241,10 +315,12 @@ export default abstract class BaseBuilder {
const appPath = this.getBuildAppPath(npmDirectory, fileName, fileType);
const distPath = path.resolve(`${name}.${fileType}`);
await fsExtra.copy(appPath, distPath);
+ await this.recordArtifact(distPath, fileType);
// Copy raw binary if requested
if (this.options.keepBinary) {
await this.copyRawBinary(npmDirectory, name);
+ await this.recordArtifact(this.getRawBinaryPath(name), 'binary');
}
await fsExtra.remove(appPath);
@@ -284,6 +360,14 @@ export default abstract class BaseBuilder {
// to copy+remove only when moving across volumes.
await fsExtra.move(appBundlePath, appDest, { overwrite: true });
+ // Keep the JSON result pointing at where the artifact actually lives.
+ const movedFrom = path.resolve(appBundlePath);
+ for (const artifact of this.artifacts) {
+ if (artifact.path === movedFrom) {
+ artifact.path = appDest;
+ }
+ }
+
logger.success(
`✔ ${appBundleName.replace(/\.app$/, '')} installed to /Applications`,
);
diff --git a/bin/builders/LinuxBuilder.ts b/bin/builders/LinuxBuilder.ts
index 6fc451d2..1e21830f 100644
--- a/bin/builders/LinuxBuilder.ts
+++ b/bin/builders/LinuxBuilder.ts
@@ -32,6 +32,10 @@ export default class LinuxBuilder extends BaseBuilder {
this.options.targets = this.buildFormat;
}
+ getReportArch(): string {
+ return this.buildArch;
+ }
+
getFileName() {
const { name = 'pake-app', targets } = this.options;
const version = tauriConfig.version;
@@ -222,11 +226,13 @@ post_remove() {
await shellExec(
`bsdtar --zstd -cf "${packagePath}" -C "${dataDir}" .PKGINFO .INSTALL usr`,
);
+ await this.recordArtifact(packagePath, 'zst');
logger.success('✔ Build success!');
logger.success('✔ App installer located in', packagePath);
} finally {
if (removeSourceDeb) {
await fsExtra.remove(debPath);
+ this.removeArtifact(debPath);
}
await fsExtra.remove(workDir);
}
diff --git a/bin/builders/MacBuilder.ts b/bin/builders/MacBuilder.ts
index 1fbf776a..95d7e285 100644
--- a/bin/builders/MacBuilder.ts
+++ b/bin/builders/MacBuilder.ts
@@ -50,6 +50,10 @@ export default class MacBuilder extends BaseBuilder {
return `${name}_${tauriConfig.version}_${arch}`;
}
+ getReportArch(): string {
+ return this.getActualArch();
+ }
+
private getActualArch(): string {
if (this.buildArch === 'universal' || this.options.multiArch) {
return 'universal';
diff --git a/bin/builders/WinBuilder.ts b/bin/builders/WinBuilder.ts
index 7b1f85e0..8c36c371 100644
--- a/bin/builders/WinBuilder.ts
+++ b/bin/builders/WinBuilder.ts
@@ -17,6 +17,10 @@ export default class WinBuilder extends BaseBuilder {
this.options.targets = this.buildFormat;
}
+ getReportArch(): string {
+ return this.buildArch;
+ }
+
getFileName(): string {
const { name } = this.options;
const language = tauriConfig.bundle.windows.wix.language[0];
diff --git a/bin/cli.ts b/bin/cli.ts
index 8fe6738c..a6d57072 100644
--- a/bin/cli.ts
+++ b/bin/cli.ts
@@ -5,22 +5,123 @@ 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 { loadConfigFile } from './helpers/config-file';
+import { isPakeError, PakeError } from './utils/error';
+import { validateUrlInput } from './utils/validate';
+import {
+ ERROR_EXIT_CODES,
+ PakeErrorCode,
+ enableMachineMode,
+ getCapturedWarnings,
+ printJsonResult,
+} from './utils/output';
import { PakeCliOptions } from './types';
const program = getCliProgram();
+// Make commander throw instead of exiting so option/argument parse errors
+// honor the exit-code contract (2 = invalid input) and still emit the JSON
+// result object when --json was requested.
+program.exitOverride();
+
+function isCommanderExit(
+ error: unknown,
+): error is { code: string; exitCode: number; message: string } {
+ return (
+ typeof error === 'object' &&
+ error !== null &&
+ typeof (error as { code?: unknown }).code === 'string' &&
+ (error as { code: string }).code.startsWith('commander.')
+ );
+}
+
+// Which stage the failure happened in decides the default error code; a
+// PakeError carrying an explicit code always wins over the phase default.
+type BuildPhase = 'input' | 'prepare' | 'build';
+
+const PHASE_ERROR_CODES: Record<BuildPhase, PakeErrorCode> = {
+ input: 'INVALID_INPUT',
+ prepare: 'ENV_MISSING',
+ build: 'BUILD_FAILED',
+};
+
+function classifyError(
+ error: unknown,
+ phase: BuildPhase,
+): { code: PakeErrorCode; message: string; hint: string | null } {
+ if (isPakeError(error)) {
+ return {
+ code: error.code ?? PHASE_ERROR_CODES[phase],
+ message: error.message,
+ hint: error.hint ?? null,
+ };
+ }
+ if (error instanceof Error) {
+ return {
+ code: PHASE_ERROR_CODES[phase],
+ message: error.message,
+ hint: null,
+ };
+ }
+ return {
+ code: 'UNEXPECTED',
+ message: `Unexpected error: ${String(error)}`,
+ hint: null,
+ };
+}
+
async function checkUpdateTips() {
updateNotifier({ pkg: packageJson, updateCheckInterval: 1000 * 60 }).notify({
isGlobal: true,
});
}
-program.action(async (url: string, options: PakeCliOptions) => {
+program.action(async (urlArg: string, options: PakeCliOptions) => {
+ const jsonMode = Boolean(options.json);
+ if (jsonMode) {
+ enableMachineMode();
+ }
+
+ let phase: BuildPhase = 'input';
+ let appName: string | null = null;
+ let url = urlArg;
+
try {
- await checkUpdateTips();
+ if (!jsonMode) {
+ await checkUpdateTips();
+ }
+
+ // Config file fills in whatever the command line did not set explicitly:
+ // CLI flag > config field > built-in default.
+ if (options.config) {
+ const validKeys = new Set(
+ program.options.map((option) => option.attributeName()),
+ );
+ const loaded = await loadConfigFile(options.config, validKeys);
+ for (const [key, value] of Object.entries(loaded.options)) {
+ if (program.getOptionValueSource(key) !== 'cli') {
+ (options as unknown as Record<string, unknown>)[key] = value;
+ }
+ }
+ if (!url && loaded.url) {
+ try {
+ url = validateUrlInput(loaded.url);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ throw new PakeError(`Invalid "url" in config file: ${detail}`, {
+ code: 'INVALID_INPUT',
+ });
+ }
+ }
+ }
if (!url) {
+ if (jsonMode) {
+ throw new PakeError('No URL or local path to package.', {
+ code: 'INVALID_INPUT',
+ hint: 'Pass a URL/path argument or a config file with a "url" field.',
+ });
+ }
program.help({
error: false,
});
@@ -34,13 +135,49 @@ program.action(async (url: string, options: PakeCliOptions) => {
}
const appOptions = await handleInputOptions(options, url);
+ appName = appOptions.name ?? null;
const builder = BuilderProvider.create(appOptions);
+ phase = 'prepare';
await builder.prepare();
+ phase = 'build';
await builder.build(url);
+
+ if (jsonMode) {
+ printJsonResult({
+ ok: true,
+ name: appName,
+ platform: process.platform,
+ arch: builder.getReportArch(),
+ outputs: builder.getArtifacts(),
+ warnings: getCapturedWarnings(),
+ error: null,
+ });
+ }
} catch (error) {
- if (isPakeError(error)) {
- console.error(chalk.red(error.message));
+ // program.help() and --help/--version throw under exitOverride with
+ // exitCode 0; a clean commander exit is not a failure.
+ if (isCommanderExit(error) && error.exitCode === 0) {
+ process.exit(0);
+ }
+
+ const classified = classifyError(error, phase);
+
+ if (jsonMode) {
+ printJsonResult({
+ ok: false,
+ name: appName,
+ platform: process.platform,
+ arch: null,
+ outputs: [],
+ warnings: getCapturedWarnings(),
+ error: classified,
+ });
+ } else if (isPakeError(error)) {
+ console.error(chalk.red(classified.message));
+ if (classified.hint) {
+ console.error(chalk.yellow(`✼ ${classified.hint}`));
+ }
} else if (error instanceof Error) {
console.error(chalk.red(`✕ ${error.message}`));
if (options?.debug && error.stack) {
@@ -49,11 +186,37 @@ program.action(async (url: string, options: PakeCliOptions) => {
} else {
console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));
}
- process.exit(1);
+
+ process.exit(ERROR_EXIT_CODES[classified.code]);
}
});
program.parseAsync().catch((error: unknown) => {
+ if (isCommanderExit(error)) {
+ // --help / --version and friends exit clean; commander already printed.
+ if (error.exitCode === 0) {
+ process.exit(0);
+ }
+ // Parse errors (unknown option, invalid argument, missing value) are
+ // invalid input. Commander already printed the message to stderr; in
+ // json mode also emit the machine-readable result on stdout.
+ if (process.argv.includes('--json')) {
+ printJsonResult({
+ ok: false,
+ name: null,
+ platform: process.platform,
+ arch: null,
+ outputs: [],
+ warnings: [],
+ error: {
+ code: 'INVALID_INPUT',
+ message: error.message.trim(),
+ hint: 'Run pake --help for the accepted options.',
+ },
+ });
+ }
+ process.exit(ERROR_EXIT_CODES.INVALID_INPUT);
+ }
if (error instanceof Error) {
console.error(chalk.red(`✕ ${error.message}`));
} else {
diff --git a/bin/defaults.ts b/bin/defaults.ts
index 7ae2ca34..3b0a24c4 100644
--- a/bin/defaults.ts
+++ b/bin/defaults.ts
@@ -34,6 +34,7 @@ export const DEFAULT_PAKE_OPTIONS: PakeCliOptions = {
systemTrayIcon: '',
proxyUrl: '',
debug: false,
+ json: false,
inject: [],
installerLanguage: 'en-US',
hideOnClose: undefined, // Platform-specific: true for macOS, false for others
diff --git a/bin/helpers/cli-program.ts b/bin/helpers/cli-program.ts
index 5b05dca1..5e2602d1 100644
--- a/bin/helpers/cli-program.ts
+++ b/bin/helpers/cli-program.ts
@@ -70,6 +70,15 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
DEFAULT.inject,
)
.option('--debug', 'Debug build and more output', DEFAULT.debug)
+ .option(
+ '--json',
+ 'Machine-readable output: logs to stderr, one JSON result on stdout',
+ DEFAULT.json,
+ )
+ .option(
+ '--config <path>',
+ 'Load options from a JSON config file (fields mirror CLI options, see schema/pake.schema.json)',
+ )
.addOption(
new Option(
'--proxy-url <url>',
diff --git a/bin/helpers/config-file.ts b/bin/helpers/config-file.ts
new file mode 100644
index 00000000..7897734b
--- /dev/null
+++ b/bin/helpers/config-file.ts
@@ -0,0 +1,131 @@
+import fsExtra from 'fs-extra';
+import { DEFAULT_PAKE_OPTIONS as DEFAULT } from '../defaults';
+import { PakeError } from '../utils/error';
+import { PakeCliOptions } from '../types';
+
+/**
+ * `--config <path>` support: a declarative JSON manifest whose fields mirror
+ * the CLI options (camelCase), plus `url`. Precedence is CLI flag > config
+ * file > default, resolved in bin/cli.ts via commander's option-value source.
+ * The published schema lives in schema/pake.schema.json.
+ */
+
+export interface LoadedConfigFile {
+ url?: string;
+ options: Partial<PakeCliOptions>;
+}
+
+// Invocation concerns, not app manifest fields; pass these as CLI flags.
+const REJECTED_KEYS = new Set(['config', 'json', 'version']);
+
+// Optional CLI options that have no entry in DEFAULT_PAKE_OPTIONS.
+const EXTRA_STRING_KEYS = new Set(['name', 'title', 'identifier']);
+
+type ExpectedType = 'string' | 'number' | 'boolean' | 'string[]';
+
+function expectedTypeFor(key: string): ExpectedType | null {
+ if (key === 'inject') return 'string[]';
+ if (key === 'hideOnClose') return 'boolean';
+ if (EXTRA_STRING_KEYS.has(key)) return 'string';
+ const defaultValue = (DEFAULT as unknown as Record<string, unknown>)[key];
+ const type = typeof defaultValue;
+ if (type === 'string' || type === 'number' || type === 'boolean') {
+ return type;
+ }
+ return null;
+}
+
+function matchesType(value: unknown, type: ExpectedType): boolean {
+ if (type === 'string[]') {
+ return Array.isArray(value) && value.every((v) => typeof v === 'string');
+ }
+ return typeof value === type;
+}
+
+export async function loadConfigFile(
+ configPath: string,
+ validKeys: Set<string>,
+): Promise<LoadedConfigFile> {
+ if (!(await fsExtra.pathExists(configPath))) {
+ throw new PakeError(`Config file not found: ${configPath}`, {
+ code: 'INVALID_INPUT',
+ hint: 'Pass a path to a JSON file matching schema/pake.schema.json.',
+ });
+ }
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(await fsExtra.readFile(configPath, 'utf8'));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ throw new PakeError(`Config file is not valid JSON: ${detail}`, {
+ code: 'INVALID_INPUT',
+ hint: `Fix the JSON syntax in ${configPath}.`,
+ });
+ }
+
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ throw new PakeError('Config file must contain a JSON object.', {
+ code: 'INVALID_INPUT',
+ hint: 'See schema/pake.schema.json for the expected shape.',
+ });
+ }
+
+ const result: LoadedConfigFile = { options: {} };
+
+ for (const [key, value] of Object.entries(parsed)) {
+ if (key === '$schema') continue;
+
+ if (key === 'url') {
+ if (typeof value !== 'string') {
+ throw new PakeError('Config field "url" must be a string.', {
+ code: 'INVALID_INPUT',
+ hint: 'Use a web URL or a local file/directory path.',
+ });
+ }
+ result.url = value;
+ continue;
+ }
+
+ if (REJECTED_KEYS.has(key)) {
+ throw new PakeError(
+ `Config field "${key}" is not allowed in a config file.`,
+ {
+ code: 'INVALID_INPUT',
+ hint: `Pass --${key} on the command line instead.`,
+ },
+ );
+ }
+
+ if (!validKeys.has(key)) {
+ throw new PakeError(`Unknown config field "${key}".`, {
+ code: 'INVALID_INPUT',
+ hint: 'Field names are camelCase CLI option names; see schema/pake.schema.json.',
+ });
+ }
+
+ const expected = expectedTypeFor(key);
+ if (expected && !matchesType(value, expected)) {
+ throw new PakeError(
+ `Config field "${key}" must be of type ${expected}.`,
+ {
+ code: 'INVALID_INPUT',
+ hint: 'See schema/pake.schema.json for field types.',
+ },
+ );
+ }
+ if (!expected && (typeof value === 'object' || value === null)) {
+ throw new PakeError(
+ `Config field "${key}" must be a string, number, or boolean.`,
+ {
+ code: 'INVALID_INPUT',
+ hint: 'See schema/pake.schema.json for field types.',
+ },
+ );
+ }
+
+ (result.options as Record<string, unknown>)[key] = value;
+ }
+
+ return result;
+}
diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.ts
index ff2e602b..7d3ac9b8 100644
--- a/bin/helpers/merge.ts
+++ b/bin/helpers/merge.ts
@@ -17,6 +17,7 @@ import {
WindowConfig,
} from '@/types';
import { tauriConfigDirectory, npmDirectory } from '@/utils/dir';
+import { PakeError } from '@/utils/error';
import { LINUX_TARGET_TYPES, resolveLinuxBundleTargets } from '@/utils/targets';
/**
@@ -106,40 +107,78 @@ async function copyTemplateConfigs(): Promise<void> {
);
}
-async function handleLocalFile(
+// Replace the CLI's own dist/ with the user's static files while keeping the
+// build artifacts (cli.js) the packaged app does not need but the CLI does.
+// dist_bak always holds the ORIGINAL package dist: once it exists, later
+// stagings must not overwrite it with a previous user tree, or the original
+// files would be unrecoverable across repeated local builds.
+async function stageLocalTree(sourceDir: string): Promise<void> {
+ const distDir = path.join(npmDirectory, 'dist');
+ const distBakDir = path.join(npmDirectory, 'dist_bak');
+
+ if (await fsExtra.pathExists(distBakDir)) {
+ fsExtra.removeSync(distDir);
+ } else {
+ fsExtra.moveSync(distDir, distBakDir);
+ }
+ fsExtra.copySync(sourceDir, distDir, { overwrite: true });
+
+ const filesToCopyBack = ['cli.js'];
+ await Promise.all(
+ filesToCopyBack.map((file) =>
+ fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file)),
+ ),
+ );
+}
+
+// Exported for unit tests (web fallback and directory entry guard).
+export async function handleLocalFile(
url: string,
useLocalFile: boolean,
tauriConf: PakeTauriConfig,
): Promise<void> {
const pathExists = await fsExtra.pathExists(url);
- if (pathExists) {
- logger.warn('✼ Your input might be a local file.');
-
- const fileName = path.basename(url);
- const dirName = path.dirname(url);
- const distDir = path.join(npmDirectory, 'dist');
- const distBakDir = path.join(npmDirectory, 'dist_bak');
+ if (!pathExists) {
+ tauriConf.pake.windows[0].url_type = 'web';
+ return;
+ }
- if (!useLocalFile) {
- const urlPath = path.join(distDir, fileName);
- await fsExtra.copy(url, urlPath);
- } else {
- fsExtra.moveSync(distDir, distBakDir, { overwrite: true });
- fsExtra.copySync(dirName, distDir, { overwrite: true });
-
- const filesToCopyBack = ['cli.js'];
- await Promise.all(
- filesToCopyBack.map((file) =>
- fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file)),
- ),
+ const stat = await fsExtra.stat(url);
+
+ if (stat.isDirectory()) {
+ // A directory of static web assets (e.g. a generated dist/): the whole
+ // tree is packaged and the app entry is its root index.html.
+ const entryFile = 'index.html';
+ if (!(await fsExtra.pathExists(path.join(url, entryFile)))) {
+ throw new PakeError(
+ `Local directory "${url}" has no ${entryFile} at its root.`,
+ {
+ code: 'INVALID_INPUT',
+ hint: 'Point Pake at the built output directory that contains index.html.',
+ },
);
}
-
- tauriConf.pake.windows[0].url = fileName;
+ logger.info(`✺ Packaging local directory: ${url}`);
+ await stageLocalTree(url);
+ tauriConf.pake.windows[0].url = entryFile;
tauriConf.pake.windows[0].url_type = 'local';
+ return;
+ }
+
+ logger.info(`✺ Packaging local file: ${url}`);
+
+ const fileName = path.basename(url);
+ const distDir = path.join(npmDirectory, 'dist');
+
+ if (!useLocalFile) {
+ const urlPath = path.join(distDir, fileName);
+ await fsExtra.copy(url, urlPath);
} else {
- tauriConf.pake.windows[0].url_type = 'web';
+ await stageLocalTree(path.dirname(url));
}
+
+ tauriConf.pake.windows[0].url = fileName;
+ tauriConf.pake.windows[0].url_type = 'local';
}
export function buildLinuxDesktopContent(
diff --git a/bin/options/icon.ts b/bin/options/icon.ts
index 9346f441..5033a5d7 100644
--- a/bin/options/icon.ts
+++ b/bin/options/icon.ts
@@ -409,8 +409,8 @@ export async function handleIcon(
}
}
- // Try favicon from website
- if (url && options.name) {
+ // Try favicon from website; local file/directory input has no favicon.
+ if (url && options.name && /^https?:\/\//i.test(url)) {
const faviconPath = await tryGetFavicon(url, options.name);
if (faviconPath) return faviconPath;
}
diff --git a/bin/options/index.ts b/bin/options/index.ts
index f499bfd6..8b9642a5 100644
--- a/bin/options/index.ts
+++ b/bin/options/index.ts
@@ -11,6 +11,7 @@ import {
} from '@/utils/info';
import { generateLinuxPackageName } from '@/utils/name';
import { PakeError } from '@/utils/error';
+import { isInteractive } from '@/utils/output';
import { PakeAppOptions, PakeCliOptions } from '@/types';
function resolveAppName(name: string, platform: NodeJS.Platform): string {
@@ -55,9 +56,13 @@ export default async function handleOptions(
const defaultName = pathExists
? resolveLocalAppName(url, platform)
: resolveAppName(url, platform);
- const promptMessage = 'Enter your application name';
- const namePrompt = await promptText(promptMessage, defaultName);
- name = namePrompt?.trim() || defaultName;
+ if (isInteractive()) {
+ const promptMessage = 'Enter your application name';
+ const namePrompt = await promptText(promptMessage, defaultName);
+ name = namePrompt?.trim() || defaultName;
+ } else {
+ name = defaultName;
+ }
}
if (name && platform === 'linux') {
diff --git a/bin/types.ts b/bin/types.ts
index 7e67b460..068c11bf 100644
--- a/bin/types.ts
+++ b/bin/types.ts
@@ -72,6 +72,12 @@ export interface PakeCliOptions {
// Debug mode, outputs more logs
debug: boolean;
+ // Machine-readable mode: logs go to stderr, stdout carries one JSON result, default false
+ json: boolean;
+
+ // Path to a JSON config file whose fields mirror CLI options plus url
+ config?: string;
+
/** External scripts that need to be injected into the page. */
inject: string[];
diff --git a/bin/utils/error.ts b/bin/utils/error.ts
index db641206..1bb78307 100644
--- a/bin/utils/error.ts
+++ b/bin/utils/error.ts
@@ -1,17 +1,27 @@
+import type { PakeErrorCode } from './output';
+
/**
* 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
+ * stack trace and exits with the code mapped from `code` (see
+ * ERROR_EXIT_CODES in utils/output.ts). Use this for predictable failures
* (invalid names, missing files, etc.) so users see a clean message instead
- * of a Node.js stack dump.
+ * of a Node.js stack dump. `code` and `hint` also feed the `--json` result.
*/
export class PakeError extends Error {
readonly isUserError = true;
+ readonly code?: PakeErrorCode;
+ readonly hint?: string;
- constructor(message: string) {
+ constructor(
+ message: string,
+ options?: { code?: PakeErrorCode; hint?: string },
+ ) {
super(message);
this.name = 'PakeError';
+ this.code = options?.code;
+ this.hint = options?.hint;
}
}
diff --git a/bin/utils/info.ts b/bin/utils/info.ts
index 6c15828b..e6172230 100644
--- a/bin/utils/info.ts
+++ b/bin/utils/info.ts
@@ -2,6 +2,7 @@ import crypto from 'crypto';
import prompts from 'prompts';
import ora from 'ora';
import chalk from 'chalk';
+import { isMachineMode } from './output';
// Generates a stable identifier based on the app URL (and optionally name).
// When name is provided it is included in the hash so two apps wrapping
@@ -62,5 +63,7 @@ export function getSpinner(text: string) {
text: `${chalk.cyan(text)}\n`,
spinner: loadingType,
color: 'cyan',
+ // In machine mode stdout must stay parseable and stderr low-noise.
+ isSilent: isMachineMode(),
}).start();
}
diff --git a/bin/utils/output.ts b/bin/utils/output.ts
new file mode 100644
index 00000000..6c91ec4d
--- /dev/null
+++ b/bin/utils/output.ts
@@ -0,0 +1,96 @@
+import chalk from 'chalk';
+import log from 'loglevel';
+
+/**
+ * Machine-readable output support (`--json`).
+ *
+ * In machine mode stdout carries exactly one JSON result object; every log,
+ * spinner, and subprocess output is routed to stderr so automation and AI
+ * agents can `JSON.parse(stdout)` without scraping terminal text.
+ */
+
+export type PakeErrorCode =
+ | 'INVALID_INPUT'
+ | 'ENV_MISSING'
+ | 'BUILD_FAILED'
+ | 'NETWORK'
+ | 'UNEXPECTED';
+
+// Stable exit-code contract: 0 success, 2 invalid input, 3 build/network
+// failure, 4 missing environment, 1 unexpected. Documented in cli-usage docs.
+export const ERROR_EXIT_CODES: Record<PakeErrorCode, number> = {
+ INVALID_INPUT: 2,
+ BUILD_FAILED: 3,
+ NETWORK: 3,
+ ENV_MISSING: 4,
+ UNEXPECTED: 1,
+};
+
+export interface BuildArtifact {
+ path: string;
+ sizeBytes: number;
+ format: string;
+}
+
+export interface PakeJsonResult {
+ ok: boolean;
+ name: string | null;
+ platform: NodeJS.Platform;
+ arch: string | null;
+ outputs: BuildArtifact[];
+ warnings: string[];
+ error: {
+ code: PakeErrorCode;
+ message: string;
+ hint: string | null;
+ } | null;
+}
+
+let machineMode = false;
+const capturedWarnings: string[] = [];
+
+/**
+ * Route all loglevel output to stderr, capture warnings for the final JSON
+ * result, and strip ANSI colors. Must be called before any logging happens.
+ */
+export function enableMachineMode(): void {
+ if (machineMode) return;
+ machineMode = true;
+ chalk.level = 0;
+ log.methodFactory = (methodName) => {
+ return (...args: unknown[]) => {
+ if (methodName === 'warn') {
+ capturedWarnings.push(args.map(String).join(' '));
+ }
+ console.error(...args);
+ };
+ };
+ // Rebuild logging methods with the new factory.
+ log.setLevel(log.getLevel());
+}
+
+export function isMachineMode(): boolean {
+ return machineMode;
+}
+
+export function getCapturedWarnings(): string[] {
+ return [...capturedWarnings];
+}
+
+/**
+ * Whether Pake may prompt the user. False in machine mode, without a TTY,
+ * or inside CI, where prompts would hang or produce garbage.
+ */
+export function isInteractive(): boolean {
+ return (
+ !machineMode &&
+ Boolean(process.stdin.isTTY) &&
+ Boolean(process.stdout.isTTY) &&
+ !process.env.CI &&
+ !process.env.GITHUB_ACTIONS
+ );
+}
+
+export function printJsonResult(result: PakeJsonResult): void {
+ process.stdout.write(`${JSON.stringify(result)}\n`);
+}
diff --git a/bin/utils/shell.ts b/bin/utils/shell.ts
index 1c87d83f..cc141fcf 100644
--- a/bin/utils/shell.ts
+++ b/bin/utils/shell.ts
@@ -1,5 +1,6 @@
import { execa } from 'execa';
import { npmDirectory } from './dir';
+import { isMachineMode } from './output';
export async function shellExec(
command: string,
@@ -11,7 +12,11 @@ export async function shellExec(
cwd: npmDirectory,
// Use 'inherit' to show all output directly to user in real-time.
// This ensures linuxdeploy and other tool outputs are visible during builds.
- stdio: 'inherit',
+ // In machine mode (--json) stdout is reserved for the final JSON result,
+ // so subprocess stdout is rerouted to stderr instead.
+ stdin: 'inherit',
+ stdout: isMachineMode() ? process.stderr : 'inherit',
+ stderr: 'inherit',
shell: true,
timeout,
env: env ? { ...process.env, ...env } : process.env,
diff --git a/bin/utils/validate.ts b/bin/utils/validate.ts
index 3ed66d68..df769119 100644
--- a/bin/utils/validate.ts
+++ b/bin/utils/validate.ts
@@ -16,10 +16,20 @@ export function validateNumberInput(value: string) {
return parsedValue;
}
+// Path-shaped input (./x, ../x, /x, ~/x, C:\x). A missing path must fail
+// loudly: appending https:// to "./typo" would otherwise produce a valid URL
+// like https://./typo and a silently broken app (worst case for agents).
+const PATH_LIKE_PATTERN = /^(\.{1,2}[\\/]|[\\/]|~[\\/]|[a-zA-Z]:[\\/])/;
+
export function validateUrlInput(url: string) {
const isFile = fs.existsSync(url);
if (!isFile) {
+ if (PATH_LIKE_PATTERN.test(url)) {
+ throw new InvalidArgumentError(
+ `Local path "${url}" does not exist. Check the path, or pass a web URL instead.`,
+ );
+ }
try {
return normalizeUrl(url);
} catch (error) {
diff --git a/dist/cli.js b/dist/cli.js
index 92d2304d..0c00a516 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -172,6 +172,58 @@ let tauriConfig = {
pake: pakeConf,
};
+// Stable exit-code contract: 0 success, 2 invalid input, 3 build/network
+// failure, 4 missing environment, 1 unexpected. Documented in cli-usage docs.
+const ERROR_EXIT_CODES = {
+ INVALID_INPUT: 2,
+ BUILD_FAILED: 3,
+ NETWORK: 3,
+ ENV_MISSING: 4,
+ UNEXPECTED: 1,
+};
+let machineMode = false;
+const capturedWarnings = [];
+/**
+ * Route all loglevel output to stderr, capture warnings for the final JSON
+ * result, and strip ANSI colors. Must be called before any logging happens.
+ */
+function enableMachineMode() {
+ if (machineMode)
+ return;
+ machineMode = true;
+ chalk.level = 0;
+ log.methodFactory = (methodName) => {
+ return (...args) => {
+ if (methodName === 'warn') {
+ capturedWarnings.push(args.map(String).join(' '));
+ }
+ console.error(...args);
+ };
+ };
+ // Rebuild logging methods with the new factory.
+ log.setLevel(log.getLevel());
+}
+function isMachineMode() {
+ return machineMode;
+}
+function getCapturedWarnings() {
+ return [...capturedWarnings];
+}
+/**
+ * Whether Pake may prompt the user. False in machine mode, without a TTY,
+ * or inside CI, where prompts would hang or produce garbage.
+ */
+function isInteractive() {
+ return (!machineMode &&
+ Boolean(process.stdin.isTTY) &&
+ Boolean(process.stdout.isTTY) &&
+ !process.env.CI &&
+ !process.env.GITHUB_ACTIONS);
+}
+function printJsonResult(result) {
+ process.stdout.write(`${JSON.stringify(result)}\n`);
+}
+
// Generates a stable identifier based on the app URL (and optionally name).
// When name is provided it is included in the hash so two apps wrapping
// the same URL can coexist. Omitting name preserves backward compatibility
@@ -217,6 +269,8 @@ function getSpinner(text) {
text: `${chalk.cyan(text)}\n`,
spinner: loadingType,
color: 'cyan',
+ // In machine mode stdout must stay parseable and stderr low-noise.
+ isSilent: isMachineMode(),
}).start();
}
@@ -324,7 +378,11 @@ async function shellExec(command, timeout = 300000, env) {
cwd: npmDirectory,
// Use 'inherit' to show all output directly to user in real-time.
// This ensures linuxdeploy and other tool outputs are visible during builds.
- stdio: 'inherit',
+ // In machine mode (--json) stdout is reserved for the final JSON result,
+ // so subprocess stdout is rerouted to stderr instead.
+ stdin: 'inherit',
+ stdout: isMachineMode() ? process.stderr : 'inherit',
+ stderr: 'inherit',
shell: true,
timeout,
env: env ? { ...process.env, ...env } : process.env,
@@ -502,6 +560,31 @@ function generateIdentifierSafeName(name) {
return cleaned;
}
+/**
+ * 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 the code mapped from `code` (see
+ * ERROR_EXIT_CODES in utils/output.ts). Use this for predictable failures
+ * (invalid names, missing files, etc.) so users see a clean message instead
+ * of a Node.js stack dump. `code` and `hint` also feed the `--json` result.
+ */
+class PakeError extends Error {
+ constructor(message, options) {
+ super(message);
+ this.isUserError = true;
+ this.name = 'PakeError';
+ this.code = options?.code;
+ this.hint = options?.hint;
+ }
+}
+function isPakeError(error) {
+ return (error instanceof PakeError ||
+ (typeof error === 'object' &&
+ error !== null &&
+ error.isUserError === true));
+}
+
const LINUX_TARGET_TYPES = ['deb', 'appimage', 'rpm', 'zst'];
// Returns the valid Linux build targets from a comma-separated targets
// string, preserving LINUX_TARGET_TYPES order. Unknown entries are dropped.
@@ -589,30 +672,60 @@ async function copyTemplateConfigs() {
}
}));
}
+// Replace the CLI's own dist/ with the user's static files while keeping the
+// build artifacts (cli.js) the packaged app does not need but the CLI does.
+// dist_bak always holds the ORIGINAL package dist: once it exists, later
+// stagings must not overwrite it with a previous user tree, or the original
+// files would be unrecoverable across repeated local builds.
+async function stageLocalTree(sourceDir) {
+ const distDir = path.join(npmDirectory, 'dist');
+ const distBakDir = path.join(npmDirectory, 'dist_bak');
+ if (await fsExtra.pathExists(distBakDir)) {
+ fsExtra.removeSync(distDir);
+ }
+ else {
+ fsExtra.moveSync(distDir, distBakDir);
+ }
+ fsExtra.copySync(sourceDir, distDir, { overwrite: true });
+ const filesToCopyBack = ['cli.js'];
+ await Promise.all(filesToCopyBack.map((file) => fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file))));
+}
+// Exported for unit tests (web fallback and directory entry guard).
async function handleLocalFile(url, useLocalFile, tauriConf) {
const pathExists = await fsExtra.pathExists(url);
- if (pathExists) {
- logger.warn('✼ Your input might be a local file.');
- const fileName = path.basename(url);
- const dirName = path.dirname(url);
- const distDir = path.join(npmDirectory, 'dist');
- const distBakDir = path.join(npmDirectory, 'dist_bak');
- if (!useLocalFile) {
- const urlPath = path.join(distDir, fileName);
- await fsExtra.copy(url, urlPath);
- }
- else {
- fsExtra.moveSync(distDir, distBakDir, { overwrite: true });
- fsExtra.copySync(dirName, distDir, { overwrite: true });
- const filesToCopyBack = ['cli.js'];
- await Promise.all(filesToCopyBack.map((file) => fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file))));
+ if (!pathExists) {
+ tauriConf.pake.windows[0].url_type = 'web';
+ return;
+ }
+ const stat = await fsExtra.stat(url);
+ if (stat.isDirectory()) {
+ // A directory of static web assets (e.g. a generated dist/): the whole
+ // tree is packaged and the app entry is its root index.html.
+ const entryFile = 'index.html';
+ if (!(await fsExtra.pathExists(path.join(url, entryFile)))) {
+ throw new PakeError(`Local directory "${url}" has no ${entryFile} at its root.`, {
+ code: 'INVALID_INPUT',
+ hint: 'Point Pake at the built output directory that contains index.html.',
+ });
}
- tauriConf.pake.windows[0].url = fileName;
+ logger.info(`✺ Packaging local directory: ${url}`);
+ await stageLocalTree(url);
+ tauriConf.pake.windows[0].url = entryFile;
tauriConf.pake.windows[0].url_type = 'local';
+ return;
+ }
+ logger.info(`✺ Packaging local file: ${url}`);
+ const fileName = path.basename(url);
+ const distDir = path.join(npmDirectory, 'dist');
+ if (!useLocalFile) {
+ const urlPath = path.join(distDir, fileName);
+ await fsExtra.copy(url, urlPath);
}
else {
- tauriConf.pake.windows[0].url_type = 'web';
+ await stageLocalTree(path.dirname(url));
}
+ tauriConf.pake.windows[0].url = fileName;
+ tauriConf.pake.windows[0].url_type = 'local';
}
function buildLinuxDesktopContent(name, title, linuxBinaryName) {
const chineseName = title && /[\u4e00-\u9fa5]/.test(title) ? title : null;
@@ -1048,8 +1161,61 @@ const APPIMAGE_FAILURE_GUIDANCE = `\n\n${APPIMAGE_BAR}\n` +
APPIMAGE_BAR;
class BaseBuilder {
constructor(options) {
+ this.artifacts = [];
this.options = options;
}
+ /** Final artifacts produced by this build, for the `--json` result. */
+ getArtifacts() {
+ return [...this.artifacts];
+ }
+ /** Architecture reported in the `--json` result. */
+ getReportArch() {
+ return this.options.multiArch ? 'universal' : process.arch;
+ }
+ // Drop a recorded artifact whose file was later removed (e.g. the
+ // temporary .deb consumed by zst repacking), so --json never lists a
+ // path that no longer exists.
+ removeArtifact(artifactPath) {
+ const resolved = path.resolve(artifactPath);
+ this.artifacts = this.artifacts.filter((artifact) => artifact.path !== resolved);
+ }
+ async recordArtifact(artifactPath, format) {
+ try {
+ const stat = await fsExtra.stat(artifactPath);
+ let sizeBytes = stat.size;
+ if (stat.isDirectory()) {
+ sizeBytes = await BaseBuilder.getPathSize(artifactPath);
+ }
+ this.artifacts.push({
+ path: path.resolve(artifactPath),
+ sizeBytes,
+ format,
+ });
+ }
+ catch {
+ // Never fail a finished build over size bookkeeping.
+ this.artifacts.push({
+ path: path.resolve(artifactPath),
+ sizeBytes: 0,
+ format,
+ });
+ }
+ }
+ static async getPathSize(directory) {
+ let size = 0;
+ for (const entry of await fsExtra.readdir(directory, {
+ withFileTypes: true,
+ })) {
+ const entryPath = path.join(directory, entry.name);
+ if (entry.isDirectory()) {
+ size += await BaseBuilder.getPathSize(entryPath);
+ }
+ else if (entry.isFile()) {
+ size += (await fsExtra.stat(entryPath)).size;
+ }
+ }
+ return size;
+ }
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
const tauriTargetPath = path.join(tauriSrcPath, 'target');
@@ -1060,6 +1226,12 @@ class BaseBuilder {
}
ensureRustEnv();
if (!checkRustInstalled()) {
+ if (!isInteractive()) {
+ throw new PakeError('Rust required to package your webapp.', {
+ code: 'ENV_MISSING',
+ hint: 'Install Rust via https://rustup.rs, then rerun the same command.',
+ });
+ }
const res = await prompts({
type: 'confirm',
message: 'Rust not detected. Install now?',
@@ -1069,8 +1241,10 @@ class BaseBuilder {
await installRust();
}
else {
- logger.error('✕ Rust required to package your webapp.');
- process.exit(1);
+ throw new PakeError('Rust required to package your webapp.', {
+ code: 'ENV_MISSING',
+ hint: 'Install Rust via https://rustup.rs, then rerun the same command.',
+ });
}
}
const spinner = getSpinner('Installing package...');
@@ -1129,8 +1303,9 @@ class BaseBuilder {
// Let spinner run for a moment so user can see it, then stop before package manager command
await new Promise((resolve) => setTimeout(resolve, 500));
buildSpinner.stop();
- // Show static message to keep the status visible
- logger.warn('✸ Building app...');
+ // Show static message to keep the status visible. Info, not warn: warn
+ // entries feed the --json warnings array and this is a status line.
+ logger.info('✸ Building app...');
const baseEnv = getBuildEnvironment();
let buildEnv = {
...(baseEnv ?? {}),
@@ -1174,6 +1349,7 @@ class BaseBuilder {
// executable the build produced instead.
if (this.options.bundle === false) {
await this.copyRawBinary(npmDirectory, name);
+ await this.recordArtifact(this.getRawBinaryPath(name), 'binary');
if (logSuccess) {
logger.success('✔ Build success!');
logger.success('✔ Raw binary located in', path.resolve(this.getRawBinaryPath(name)));
@@ -1186,9 +1362,11 @@ class BaseBuilder {
const appPath = this.getBuildAppPath(npmDirectory, fileName, fileType);
const distPath = path.resolve(`${name}.${fileType}`);
await fsExtra.copy(appPath, distPath);
+ await this.recordArtifact(distPath, fileType);
// Copy raw binary if requested
if (this.options.keepBinary) {
await this.copyRawBinary(npmDirectory, name);
+ await this.recordArtifact(this.getRawBinaryPath(name), 'binary');
}
await fsExtra.remove(appPath);
if (logSuccess) {
@@ -1215,6 +1393,13 @@ class BaseBuilder {
// fsExtra.move uses fs.rename (atomic on same filesystem) and falls back
// to copy+remove only when moving across volumes.
await fsExtra.move(appBundlePath, appDest, { overwrite: true });
+ // Keep the JSON result pointing at where the artifact actually lives.
+ const movedFrom = path.resolve(appBundlePath);
+ for (const artifact of this.artifacts) {
+ if (artifact.path === movedFrom) {
+ artifact.path = appDest;
+ }
+ }
logger.success(`✔ ${appBundleName.replace(/\.app$/, '')} installed to /Applications`);
}
catch (error) {
@@ -1430,6 +1615,9 @@ class MacBuilder extends BaseBuilder {
}
return `${name}_${tauriConfig.version}_${arch}`;
}
+ getReportArch() {
+ return this.getActualArch();
+ }
getActualArch() {
if (this.buildArch === 'universal' || this.options.multiArch) {
return 'universal';
@@ -1483,6 +1671,9 @@ class WinBuilder extends BaseBuilder {
: this.resolveTargetArch('auto');
this.options.targets = this.buildFormat;
}
+ getReportArch() {
+ return this.buildArch;
+ }
getFileName() {
const { name } = this.options;
const language = tauriConfig.bundle.windows.wix.language[0];
@@ -1538,6 +1729,9 @@ class LinuxBuilder extends BaseBuilder {
}
this.options.targets = this.buildFormat;
}
+ getReportArch() {
+ return this.buildArch;
+ }
getFileName() {
const { name = 'pake-app', targets } = this.options;
const version = tauriConfig.version;
@@ -1686,12 +1880,14 @@ post_remove() {
}
`);
await shellExec(`bsdtar --zstd -cf "${packagePath}" -C "${dataDir}" .PKGINFO .INSTALL usr`);
+ await this.recordArtifact(packagePath, 'zst');
logger.success('✔ Build success!');
logger.success('✔ App installer located in', packagePath);
}
finally {
if (removeSourceDeb) {
await fsExtra.remove(debPath);
+ this.removeArtifact(debPath);
}
await fsExtra.remove(workDir);
}
@@ -2389,8 +2585,8 @@ async function handleIcon(options, url) {
return localIconPath;
}
}
- // Try favicon from website
- if (url && options.name) {
+ // Try favicon from website; local file/directory input has no favicon.
+ if (url && options.name && /^https?:\/\//i.test(url)) {
const faviconPath = await tryGetFavicon(url, options.name);
if (faviconPath)
return faviconPath;
@@ -2633,28 +2829,6 @@ function safeDomainsToRegex(domains) {
: '';
}
-/**
- * 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;
@@ -2686,9 +2860,14 @@ async function handleOptions(options, url) {
const defaultName = pathExists
? resolveLocalAppName(url, platform)
: resolveAppName(url, platform);
- const promptMessage = 'Enter your application name';
- const namePrompt = await promptText(promptMessage, defaultName);
- name = namePrompt?.trim() || defaultName;
+ if (isInteractive()) {
+ const promptMessage = 'Enter your application name';
+ const namePrompt = await promptText(promptMessage, defaultName);
+ name = namePrompt?.trim() || defaultName;
+ }
+ else {
+ name = defaultName;
+ }
}
if (name && platform === 'linux') {
name = generateLinuxPackageName(name);
@@ -2732,6 +2911,7 @@ const DEFAULT_PAKE_OPTIONS = {
width: 1200,
fullscreen: false,
maximize: false,
+ resizable: true,
hideTitleBar: false,
hideWindowDecorations: false,
alwaysOnTop: false,
@@ -2758,6 +2938,7 @@ const DEFAULT_PAKE_OPTIONS = {
systemTrayIcon: '',
proxyUrl: '',
debug: false,
+ json: false,
inject: [],
installerLanguage: 'en-US',
hideOnClose: undefined, // Platform-specific: true for macOS, false for others
@@ -2797,9 +2978,16 @@ function validateNumberInput(value) {
}
return parsedValue;
}
+// Path-shaped input (./x, ../x, /x, ~/x, C:\x). A missing path must fail
+// loudly: appending https:// to "./typo" would otherwise produce a valid URL
+// like https://./typo and a silently broken app (worst case for agents).
+const PATH_LIKE_PATTERN = /^(\.{1,2}[\\/]|[\\/]|~[\\/]|[a-zA-Z]:[\\/])/;
function validateUrlInput(url) {
const isFile = fs.existsSync(url);
if (!isFile) {
+ if (PATH_LIKE_PATTERN.test(url)) {
+ throw new InvalidArgumentError(`Local path "${url}" does not exist. Check the path, or pass a web URL instead.`);
+ }
try {
return normalizeUrl(url);
}
@@ -2849,6 +3037,8 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
return previous ? [...previous, ...files] : files;
}, DEFAULT_PAKE_OPTIONS.inject)
.option('--debug', 'Debug build and more output', DEFAULT_PAKE_OPTIONS.debug)
+ .option('--json', 'Machine-readable output: logs to stderr, one JSON result on stdout', DEFAULT_PAKE_OPTIONS.json)
+ .option('--config <path>', 'Load options from a JSON config file (fields mirror CLI options, see schema/pake.schema.json)')
.addOption(new Option('--proxy-url <url>', 'Proxy URL for all network requests (http://, https://, socks5://)')
.default(DEFAULT_PAKE_OPTIONS.proxyUrl)
.hideHelp())
@@ -2981,16 +3171,181 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
});
}
+// Invocation concerns, not app manifest fields; pass these as CLI flags.
+const REJECTED_KEYS = new Set(['config', 'json', 'version']);
+// Optional CLI options that have no entry in DEFAULT_PAKE_OPTIONS.
+const EXTRA_STRING_KEYS = new Set(['name', 'title', 'identifier']);
+function expectedTypeFor(key) {
+ if (key === 'inject')
+ return 'string[]';
+ if (key === 'hideOnClose')
+ return 'boolean';
+ if (EXTRA_STRING_KEYS.has(key))
+ return 'string';
+ const defaultValue = DEFAULT_PAKE_OPTIONS[key];
+ const type = typeof defaultValue;
+ if (type === 'string' || type === 'number' || type === 'boolean') {
+ return type;
+ }
+ return null;
+}
+function matchesType(value, type) {
+ if (type === 'string[]') {
+ return Array.isArray(value) && value.every((v) => typeof v === 'string');
+ }
+ return typeof value === type;
+}
+async function loadConfigFile(configPath, validKeys) {
+ if (!(await fsExtra.pathExists(configPath))) {
+ throw new PakeError(`Config file not found: ${configPath}`, {
+ code: 'INVALID_INPUT',
+ hint: 'Pass a path to a JSON file matching schema/pake.schema.json.',
+ });
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(await fsExtra.readFile(configPath, 'utf8'));
+ }
+ catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ throw new PakeError(`Config file is not valid JSON: ${detail}`, {
+ code: 'INVALID_INPUT',
+ hint: `Fix the JSON syntax in ${configPath}.`,
+ });
+ }
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ throw new PakeError('Config file must contain a JSON object.', {
+ code: 'INVALID_INPUT',
+ hint: 'See schema/pake.schema.json for the expected shape.',
+ });
+ }
+ const result = { options: {} };
+ for (const [key, value] of Object.entries(parsed)) {
+ if (key === '$schema')
+ continue;
+ if (key === 'url') {
+ if (typeof value !== 'string') {
+ throw new PakeError('Config field "url" must be a string.', {
+ code: 'INVALID_INPUT',
+ hint: 'Use a web URL or a local file/directory path.',
+ });
+ }
+ result.url = value;
+ continue;
+ }
+ if (REJECTED_KEYS.has(key)) {
+ throw new PakeError(`Config field "${key}" is not allowed in a config file.`, {
+ code: 'INVALID_INPUT',
+ hint: `Pass --${key} on the command line instead.`,
+ });
+ }
+ if (!validKeys.has(key)) {
+ throw new PakeError(`Unknown config field "${key}".`, {
+ code: 'INVALID_INPUT',
+ hint: 'Field names are camelCase CLI option names; see schema/pake.schema.json.',
+ });
+ }
+ const expected = expectedTypeFor(key);
+ if (expected && !matchesType(value, expected)) {
+ throw new PakeError(`Config field "${key}" must be of type ${expected}.`, {
+ code: 'INVALID_INPUT',
+ hint: 'See schema/pake.schema.json for field types.',
+ });
+ }
+ if (!expected && (typeof value === 'object' || value === null)) {
+ throw new PakeError(`Config field "${key}" must be a string, number, or boolean.`, {
+ code: 'INVALID_INPUT',
+ hint: 'See schema/pake.schema.json for field types.',
+ });
+ }
+ result.options[key] = value;
+ }
+ return result;
+}
+
const program = getCliProgram();
+// Make commander throw instead of exiting so option/argument parse errors
+// honor the exit-code contract (2 = invalid input) and still emit the JSON
+// result object when --json was requested.
+program.exitOverride();
+function isCommanderExit(error) {
+ return (typeof error === 'object' &&
+ error !== null &&
+ typeof error.code === 'string' &&
+ error.code.startsWith('commander.'));
+}
+const PHASE_ERROR_CODES = {
+ input: 'INVALID_INPUT',
+ prepare: 'ENV_MISSING',
+ build: 'BUILD_FAILED',
+};
+function classifyError(error, phase) {
+ if (isPakeError(error)) {
+ return {
+ code: error.code ?? PHASE_ERROR_CODES[phase],
+ message: error.message,
+ hint: error.hint ?? null,
+ };
+ }
+ if (error instanceof Error) {
+ return {
+ code: PHASE_ERROR_CODES[phase],
+ message: error.message,
+ hint: null,
+ };
+ }
+ return {
+ code: 'UNEXPECTED',
+ message: `Unexpected error: ${String(error)}`,
+ hint: null,
+ };
+}
async function checkUpdateTips() {
updateNotifier({ pkg: packageJson, updateCheckInterval: 1000 * 60 }).notify({
isGlobal: true,
});
}
-program.action(async (url, options) => {
+program.action(async (urlArg, options) => {
+ const jsonMode = Boolean(options.json);
+ if (jsonMode) {
+ enableMachineMode();
+ }
+ let phase = 'input';
+ let appName = null;
+ let url = urlArg;
try {
- await checkUpdateTips();
+ if (!jsonMode) {
+ await checkUpdateTips();
+ }
+ // Config file fills in whatever the command line did not set explicitly:
+ // CLI flag > config field > built-in default.
+ if (options.config) {
+ const validKeys = new Set(program.options.map((option) => option.attributeName()));
+ const loaded = await loadConfigFile(options.config, validKeys);
+ for (const [key, value] of Object.entries(loaded.options)) {
+ if (program.getOptionValueSource(key) !== 'cli') {
+ options[key] = value;
+ }
+ }
+ if (!url && loaded.url) {
+ try {
+ url = validateUrlInput(loaded.url);
+ }
+ catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ throw new PakeError(`Invalid "url" in config file: ${detail}`, {
+ code: 'INVALID_INPUT',
+ });
+ }
+ }
+ }
if (!url) {
+ if (jsonMode) {
+ throw new PakeError('No URL or local path to package.', {
+ code: 'INVALID_INPUT',
+ hint: 'Pass a URL/path argument or a config file with a "url" field.',
+ });
+ }
program.help({
error: false,
});
@@ -3002,13 +3357,47 @@ program.action(async (url, options) => {
log.setLevel('debug');
}
const appOptions = await handleOptions(options, url);
+ appName = appOptions.name ?? null;
const builder = BuilderProvider.create(appOptions);
+ phase = 'prepare';
await builder.prepare();
+ phase = 'build';
await builder.build(url);
+ if (jsonMode) {
+ printJsonResult({
+ ok: true,
+ name: appName,
+ platform: process.platform,
+ arch: builder.getReportArch(),
+ outputs: builder.getArtifacts(),
+ warnings: getCapturedWarnings(),
+ error: null,
+ });
+ }
}
catch (error) {
- if (isPakeError(error)) {
- console.error(chalk.red(error.message));
+ // program.help() and --help/--version throw under exitOverride with
+ // exitCode 0; a clean commander exit is not a failure.
+ if (isCommanderExit(error) && error.exitCode === 0) {
+ process.exit(0);
+ }
+ const classified = classifyError(error, phase);
+ if (jsonMode) {
+ printJsonResult({
+ ok: false,
+ name: appName,
+ platform: process.platform,
+ arch: null,
+ outputs: [],
+ warnings: getCapturedWarnings(),
+ error: classified,
+ });
+ }
+ else if (isPakeError(error)) {
+ console.error(chalk.red(classified.message));
+ if (classified.hint) {
+ console.error(chalk.yellow(`✼ ${classified.hint}`));
+ }
}
else if (error instanceof Error) {
console.error(chalk.red(`✕ ${error.message}`));
@@ -3019,10 +3408,35 @@ program.action(async (url, options) => {
else {
console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));
}
- process.exit(1);
+ process.exit(ERROR_EXIT_CODES[classified.code]);
}
});
program.parseAsync().catch((error) => {
+ if (isCommanderExit(error)) {
+ // --help / --version and friends exit clean; commander already printed.
+ if (error.exitCode === 0) {
+ process.exit(0);
+ }
+ // Parse errors (unknown option, invalid argument, missing value) are
+ // invalid input. Commander already printed the message to stderr; in
+ // json mode also emit the machine-readable result on stdout.
+ if (process.argv.includes('--json')) {
+ printJsonResult({
+ ok: false,
+ name: null,
+ platform: process.platform,
+ arch: null,
+ outputs: [],
+ warnings: [],
+ error: {
+ code: 'INVALID_INPUT',
+ message: error.message.trim(),
+ hint: 'Run pake --help for the accepted options.',
+ },
+ });
+ }
+ process.exit(ERROR_EXIT_CODES.INVALID_INPUT);
+ }
if (error instanceof Error) {
console.error(chalk.red(`✕ ${error.message}`));
}
diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md
index a446bde0..fadce458 100644
--- a/docs/advanced-usage.md
+++ b/docs/advanced-usage.md
@@ -123,10 +123,15 @@ Configure window properties in `pake.json`:
Package local HTML/CSS/JS files:
```bash
+# A whole directory of static files (must contain index.html at its root),
+# e.g. the dist/ output of a web build. The full tree is packaged.
+pake ./dist --name my-tool
+
+# A single HTML file; add --use-local-file to also copy its sibling files
pake ./my-app/index.html --name my-static-app --use-local-file
```
-Requirements: Pake CLI >= 3.0.0
+Hash-based routing works out of the box; history-mode SPA routing is not yet supported for local packaging. Single-file packaging requires Pake CLI >= 3.0.0; directory packaging requires >= 3.15.0.
## macOS Media Permissions
@@ -137,8 +142,8 @@ pake https://chatgpt.com --name ChatGPT --microphone
pake https://meet.google.com --name GoogleMeet --camera --microphone
```
-- `--microphone` — grants microphone access (`com.apple.security.device.audio-input`)
-- `--camera` — grants camera access (`com.apple.security.device.camera`)
+- `--microphone`: grants microphone access (`com.apple.security.device.audio-input`)
+- `--camera`: grants camera access (`com.apple.security.device.camera`)
macOS will prompt the user for permission on first use. Only add these flags for sites that actually need them.
diff --git a/docs/advanced-usage_CN.md b/docs/advanced-usage_CN.md
index 15bc1c3e..6b1ab8f0 100644
--- a/docs/advanced-usage_CN.md
+++ b/docs/advanced-usage_CN.md
@@ -123,10 +123,15 @@ fn handle_scroll(scroll_y: f64, scroll_x: f64) {
打包本地 HTML/CSS/JS 文件:
```bash
+# 打包整个静态文件目录(根目录必须有 index.html),
+# 例如前端构建产物 dist/,整个目录树都会被打进应用
+pake ./dist --name my-tool
+
+# 打包单个 HTML 文件;加 --use-local-file 可同时拷贝同级文件
pake ./my-app/index.html --name my-static-app --use-local-file
```
-要求:Pake CLI >= 3.0.0
+本地打包开箱支持 hash 路由,history 模式的 SPA 路由暂不支持。单文件打包要求 Pake CLI >= 3.0.0,目录打包要求 >= 3.15.0。
## macOS 摄像头与麦克风权限
@@ -137,8 +142,8 @@ pake https://chatgpt.com --name ChatGPT --microphone
pake https://meet.google.com --name GoogleMeet --camera --microphone
```
-- `--microphone` — 申请麦克风权限(`com.apple.security.device.audio-input`)
-- `--camera` — 申请摄像头权限(`com.apple.security.device.camera`)
+- `--microphone`: 申请麦克风权限(`com.apple.security.device.audio-input`)
+- `--camera`: 申请摄像头权限(`com.apple.security.device.camera`)
macOS 会在首次使用时向用户弹出权限确认对话框。请仅在确实需要的站点上添加这些标志。
diff --git a/docs/cli-usage.md b/docs/cli-usage.md
index d785262c..619f0498 100644
--- a/docs/cli-usage.md
+++ b/docs/cli-usage.md
@@ -66,7 +66,15 @@ The packaged application will be located in the current working directory by def
### [url]
-The URL is the link to the web page you want to package or the path to a local HTML file. This is mandatory.
+The URL is the link to the web page you want to package, the path to a local HTML file, or the path to a directory of static web files containing an `index.html` at its root (e.g. a `dist/` build output). Mandatory unless a `--config` file provides `url`.
+
+```shell
+pake https://example.com --name Example
+pake ./page.html --name MyPage
+pake ./dist --name MyTool
+```
+
+For local packaging, hash-based routing works out of the box; history-mode SPA routing is not yet supported.
### [options]
@@ -81,6 +89,8 @@ Various options are available for customization. `pake --help` shows every suppo
| `--hide-title-bar` | Immersive header (macOS only) | `--hide-title-bar` |
| `--hide-window-decorations` | Hide native window decorations (Windows/Linux only) | `--hide-window-decorations` |
| `--debug` | Enable development tools | `--debug` |
+| `--config` | Load options from a JSON config file | `--config app.json` |
+| `--json` | Machine-readable result on stdout (for automation) | `--json` |
| `--help` | Show all CLI options | `--help` |
| `--version` | Show CLI version | `--version` |
@@ -550,6 +560,8 @@ Set the Windows Installer language. Options include `zh-CN`, `ja-JP`, More at [T
Enable recursive copying. When the URL is a local file path, enabling this option will copy the folder containing the file specified in the URL, as well as all sub-files, to the Pake static folder. This is disabled by default.
+Directory inputs (`pake ./dist`) always package the full tree; this flag only affects single-HTML-file inputs.
+
```shell
--use-local-file
@@ -591,6 +603,44 @@ Enable developer tools and detailed logging for debugging.
--debug
```
+#### [config]
+
+Load options from a declarative JSON config file instead of assembling flags. Fields are the camelCase CLI option names plus `url`; the published schema is [schema/pake.schema.json](../schema/pake.schema.json). An explicit CLI flag always wins over a config field. Unknown fields and wrong types fail fast. Invocation flags (`--json`, `--config`, `--version`) are CLI-only and rejected inside the file.
+
+```shell
+--config <path>
+
+# app.json
+# {
+# "$schema": "https://raw.githubusercontent.com/tw93/Pake/main/schema/pake.schema.json",
+# "url": "https://example.com",
+# "name": "MyApp",
+# "width": 1280,
+# "hideTitleBar": true
+# }
+pake --config app.json
+```
+
+#### [json]
+
+Machine-readable mode for scripts and AI agents. All logs move to stderr and stdout carries exactly one JSON result object; interactive prompts are disabled (they are also disabled whenever stdin is not a TTY).
+
+```shell
+--json
+
+# Success (stdout):
+# {"ok":true,"name":"MyApp","platform":"darwin","arch":"arm64",
+# "outputs":[{"path":"/abs/MyApp.dmg","sizeBytes":5242880,"format":"dmg"}],
+# "warnings":[],"error":null}
+#
+# Failure (stdout):
+# {"ok":false, ..., "error":{"code":"ENV_MISSING","message":"...","hint":"..."}}
+```
+
+Exit codes: `0` success, `2` invalid input, `3` build failure, `4` missing environment or dependency setup failure (e.g. Rust not installed, package install failed), `1` unexpected error. Error codes: `INVALID_INPUT`, `ENV_MISSING`, `BUILD_FAILED`, `NETWORK`, `UNEXPECTED`.
+
+On Linux multi-target builds (e.g. `--targets deb,appimage`), `ok` can be true with fewer `outputs` than requested: a target that fails while others succeed is reported in `warnings`, not as a failure. Check `outputs[].format` against the formats you asked for.
+
#### [ignore-certificate-errors]
Ignore TLS certificate validation errors when loading the target URL. Useful for intranet apps, dev servers, or self-signed certificates.
diff --git a/docs/cli-usage_CN.md b/docs/cli-usage_CN.md
index e07128d3..65ba2fe1 100644
--- a/docs/cli-usage_CN.md
+++ b/docs/cli-usage_CN.md
@@ -66,7 +66,15 @@ pake [url] [options]
### [url]
-`url` 是您需要打包的网页链接 🔗 或本地 HTML 文件的路径,此参数为必填。
+`url` 是您需要打包的网页链接 🔗、本地 HTML 文件的路径,或包含根级 `index.html` 的静态文件目录(例如构建产物 `dist/`)。除非通过 `--config` 文件提供 `url`,此参数为必填。
+
+```shell
+pake https://example.com --name Example
+pake ./page.html --name MyPage
+pake ./dist --name MyTool
+```
+
+本地打包开箱支持 hash 路由;history 模式的 SPA 路由暂不支持。
### [options]
@@ -81,6 +89,8 @@ pake [url] [options]
| `--hide-title-bar` | 沉浸式标题栏(仅 macOS) | `--hide-title-bar` |
| `--hide-window-decorations` | 隐藏原生窗口装饰(仅 Windows/Linux) | `--hide-window-decorations` |
| `--debug` | 启用开发者工具 | `--debug` |
+| `--config` | 从 JSON 配置文件读取选项 | `--config app.json` |
+| `--json` | stdout 输出机器可读结果(自动化用) | `--json` |
| `--help` | 显示全部 CLI 选项 | `--help` |
| `--version` | 显示 CLI 版本 | `--version` |
@@ -548,6 +558,8 @@ pake https://chat.example.com --name ChatApp --multi-window
当 `url` 为本地文件路径时,如果启用此选项,则会递归地将 `url` 路径文件所在的文件夹及其所有子文件复制到 Pake 的静态文件夹。默认不启用。
+目录输入(`pake ./dist`)始终打包整个目录树,此选项只影响单个 HTML 文件输入。
+
```shell
--use-local-file
@@ -589,6 +601,44 @@ pake ./my-app/index.html --name "my-app" --use-local-file
--debug
```
+#### [config]
+
+用声明式 JSON 配置文件代替拼接命令行参数。字段名是 camelCase 的 CLI 选项名,外加 `url`;schema 见 [schema/pake.schema.json](../schema/pake.schema.json)。显式 CLI 参数始终优先于配置文件字段。未知字段与类型错误会立即报错。调用参数(`--json`、`--config`、`--version`)不允许写进配置文件。
+
+```shell
+--config <path>
+
+# app.json
+# {
+# "$schema": "https://raw.githubusercontent.com/tw93/Pake/main/schema/pake.schema.json",
+# "url": "https://example.com",
+# "name": "MyApp",
+# "width": 1280,
+# "hideTitleBar": true
+# }
+pake --config app.json
+```
+
+#### [json]
+
+面向脚本与 AI agent 的机器可读模式。所有日志改走 stderr,stdout 只输出一个 JSON 结果对象;交互式提示全部禁用(stdin 非 TTY 时同样禁用)。
+
+```shell
+--json
+
+# 成功(stdout):
+# {"ok":true,"name":"MyApp","platform":"darwin","arch":"arm64",
+# "outputs":[{"path":"/abs/MyApp.dmg","sizeBytes":5242880,"format":"dmg"}],
+# "warnings":[],"error":null}
+#
+# 失败(stdout):
+# {"ok":false, ..., "error":{"code":"ENV_MISSING","message":"...","hint":"..."}}
+```
+
+退出码:`0` 成功、`2` 输入非法、`3` 构建失败、`4` 环境缺失或依赖安装失败(如未安装 Rust、依赖安装出错)、`1` 未预期错误。错误码:`INVALID_INPUT`、`ENV_MISSING`、`BUILD_FAILED`、`NETWORK`、`UNEXPECTED`。
+
+Linux 多 target 构建(如 `--targets deb,appimage`)时,`ok` 为 true 不代表全部格式成功:单个 target 失败而其余成功会记入 `warnings`。请用 `outputs[].format` 核对拿到的格式是否齐全。
+
#### [ignore-certificate-errors]
忽略目标 URL 的 TLS 证书校验错误,适用于内网应用、开发环境、自签名证书。
diff --git a/llms.txt b/llms.txt
new file mode 100644
index 00000000..da73acd2
--- /dev/null
+++ b/llms.txt
@@ -0,0 +1,31 @@
+# Pake
+
+> Pake turns any webpage or local web build into a lightweight desktop app (~5MB) for macOS, Windows, and Linux, using Tauri (Rust) and the system webview. One CLI command packages a URL, a local HTML file, or a static directory into a native installer.
+
+## Install and run
+
+- Install: `npm install -g pake-cli` (requires Node 18+ and Rust; the CLI offers to install Rust when missing)
+- Basic: `pake https://example.com --name MyApp`
+- Local build output: `pake ./dist --name MyTool` (directory must contain index.html at its root; hash routing only, history-mode SPA routing unsupported)
+
+## Agent contract
+
+- Always pass `--json` in automation: stdout carries exactly one JSON object `{ok, name, platform, arch, outputs: [{path, sizeBytes, format}], warnings, error: {code, message, hint} | null}`; all logs go to stderr; interactive prompts are disabled.
+- Exit codes: 0 success, 2 invalid input, 3 build failure, 4 missing environment or dependency setup failure, 1 unexpected.
+- On Linux multi-target builds, ok:true can carry fewer outputs than requested formats; failed targets land in warnings. Check outputs[].format.
+- Error codes: INVALID_INPUT, ENV_MISSING, BUILD_FAILED, NETWORK, UNEXPECTED. `error.hint` states how to fix.
+- Declarative config: `pake --config app.json --json`; fields are camelCase CLI option names plus `url`. Explicit CLI flags win over config fields. Unknown fields fail fast.
+- Config schema: https://raw.githubusercontent.com/tw93/Pake/main/schema/pake.schema.json
+
+## Docs
+
+- [CLI usage, all options](https://github.com/tw93/Pake/blob/main/docs/cli-usage.md): every flag with defaults and examples
+- [Advanced usage](https://github.com/tw93/Pake/blob/main/docs/advanced-usage.md): style injection, containers, customization
+- [FAQ](https://github.com/tw93/Pake/blob/main/docs/faq.md): platform-specific troubleshooting
+
+## Notes
+
+- Output formats: dmg/app (macOS), msi (Windows), deb/AppImage/rpm/zst (Linux); pick with `--targets`.
+- Icons auto-fetch from the site favicon when `--icon` is omitted.
+- `--proxy-url` is baked into the app webview at build time; it does not proxy the icon download itself.
+- Google OAuth and similar providers may reject embedded webviews regardless of flags; `--new-window` and `--safe-domain` help with most SSO flows.
diff --git a/schema/pake.schema.json b/schema/pake.schema.json
new file mode 100644
index 00000000..d957ba99
--- /dev/null
+++ b/schema/pake.schema.json
@@ -0,0 +1,249 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "https://raw.githubusercontent.com/tw93/Pake/main/schema/pake.schema.json",
+ "title": "Pake CLI config file",
+ "description": "Declarative config for `pake --config <path>`. Fields mirror the camelCase CLI options; an explicit CLI flag always wins over a config field. Invocation concerns (--json, --config) are CLI-only.",
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "$schema": {
+ "type": "string",
+ "description": "Optional reference to this schema for editor validation."
+ },
+ "url": {
+ "type": "string",
+ "description": "Web URL, local HTML file, or local directory to package. A positional CLI argument wins over this field."
+ },
+ "name": {
+ "type": "string",
+ "description": "Application name."
+ },
+ "identifier": {
+ "type": "string",
+ "description": "Application identifier / bundle ID. Derived from url and name when omitted."
+ },
+ "title": {
+ "type": "string",
+ "description": "Window title."
+ },
+ "icon": {
+ "type": "string",
+ "description": "Application icon path or URL. Fetched from the site favicon when omitted.",
+ "default": ""
+ },
+ "width": {
+ "type": "number",
+ "description": "Window width in pixels.",
+ "default": 1200
+ },
+ "height": {
+ "type": "number",
+ "description": "Window height in pixels.",
+ "default": 780
+ },
+ "useLocalFile": {
+ "type": "boolean",
+ "description": "When url is a local file, recursively copy its sibling files into the app.",
+ "default": false
+ },
+ "fullscreen": {
+ "type": "boolean",
+ "description": "Start in full screen.",
+ "default": false
+ },
+ "hideTitleBar": {
+ "type": "boolean",
+ "description": "macOS only: hide title bar (immersive header).",
+ "default": false
+ },
+ "hideWindowDecorations": {
+ "type": "boolean",
+ "description": "Windows/Linux only: hide native window decorations.",
+ "default": false
+ },
+ "multiArch": {
+ "type": "boolean",
+ "description": "macOS only: build a universal binary for both Intel and Apple Silicon.",
+ "default": false
+ },
+ "inject": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description": "Local CSS/JS file paths injected into the page.",
+ "default": []
+ },
+ "debug": {
+ "type": "boolean",
+ "description": "Debug build with more output.",
+ "default": false
+ },
+ "proxyUrl": {
+ "type": "string",
+ "description": "Proxy URL for all network requests (http://, https://, socks5://).",
+ "default": ""
+ },
+ "userAgent": {
+ "type": "string",
+ "description": "Custom user agent.",
+ "default": ""
+ },
+ "targets": {
+ "type": "string",
+ "description": "Build target format. Linux: deb/appimage/rpm/zst and *-arm64 variants (comma-separated allowed); Windows: x64/arm64; macOS: intel/apple/universal/app/dmg. Defaults to the platform installer format."
+ },
+ "appVersion": {
+ "type": "string",
+ "description": "App version written into the bundle.",
+ "default": "1.0.0"
+ },
+ "alwaysOnTop": {
+ "type": "boolean",
+ "description": "Keep the window always on top.",
+ "default": false
+ },
+ "maximize": {
+ "type": "boolean",
+ "description": "Start window maximized.",
+ "default": false
+ },
+ "darkMode": {
+ "type": "boolean",
+ "description": "Force dark mode (macOS, Windows, Linux).",
+ "default": false
+ },
+ "disabledWebShortcuts": {
+ "type": "boolean",
+ "description": "Disable web page shortcuts.",
+ "default": false
+ },
+ "activationShortcut": {
+ "type": "string",
+ "description": "Global shortcut that activates the app window.",
+ "default": ""
+ },
+ "showSystemTray": {
+ "type": "boolean",
+ "description": "Show a system tray icon.",
+ "default": false
+ },
+ "systemTrayIcon": {
+ "type": "string",
+ "description": "Custom system tray icon path.",
+ "default": ""
+ },
+ "hideOnClose": {
+ "type": "boolean",
+ "description": "Hide the window on close instead of exiting. Defaults to true on macOS, false elsewhere."
+ },
+ "incognito": {
+ "type": "boolean",
+ "description": "Launch in incognito/private mode (no persisted cookies or storage).",
+ "default": false
+ },
+ "wasm": {
+ "type": "boolean",
+ "description": "Enable WebAssembly support (Flutter Web, etc.).",
+ "default": false
+ },
+ "enableDragDrop": {
+ "type": "boolean",
+ "description": "Enable drag and drop.",
+ "default": false
+ },
+ "keepBinary": {
+ "type": "boolean",
+ "description": "Keep the raw binary alongside the installer.",
+ "default": false
+ },
+ "bundle": {
+ "type": "boolean",
+ "description": "Linux only: false skips packaging and outputs the raw executable (CLI: --no-bundle).",
+ "default": true
+ },
+ "multiInstance": {
+ "type": "boolean",
+ "description": "Allow multiple app instances.",
+ "default": false
+ },
+ "multiWindow": {
+ "type": "boolean",
+ "description": "Allow opening multiple windows in one instance.",
+ "default": false
+ },
+ "startToTray": {
+ "type": "boolean",
+ "description": "Start minimized to tray.",
+ "default": false
+ },
+ "forceInternalNavigation": {
+ "type": "boolean",
+ "description": "Keep every link inside the Pake window.",
+ "default": false
+ },
+ "internalUrlRegex": {
+ "type": "string",
+ "description": "Regex for URLs treated as internal navigation.",
+ "default": ""
+ },
+ "safeDomain": {
+ "type": "string",
+ "description": "Comma-separated domains kept inside the app (e.g. SSO callbacks).",
+ "default": ""
+ },
+ "enableFind": {
+ "type": "boolean",
+ "description": "Enable in-page Find UI with Cmd/Ctrl+F/G.",
+ "default": false
+ },
+ "installerLanguage": {
+ "type": "string",
+ "description": "Windows installer language.",
+ "default": "en-US"
+ },
+ "zoom": {
+ "type": "number",
+ "description": "Initial page zoom level (50-200).",
+ "default": 100
+ },
+ "minWidth": {
+ "type": "number",
+ "description": "Minimum window width (0 = no limit).",
+ "default": 0
+ },
+ "minHeight": {
+ "type": "number",
+ "description": "Minimum window height (0 = no limit).",
+ "default": 0
+ },
+ "ignoreCertificateErrors": {
+ "type": "boolean",
+ "description": "Ignore certificate errors (self-signed certs).",
+ "default": false
+ },
+ "iterativeBuild": {
+ "type": "boolean",
+ "description": "Rapid build mode (app only, no dmg/deb/msi), for debugging.",
+ "default": false
+ },
+ "newWindow": {
+ "type": "boolean",
+ "description": "Allow sites to open new windows (auth flows, tabs).",
+ "default": false
+ },
+ "install": {
+ "type": "boolean",
+ "description": "macOS only: move the built app into /Applications.",
+ "default": false
+ },
+ "camera": {
+ "type": "boolean",
+ "description": "macOS only: request camera permission.",
+ "default": false
+ },
+ "microphone": {
+ "type": "boolean",
+ "description": "macOS only: request microphone permission.",
+ "default": false
+ }
+ }
+}
diff --git a/tests/unit/config-file.test.ts b/tests/unit/config-file.test.ts
new file mode 100644
index 00000000..72dd1dd4
--- /dev/null
+++ b/tests/unit/config-file.test.ts
@@ -0,0 +1,134 @@
+import path from 'path';
+import os from 'os';
+import fsExtra from 'fs-extra';
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { getCliProgram } from '@/helpers/cli-program';
+import { loadConfigFile } from '@/helpers/config-file';
+import { PakeError } from '@/utils/error';
+import schema from '../../schema/pake.schema.json';
+
+// Fields that exist as CLI options but are invocation concerns, so they are
+// rejected in config files and excluded from the schema.
+const CLI_ONLY_KEYS = new Set(['config', 'json', 'version']);
+// Fields that exist only in config files, not as CLI options.
+const CONFIG_ONLY_KEYS = new Set(['url', '$schema']);
+
+// getCliProgram configures commander's global singleton, so it can only be
+// called once per process; cache the derived attribute names.
+const CLI_ATTRIBUTE_NAMES = new Set(
+ getCliProgram().options.map((o) => o.attributeName()),
+);
+
+function cliAttributeNames(): Set<string> {
+ return CLI_ATTRIBUTE_NAMES;
+}
+
+describe('pake.schema.json stays in sync with the CLI surface', () => {
+ it('covers every CLI option except CLI-only invocation flags', () => {
+ const schemaKeys = new Set(Object.keys(schema.properties));
+ for (const key of cliAttributeNames()) {
+ if (CLI_ONLY_KEYS.has(key)) {
+ expect(schemaKeys.has(key), `schema must not contain "${key}"`).toBe(
+ false,
+ );
+ } else {
+ expect(schemaKeys.has(key), `schema is missing "${key}"`).toBe(true);
+ }
+ }
+ });
+
+ it('contains no field that is not a CLI option', () => {
+ const validKeys = cliAttributeNames();
+ for (const key of Object.keys(schema.properties)) {
+ if (CONFIG_ONLY_KEYS.has(key)) continue;
+ expect(
+ validKeys.has(key),
+ `schema field "${key}" has no CLI option`,
+ ).toBe(true);
+ }
+ });
+
+ it('rejects unknown fields via additionalProperties', () => {
+ expect(schema.additionalProperties).toBe(false);
+ });
+});
+
+describe('loadConfigFile', () => {
+ let tmpDir: string;
+ const validKeys = cliAttributeNames();
+
+ const writeConfig = async (content: unknown, file = 'app.json') => {
+ const configPath = path.join(tmpDir, file);
+ await fsExtra.writeFile(
+ configPath,
+ typeof content === 'string' ? content : JSON.stringify(content),
+ );
+ return configPath;
+ };
+
+ beforeAll(async () => {
+ tmpDir = await fsExtra.mkdtemp(path.join(os.tmpdir(), 'pake-config-'));
+ });
+
+ afterAll(async () => {
+ await fsExtra.remove(tmpDir);
+ });
+
+ it('loads url and camelCase options', async () => {
+ const configPath = await writeConfig({
+ $schema: 'https://example.com/pake.schema.json',
+ url: 'https://weekly.tw93.fun',
+ name: 'Weekly',
+ width: 1000,
+ hideTitleBar: true,
+ inject: ['./patch.css'],
+ });
+
+ const loaded = await loadConfigFile(configPath, validKeys);
+ expect(loaded.url).toBe('https://weekly.tw93.fun');
+ expect(loaded.options).toEqual({
+ name: 'Weekly',
+ width: 1000,
+ hideTitleBar: true,
+ inject: ['./patch.css'],
+ });
+ });
+
+ it('rejects a missing file with INVALID_INPUT', async () => {
+ const missing = path.join(tmpDir, 'nope.json');
+ await expect(loadConfigFile(missing, validKeys)).rejects.toMatchObject({
+ code: 'INVALID_INPUT',
+ });
+ });
+
+ it('rejects broken JSON with INVALID_INPUT', async () => {
+ const configPath = await writeConfig('{ oops', 'broken.json');
+ await expect(loadConfigFile(configPath, validKeys)).rejects.toMatchObject({
+ code: 'INVALID_INPUT',
+ });
+ });
+
+ it('rejects unknown fields naming the field', async () => {
+ const configPath = await writeConfig({ nmae: 'typo' }, 'typo.json');
+ await expect(loadConfigFile(configPath, validKeys)).rejects.toThrow(
+ /Unknown config field "nmae"/,
+ );
+ });
+
+ it('rejects CLI-only invocation fields', async () => {
+ const configPath = await writeConfig({ json: true }, 'json-flag.json');
+ await expect(loadConfigFile(configPath, validKeys)).rejects.toThrow(
+ /not allowed in a config file/,
+ );
+ });
+
+ it('rejects wrong value types naming the expected type', async () => {
+ const configPath = await writeConfig({ width: 'wide' }, 'badtype.json');
+ const rejection = expect(loadConfigFile(configPath, validKeys)).rejects;
+ await rejection.toBeInstanceOf(PakeError);
+ const configPath2 = await writeConfig({ inject: 'a.css' }, 'badtype2.json');
+ await expect(loadConfigFile(configPath2, validKeys)).rejects.toThrow(
+ /"inject" must be of type string\[\]/,
+ );
+ });
+});
diff --git a/tests/unit/json-output.test.ts b/tests/unit/json-output.test.ts
new file mode 100644
index 00000000..0918a310
--- /dev/null
+++ b/tests/unit/json-output.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import log from 'loglevel';
+import {
+ ERROR_EXIT_CODES,
+ enableMachineMode,
+ getCapturedWarnings,
+ isInteractive,
+ isMachineMode,
+ printJsonResult,
+ PakeJsonResult,
+} from '@/utils/output';
+import { PakeError } from '@/utils/error';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('exit code contract', () => {
+ it('maps every error code to its documented exit code', () => {
+ expect(ERROR_EXIT_CODES).toEqual({
+ INVALID_INPUT: 2,
+ BUILD_FAILED: 3,
+ NETWORK: 3,
+ ENV_MISSING: 4,
+ UNEXPECTED: 1,
+ });
+ });
+});
+
+describe('PakeError code and hint', () => {
+ it('carries an optional code and hint for the JSON result', () => {
+ const err = new PakeError('rust missing', {
+ code: 'ENV_MISSING',
+ hint: 'Install Rust via https://rustup.rs',
+ });
+ expect(err.code).toBe('ENV_MISSING');
+ expect(err.hint).toBe('Install Rust via https://rustup.rs');
+ });
+
+ it('leaves code and hint undefined when not provided', () => {
+ const err = new PakeError('plain');
+ expect(err.code).toBeUndefined();
+ expect(err.hint).toBeUndefined();
+ });
+});
+
+describe('machine mode', () => {
+ // enableMachineMode mutates module-level state, so ordering inside this
+ // file matters: isInteractive/isMachineMode pre-state is checked first.
+ it('is off by default and never interactive after enabling', () => {
+ expect(isMachineMode()).toBe(false);
+
+ enableMachineMode();
+
+ expect(isMachineMode()).toBe(true);
+ expect(isInteractive()).toBe(false);
+ });
+
+ it('routes logs to stderr and captures warnings for the JSON result', () => {
+ enableMachineMode();
+ // setLevel after enabling must keep the stderr factory (cli.ts does this).
+ log.setLevel('info');
+ const stderrSpy = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => undefined);
+
+ log.warn('something soft-failed');
+ log.info('progress line');
+
+ expect(stderrSpy).toHaveBeenCalledTimes(2);
+ expect(getCapturedWarnings()).toContain('something soft-failed');
+ expect(getCapturedWarnings()).not.toContain('progress line');
+ });
+
+ it('prints exactly one parseable JSON line on stdout', () => {
+ const writes: string[] = [];
+ const stdoutSpy = vi
+ .spyOn(process.stdout, 'write')
+ .mockImplementation((chunk) => {
+ writes.push(String(chunk));
+ return true;
+ });
+
+ const result: PakeJsonResult = {
+ ok: true,
+ name: 'Weekly',
+ platform: process.platform,
+ arch: 'arm64',
+ outputs: [{ path: '/tmp/Weekly.dmg', sizeBytes: 42, format: 'dmg' }],
+ warnings: [],
+ error: null,
+ };
+ printJsonResult(result);
+
+ expect(stdoutSpy).toHaveBeenCalledTimes(1);
+ expect(writes[0].endsWith('\n')).toBe(true);
+ expect(JSON.parse(writes[0])).toEqual(result);
+ });
+});
diff --git a/tests/unit/local-input.test.ts b/tests/unit/local-input.test.ts
new file mode 100644
index 00000000..16bc44ff
--- /dev/null
+++ b/tests/unit/local-input.test.ts
@@ -0,0 +1,60 @@
+import path from 'path';
+import os from 'os';
+import fsExtra from 'fs-extra';
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { handleLocalFile } from '@/helpers/merge';
+import { PakeTauriConfig } from '@/types';
+
+// Staging a real directory rewrites the package's own dist/, so tests cover
+// only the paths that return or throw before any staging happens.
+function makeTauriConf(): PakeTauriConfig {
+ return {
+ pake: {
+ windows: [{ url: '', url_type: 'web' } as never],
+ user_agent: { macos: '', linux: '', windows: '' },
+ system_tray: { macos: false, linux: false, windows: false },
+ system_tray_path: '',
+ proxy_url: '',
+ multi_instance: false,
+ multi_window: false,
+ },
+ bundle: {},
+ app: {},
+ };
+}
+
+describe('handleLocalFile', () => {
+ let tmpDir: string;
+
+ beforeAll(async () => {
+ tmpDir = await fsExtra.mkdtemp(path.join(os.tmpdir(), 'pake-local-'));
+ });
+
+ afterAll(async () => {
+ await fsExtra.remove(tmpDir);
+ });
+
+ it('treats a non-existing path as a web url', async () => {
+ const conf = makeTauriConf();
+ await handleLocalFile('https://example.com', false, conf);
+ expect(conf.pake.windows[0].url_type).toBe('web');
+ });
+
+ it('rejects a directory without index.html at its root', async () => {
+ const emptyDir = path.join(tmpDir, 'no-entry');
+ await fsExtra.ensureDir(emptyDir);
+ // index.html nested one level down must not count as a root entry.
+ await fsExtra.ensureDir(path.join(emptyDir, 'nested'));
+ await fsExtra.writeFile(
+ path.join(emptyDir, 'nested', 'index.html'),
+ '<html></html>',
+ );
+
+ const conf = makeTauriConf();
+ await expect(handleLocalFile(emptyDir, false, conf)).rejects.toMatchObject({
+ code: 'INVALID_INPUT',
+ });
+ // Config must be untouched on failure.
+ expect(conf.pake.windows[0].url).toBe('');
+ });
+});
diff --git a/tests/unit/validate-url-input.test.ts b/tests/unit/validate-url-input.test.ts
index 548e89ec..9778755d 100644
--- a/tests/unit/validate-url-input.test.ts
+++ b/tests/unit/validate-url-input.test.ts
@@ -24,4 +24,22 @@ describe('validateUrlInput', () => {
// '' is not a file, normalizeUrl('') -> 'https://' -> new URL() throws.
expect(() => validateUrlInput('')).toThrow(InvalidArgumentError);
});
+
+ it('rejects path-shaped input that does not exist instead of URL-ifying it', () => {
+ // Regression guard: './typo' must never become https://./typo and build
+ // a silently broken app. Covers ./, ../, /, ~/ and Windows drive paths.
+ for (const missing of [
+ './does-not-exist-dir',
+ '../does-not-exist-dir',
+ '/does/not/exist/anywhere-pake',
+ '~/does-not-exist-pake',
+ 'C:\\does-not-exist-pake',
+ ]) {
+ expect(() => validateUrlInput(missing)).toThrow(/does not exist/);
+ }
+ });
+
+ it('still treats bare domains without scheme as web urls', () => {
+ expect(validateUrlInput('example.com')).toBe('https://example.com');
+ });
});