@yufengtadian/freedom-cli 1.1.10 → 1.10.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,33 @@
1
+ ---
2
+ AIGC:
3
+ Label: "1"
4
+ ContentProducer: 001191440300708461136T1XGW3
5
+ ProduceID: 84e692d233baf4c4ebb909c06f044dd3_70353d809c3a11f19bec525400826444
6
+ ReservedCode1: F+Qlzocu3qufDKwdTzizi2zKAc4B1PeLnx1QG2eBbCzoFNe8VCjjy7ZVan5+wjHbBQrGtKwJC6zkKzoSrFUq7Gv3XMiE7j3v8hF+C7Tmpw0ziqQdD/JCj6m6KXkxPjJqrRK2gF51x03qxPXi6Wsiye+vID13w/vsTmLretYS7o5/4Aagvd1xxvh/i3k=
7
+ ContentPropagator: 001191440300708461136T1XGW3
8
+ PropagateID: 84e692d233baf4c4ebb909c06f044dd3_70353d809c3a11f19bec525400826444
9
+ ReservedCode2: F+Qlzocu3qufDKwdTzizi2zKAc4B1PeLnx1QG2eBbCzoFNe8VCjjy7ZVan5+wjHbBQrGtKwJC6zkKzoSrFUq7Gv3XMiE7j3v8hF+C7Tmpw0ziqQdD/JCj6m6KXkxPjJqrRK2gF51x03qxPXi6Wsiye+vID13w/vsTmLretYS7o5/4Aagvd1xxvh/i3k=
10
+ ---
11
+
1
12
  # freedom-cli
2
13
 
3
- Freedom 桌面壳打包工具:把你的 Web 前端一键打包成跨平台桌面应用(v1.1.10)。
14
+ Freedom 桌面壳打包工具:把你的 Web 前端一键打包成跨平台桌面应用(v1.10.12)。
4
15
 
5
16
  基于自研 Freedom WebView 壳层(对标 Wails / Tauri):前端完全自由、后端可任意语言、渲染复用系统 WebView(Windows WebView2 / macOS WKWebView / Linux WebKitGTK),产物为单个可执行文件 + resources 目录,前端页面内存加载,不占本地端口。
6
17
 
7
- **v1.1.10 核心升级**:不再依赖 Go 工具链。壳层以预编译二进制随 npm 包分发(`shell/<platform>/`),`freedom build` 直接复制壳 + 写入前端与配置即可出包,Windows / macOS / Linux 三平台一次全出,任意前后端语言自由组合。
18
+ **v1.10.12 核心升级**:macOS 产物升级为标准 .app 应用包,直接产出 `.app.zip`(mac 用户解压即得 `.app`,拖入 /Applications 即可使用);在 macOS 上执行 `freedom dmg` 可再用系统 hdiutil 生成 `.dmg`。全程仍不依赖 Go 工具链。
19
+
20
+ **v1.1.11 核心升级**:不再依赖 Go 工具链。壳层以预编译二进制随 npm 包分发(`shell/<platform>/`),`freedom build` 直接复制壳 + 写入前端与配置即可出包,Windows / macOS / Linux 三平台一次全出,任意前后端语言自由组合。
21
+
22
+ **v1.10.12 新特性**:
23
+ - macOS 产物打包为标准 `.app` bundle + `.app.zip`:壳复制进 `Contents/MacOS/`,resources 与前端/后端随包,解压即用,无需任何语言运行时;
24
+ - `freedom dmg`:在 macOS 上用系统 hdiutil 把 `.app` 打成 `.dmg`(Windows / Linux 上运行会给出指引);
25
+ - TUI 壳管理去 Go 依赖感:「下载壳」标注无需 Go,「本地编译壳」明确为可选项(壳已预编译随包分发)。
26
+
27
+ **v1.1.11 新特性**:
28
+ - `freedom tui` 交互式终端界面:菜单化完成打包 / 新建项目 / 修改配置 / 壳管理 / 教程,零依赖、方向键 + 回车导航、支持搜索过滤与多选;
29
+ - 前端构建缓存:源码无改动时跳过重复 `vite build`(秒级复用,典型加速 10 倍+),`--no-cache` 强制全量重建;
30
+ - 多平台分发并行化:`--platform all` 各平台同时复制分发,全平台打包耗时显著缩短。
8
31
 
9
32
  ## 安装
10
33
 
@@ -22,22 +45,42 @@ freedom init my-app
22
45
  cd my-app
23
46
  npm install
24
47
 
25
- # 2. 调整标题栏(可选,随时可改)
48
+ # 2. 交互式终端界面(方向键 + 回车选择,q 返回)
49
+ freedom tui
50
+
51
+ # 3. 调整标题栏(可选,随时可改)
26
52
  freedom titlebar native # 保留系统原生标题栏(默认)
27
53
  freedom titlebar hidden # 隐藏标题栏视觉,仅保留 Windows 原生最小化/最大化/关闭按钮
28
54
  freedom titlebar frameless # 完全无边框,按钮由前端自绘(模板已内置示例)
29
55
 
30
- # 3. 打包
56
+ # 4. 打包
31
57
  freedom build # 默认当前平台
32
58
  freedom build --platform all # 三平台全量(win + mac + linux)
33
59
  freedom build --platform win-x64 # 仅 Windows
34
60
  freedom build --platform mac-arm64 # 仅 macOS Apple Silicon
35
61
  freedom build --platform linux-x64 # 仅 Linux
62
+ freedom build --no-cache # 忽略前端构建缓存,强制重建
36
63
  ```
37
64
 
38
65
  构建产物默认输出到 `dist/`。`dist/<应用名>.exe`(或对应平台可执行文件)为壳层程序,运行时从 `dist/resources/` 加载前端页面与配置,不弹 cmd 黑窗。
39
66
 
40
- **三平台打包**:壳层二进制随包分发,无需本机安装 Go 或交叉编译工具链。首次构建某平台时若本地缺少对应壳二进制,CLI 自动从 GitHub Releases 下载(`freedom shell download <platform>` 可手动补齐);仅当你想用本机 Go 工具链亲自编译壳时才需要 `freedom shell build`(只产出本机平台)。
67
+ **macOS 产物(v1.10.12)**:`freedom build --platform mac` 除裸可执行文件外,额外生成标准 `.app` bundle 与 `<应用名>-<平台>.app.zip`:
68
+
69
+ ```
70
+ dist/<应用名>.app/
71
+ └── Contents/
72
+ ├── Info.plist
73
+ ├── MacOS/
74
+ │ ├── <应用名> # 壳可执行文件
75
+ │ └── resources/ # 前端页面 + config.json + backend/
76
+ └── Resources/
77
+ ```
78
+
79
+ mac 用户解压 `.app.zip` 即得 `.app`,拖入 `/Applications` 即可直接运行,无需安装任何语言运行时。如需 `.dmg` 安装映像,把产物拷到 macOS 上执行 `freedom dmg`(用系统 hdiutil 生成),或仅分发包内 `.app.zip`。
80
+
81
+ **构建缓存**:CLI 会在 `.freedom/vite-dist/` 记录前端源码指纹,源码无改动时复用上次构建产物直接进入分发阶段(秒级完成)。修改了 `src/` / `index.html` / `vite.config.js` 等任一处会触发自动重建;需要强制全量时可加 `--no-cache`。
82
+
83
+ **三平台打包**:壳层二进制随包分发,无需本机安装 Go 或交叉编译工具链。首次构建某平台时若本地缺少对应壳二进制,CLI 自动从 GitHub Releases 下载(`freedom shell download <platform>` 可手动补齐);仅当你想用本机 Go 工具链亲自编译壳时才需要 `freedom shell build`(只产出本机平台)。多平台分发为并行执行,全平台打包耗时大幅缩短。
41
84
 
42
85
  产物目录可在 `freedom.config.js` 的 `outDir` 中调整:默认 `'dist'`,设为 `'.'` 则直接输出到项目根目录(dist 的上级),设为任意相对 / 绝对路径亦可。输出到项目根目录时会自动跳过 `index.html` 副本,避免覆盖项目源文件。
43
86
 
@@ -88,15 +131,18 @@ window.freedom.window.minimize(); // 窗口控制
88
131
  - Node.js >= 18
89
132
  - 不需要 Go 工具链(壳层为随包分发的预编译二进制)
90
133
  - 可选:`freedom shell build` 需本机 Go(含 CGO,Windows 需 MSVC 编译环境),仅用于亲自编译壳
134
+ - `.dmg` 打包需在 macOS 上执行(依赖系统 hdiutil);`.app.zip` 在任意平台均可直接产出
91
135
 
92
136
  ## 命令
93
137
 
94
138
  ```
139
+ freedom tui # 交互式终端界面
95
140
  freedom init <目录> [--force]
96
- freedom build [--platform win-x64|mac-arm64|linux-x64|all]
141
+ freedom build [--platform win-x64|mac-arm64|linux-x64|all] [--no-cache]
97
142
  freedom titlebar <native|hidden|frameless>
98
143
  freedom config [get|set]
99
144
  freedom shell list|download <platform>|build <platform>
145
+ freedom dmg [--platform <plat>] # 在 macOS 上把 .app 打包为 .dmg
100
146
  freedom tutorial
101
147
  freedom help
102
148
  ```
@@ -123,3 +169,4 @@ export default {
123
169
  ## License
124
170
 
125
171
  MIT
172
+ *(内容由AI生成,仅供参考)*
package/lib/build.js CHANGED
@@ -11,17 +11,24 @@
11
11
  // - 写 resources/config.json(窗口 + 后端配置,壳运行时读取)
12
12
  // - 复制壳为 outDir/<app>[.exe]
13
13
  // - 复制 backend/ 到 resources/backend/(配置了 backend 时)
14
+ // 4. macOS 平台额外生成 .app bundle + .app.zip:
15
+ // outDir/<app>.app/Contents/{Info.plist, MacOS/<app>, MacOS/resources/}
16
+ // 壳加载 exe 同目录 resources/,因此 .app 无需改壳即可运行;
17
+ // mac 用户解压 .app.zip 得 .app,拖入 /Applications 即可使用;
18
+ // 如需 .dmg,在 macOS 上运行 freedom dmg 用系统 hdiutil 生成。
14
19
  //
15
20
  // 产物不嵌入 HTML,页面与配置均在 exe 同目录 resources/ 下,因此壳可复用、
16
21
  // 可跨平台分发、无需在目标机器安装任何语言运行时。
17
22
 
18
23
  const fs = require('fs');
24
+ const fsp = fs.promises;
19
25
  const path = require('path');
20
26
  const { spawnSync } = require('child_process');
21
27
  const { copyDir } = require('./utils');
22
28
  const {
23
29
  ALL_PLATFORMS,
24
30
  isWinPlat,
31
+ isMacPlat,
25
32
  platformExeName,
26
33
  nativePlatform,
27
34
  localShellPath,
@@ -68,16 +75,23 @@ async function build(projectDir, opts = {}) {
68
75
  const cfg = await loadConfig(dir);
69
76
 
70
77
  const name = (cfg.name || 'freedom-app').replace(/[^a-zA-Z0-9_.-]/g, '-');
78
+ const version = String(cfg.version || appVersionFromPkg(dir) || '1.0.0');
71
79
  const outDir = String(cfg.outDir || 'dist').trim() || 'dist';
72
80
  const outDirPath = path.resolve(dir, outDir);
73
81
  const platforms = parsePlatforms(opts.platform);
74
82
  const autoDownload = opts.autoDownload !== false;
75
83
 
76
- // 1) 前端打包
84
+ // 1) 前端打包(带缓存:源码未变更时复用上次 vite 产物,跳过 npm run build)
77
85
  ensureNodeModules(dir);
78
- const vite = run('npm', ['run', 'build'], { cwd: dir });
79
- if (vite.status !== 0) {
80
- throw new Error(`前端打包失败:\n${vite.stdout}\n${vite.stderr}`);
86
+ const useCache = opts.noCache !== true;
87
+ if (useCache && !viteNeedsRebuild(dir)) {
88
+ process.stdout.write('[freedom] 前端源码无改动,复用构建缓存...\n');
89
+ } else {
90
+ const vite = run('npm', ['run', 'build'], { cwd: dir });
91
+ if (vite.status !== 0) {
92
+ throw new Error(`前端打包失败:\n${vite.stdout}\n${vite.stderr}`);
93
+ }
94
+ writeViteCacheMarker(dir);
81
95
  }
82
96
  const distHtml = path.join(dir, '.freedom', 'vite-dist', 'index.html');
83
97
  if (!fs.existsSync(distHtml)) {
@@ -90,20 +104,21 @@ async function build(projectDir, opts = {}) {
90
104
  const backendDir = path.join(dir, cfg.backendDir || 'backend');
91
105
  const hasBackend = !!(cfg.backend && fs.existsSync(backendDir));
92
106
 
93
- // 3) 逐平台分发
107
+ // 3) 逐平台分发(多平台并行,显著缩短全平台打包耗时)
94
108
  // 单平台直接输出到 outDir;多平台各自放到 outDir/<plat>/ 子目录,避免互相覆盖
95
109
  const multi = platforms.length > 1;
96
- const results = [];
97
- for (const plat of platforms) {
98
- const targetDir = multi ? path.join(outDirPath, plat) : outDirPath;
99
- const outFile = await emitPlatform({ plat, name, targetDir, html, configJSON, backendDir, hasBackend, autoDownload });
100
- results.push({ plat, outFile });
101
- }
110
+ const results = await Promise.all(
111
+ platforms.map(async (plat) => {
112
+ const targetDir = multi ? path.join(outDirPath, plat) : outDirPath;
113
+ const outFile = await emitPlatform({ plat, name, version, targetDir, html, configJSON, backendDir, hasBackend, autoDownload });
114
+ return { plat, outFile };
115
+ })
116
+ );
102
117
 
103
118
  return { results };
104
119
  }
105
120
 
106
- async function emitPlatform({ plat, name, targetDir, html, configJSON, backendDir, hasBackend, autoDownload }) {
121
+ async function emitPlatform({ plat, name, version, targetDir, html, configJSON, backendDir, hasBackend, autoDownload }) {
107
122
  // 取预编译壳二进制
108
123
  const shell = localShellPath(plat);
109
124
  if (!fs.existsSync(shell)) {
@@ -117,28 +132,125 @@ async function emitPlatform({ plat, name, targetDir, html, configJSON, backendDi
117
132
  await downloadShell(plat);
118
133
  }
119
134
 
120
- fs.mkdirSync(targetDir, { recursive: true });
135
+ await fsp.mkdir(targetDir, { recursive: true });
121
136
 
122
137
  // 壳二进制 -> 应用可执行文件
123
138
  const exeName = platformExeName(plat, name);
124
139
  const outFile = path.join(targetDir, exeName);
125
- fs.copyFileSync(shell, outFile);
140
+ await fsp.copyFile(shell, outFile);
126
141
  if (!isWinPlat(plat)) {
127
- fs.chmodSync(outFile, 0o755);
142
+ await fsp.chmod(outFile, 0o755);
128
143
  }
129
144
 
130
145
  // 写 resources:页面 + 配置 + 后端
131
146
  const resDir = path.join(targetDir, 'resources');
132
- fs.mkdirSync(resDir, { recursive: true });
133
- fs.writeFileSync(path.join(resDir, 'index.html'), html, 'utf8');
134
- fs.writeFileSync(path.join(resDir, 'config.json'), configJSON, 'utf8');
147
+ await fsp.mkdir(resDir, { recursive: true });
148
+ await fsp.writeFile(path.join(resDir, 'index.html'), html, 'utf8');
149
+ await fsp.writeFile(path.join(resDir, 'config.json'), configJSON, 'utf8');
135
150
  if (hasBackend) {
136
151
  copyDir(backendDir, path.join(resDir, 'backend'));
137
152
  }
138
153
 
154
+ // macOS:额外生成 .app bundle + .app.zip(供 mac 用户解压即用)
155
+ // 壳加载 exe 同目录 resources/,故把 resources 放进 Contents/MacOS/ 即可运行,无需改壳。
156
+ if (isMacPlat(plat)) {
157
+ const appZip = createMacApp({ targetDir, name, plat, exeName, resDir, version });
158
+ process.stdout.write(
159
+ `[freedom] macOS 产物已打包为 .app.zip:${path.relative(process.cwd(), appZip)}\n`
160
+ );
161
+ }
162
+
139
163
  return outFile;
140
164
  }
141
165
 
166
+ // 把已分发的裸产物升级为标准 .app bundle,并压缩为 .app.zip
167
+ function createMacApp({ targetDir, name, plat, exeName, resDir, version }) {
168
+ const appDir = path.join(targetDir, `${name}.app`);
169
+ const contents = path.join(appDir, 'Contents');
170
+ const macos = path.join(contents, 'MacOS');
171
+ const appRes = path.join(macos, 'resources');
172
+ fs.mkdirSync(macos, { recursive: true });
173
+ fs.mkdirSync(path.join(contents, 'Resources'), { recursive: true });
174
+
175
+ // 可执行文件:exe 名与 app 同名,放入 MacOS/
176
+ const exeDst = path.join(macos, name);
177
+ fs.copyFileSync(path.join(targetDir, exeName), exeDst);
178
+ fs.chmodSync(exeDst, 0o755);
179
+
180
+ // resources -> MacOS/resources(壳的运行时目录)
181
+ if (fs.existsSync(resDir)) {
182
+ copyDir(resDir, appRes);
183
+ }
184
+
185
+ // Info.plist
186
+ fs.writeFileSync(path.join(contents, 'Info.plist'), renderInfoPlist(name, version), 'utf8');
187
+
188
+ // .app.zip:解压即得 .app,拖入 /Applications 即可使用
189
+ const zipPath = path.join(targetDir, `${name}-${plat}.app.zip`);
190
+ zipDir(zipPath, appDir);
191
+ return zipPath;
192
+ }
193
+
194
+ function renderInfoPlist(name, version) {
195
+ const safe = String(name).replace(/&/g, '&amp;');
196
+ const bundleId = `com.freedom.app.${String(name).toLowerCase().replace(/[^a-z0-9.-]/g, '-')}`;
197
+ return `<?xml version="1.0" encoding="UTF-8"?>
198
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
199
+ <plist version="1.0">
200
+ <dict>
201
+ <key>CFBundleName</key>
202
+ <string>${safe}</string>
203
+ <key>CFBundleDisplayName</key>
204
+ <string>${safe}</string>
205
+ <key>CFBundleExecutable</key>
206
+ <string>${safe}</string>
207
+ <key>CFBundleIdentifier</key>
208
+ <string>${bundleId}</string>
209
+ <key>CFBundleVersion</key>
210
+ <string>${version}</string>
211
+ <key>CFBundleShortVersionString</key>
212
+ <string>${version}</string>
213
+ <key>CFBundlePackageType</key>
214
+ <string>APPL</string>
215
+ <key>CFBundleInfoDictionaryVersion</key>
216
+ <string>6.0</string>
217
+ <key>LSMinimumSystemVersion</key>
218
+ <string>10.13</string>
219
+ <key>NSHighResolutionCapable</key>
220
+ <true/>
221
+ <key>NSAppTransportSecurity</key>
222
+ <dict>
223
+ <key>NSAllowsArbitraryLoads</key>
224
+ <true/>
225
+ </dict>
226
+ </dict>
227
+ </plist>
228
+ `;
229
+ }
230
+
231
+ // 用系统 tar(Windows 为 bsdtar)把目录压成 zip:跨平台可用,无需额外依赖
232
+ function zipDir(zipPath, dir) {
233
+ const parent = path.dirname(dir);
234
+ const base = path.basename(dir);
235
+ if (fs.existsSync(zipPath)) fs.unlinkSync(zipPath);
236
+ const res = spawnSync('tar', ['-a', '-c', '-f', zipPath, base], { cwd: parent, encoding: 'utf8' });
237
+ if (res.error || res.status !== 0) {
238
+ throw new Error(
239
+ `打包 ${base} 为 zip 失败:${(res.stderr || res.stdout || '').trim() || res.error.message}`
240
+ );
241
+ }
242
+ }
243
+
244
+ // 从项目 package.json 取版本号(cfg.version 优先)
245
+ function appVersionFromPkg(dir) {
246
+ try {
247
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
248
+ return typeof pkg.version === 'string' ? pkg.version : null;
249
+ } catch (e) {
250
+ return null;
251
+ }
252
+ }
253
+
142
254
  // 渲染 resources/config.json(与壳 configfile.go 的 runtimeConfigFile 字段对齐)
143
255
  function renderConfigJSON(cfg, name) {
144
256
  const obj = {
@@ -164,6 +276,63 @@ function renderConfigJSON(cfg, name) {
164
276
  return JSON.stringify(obj, null, 2);
165
277
  }
166
278
 
279
+ // ---- 前端构建缓存 ----
280
+ // 追踪影响前端产物的源文件(index.html / vite.config.* / src/**)的最新 mtime,
281
+ // 与上次 vite build 记录值比较:未变更则跳过 npm run build,直接复用 .freedom/vite-dist 产物。
282
+
283
+ function collectViteSources(dir) {
284
+ const files = [];
285
+ const roots = ['index.html', 'vite.config.js', 'vite.config.mjs', 'vite.config.ts', 'vite.config.cjs'];
286
+ for (const r of roots) {
287
+ const p = path.join(dir, r);
288
+ if (fs.existsSync(p)) files.push(p);
289
+ }
290
+ const src = path.join(dir, 'src');
291
+ if (fs.existsSync(src)) {
292
+ const walk = (d) => {
293
+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
294
+ const p = path.join(d, entry.name);
295
+ if (entry.isDirectory()) walk(p);
296
+ else files.push(p);
297
+ }
298
+ };
299
+ walk(src);
300
+ }
301
+ return files;
302
+ }
303
+
304
+ function maxMtime(files) {
305
+ return files.reduce((m, f) => {
306
+ try {
307
+ const t = fs.statSync(f).mtimeMs;
308
+ return t > m ? t : m;
309
+ } catch (e) {
310
+ return m;
311
+ }
312
+ }, 0);
313
+ }
314
+
315
+ function viteCacheMarker(dir) {
316
+ return path.join(dir, '.freedom', 'vite-dist', '.cache-mtime');
317
+ }
318
+
319
+ function viteNeedsRebuild(dir) {
320
+ const distHtml = path.join(dir, '.freedom', 'vite-dist', 'index.html');
321
+ const marker = viteCacheMarker(dir);
322
+ if (!fs.existsSync(distHtml) || !fs.existsSync(marker)) return true;
323
+ let recorded = 0;
324
+ try {
325
+ recorded = Number(fs.readFileSync(marker, 'utf8'));
326
+ } catch (e) { return true; }
327
+ // 留 1s 容差避免文件系统时间精度抖动
328
+ return maxMtime(collectViteSources(dir)) > recorded + 1000;
329
+ }
330
+
331
+ function writeViteCacheMarker(dir) {
332
+ fs.mkdirSync(path.join(dir, '.freedom', 'vite-dist'), { recursive: true });
333
+ fs.writeFileSync(viteCacheMarker(dir), String(maxMtime(collectViteSources(dir))), 'utf8');
334
+ }
335
+
167
336
  function ensureNodeModules(dir) {
168
337
  // 缺陷修复:node_modules 存在但 package.json 更新过(依赖变更)时自动重装。
169
338
  const pkgFile = path.join(dir, 'package.json');
package/lib/cli.js CHANGED
@@ -14,14 +14,17 @@ function help() {
14
14
  freedom - Freedom 桌面壳打包工具 v${VERSION}
15
15
 
16
16
  用法:
17
+ freedom tui 进入交互式 TUI 界面(新建/打包/配置/壳管理)
17
18
  freedom init [目录] [--force] 在当前/指定目录新建项目模板
18
19
  freedom build [--platform <p>] 前端打包并分发桌面应用(默认当前平台)
19
20
  --platform win|mac|linux|all 指定目标平台(all = 三平台全量)
21
+ --no-cache 忽略前端构建缓存,强制重新打包
20
22
  freedom titlebar <native|hidden|frameless>
21
23
  一键切换标题栏策略
22
24
  freedom shell list 列出本地已就绪的预编译壳
23
- freedom shell download <plat> 从 GitHub Releases 下载预编译壳
24
- freedom shell build <plat> 本地用 Go 编译壳(需要 Go)
25
+ freedom shell download <plat> 从 GitHub Releases 下载预编译壳(无需 Go)
26
+ freedom shell build <plat> 本地用 Go 编译壳(可选,壳已预编译一般无需)
27
+ freedom dmg [--platform <plat>] 将已构建的 .app 打包为 .dmg(需在 macOS 上执行)
25
28
  freedom config 查看当前配置
26
29
  freedom config get <key> 读取单个配置项
27
30
  freedom config set <key> <value> 修改单个配置项
@@ -32,6 +35,11 @@ freedom - Freedom 桌面壳打包工具 v${VERSION}
32
35
  平台(<p>/<plat>):win-x64 / darwin-x64 / darwin-arm64 / linux-x64 / linux-arm64,
33
36
  快捷别名:win / mac / linux / all。
34
37
 
38
+ macOS 产物说明:
39
+ freedom build --platform mac 直接产出 <app>.app.zip(解压即得 .app,
40
+ 拖入 /Applications 即可使用,无需安装任何语言运行时);如需 .dmg,
41
+ 在 macOS 上执行 freedom dmg 用系统 hdiutil 生成。
42
+
35
43
  标题栏策略说明:
36
44
  native 保留系统原生标题栏(默认)
37
45
  hidden 隐藏标题栏视觉,仅保留 Windows 原生最小化/最大化/关闭按钮
@@ -56,6 +64,9 @@ async function run(argv) {
56
64
  console.log(VERSION);
57
65
  return 0;
58
66
 
67
+ case 'tui':
68
+ return await require('./tui').tui(process.cwd());
69
+
59
70
  case 'init': {
60
71
  const force = rest.includes('--force');
61
72
  const dirArg = rest.filter((a) => a !== '--force')[0];
@@ -74,7 +85,7 @@ async function run(argv) {
74
85
  if (platArg) {
75
86
  platform = platArg.includes('=') ? platArg.split('=')[1] : rest[rest.indexOf(platArg) + 1];
76
87
  }
77
- const { results } = await build(process.cwd(), { platform });
88
+ const { results } = await build(process.cwd(), { platform, noCache: rest.includes('--no-cache') });
78
89
  for (const r of results) {
79
90
  console.log(`[freedom] [${r.plat}] 构建完成:${r.outFile}`);
80
91
  }
@@ -85,6 +96,10 @@ async function run(argv) {
85
96
  return await runShell(rest);
86
97
  }
87
98
 
99
+ case 'dmg': {
100
+ return await runDmg(rest);
101
+ }
102
+
88
103
  case 'titlebar': {
89
104
  const mode = rest[0];
90
105
  if (!['native', 'hidden', 'frameless'].includes(mode)) {
@@ -178,6 +193,7 @@ async function runShell(rest) {
178
193
  }
179
194
  const dest = buildShell(plat);
180
195
  console.log(`[freedom] 已编译 ${plat} 壳:${dest}`);
196
+ console.log('[freedom] 提示:壳已预编译随包分发,一般无需本地编译。');
181
197
  return 0;
182
198
  }
183
199
  default:
@@ -186,6 +202,45 @@ async function runShell(rest) {
186
202
  }
187
203
  }
188
204
 
205
+ // freedom dmg:在 macOS 上把已构建的 .app 打包为 .dmg(依赖系统 hdiutil)
206
+ async function runDmg(rest) {
207
+ const { loadConfig, nativePlatform } = require('./utils');
208
+ const { makeDmg } = require('./dmg');
209
+ const dir = process.cwd();
210
+ const cfg = await loadConfig(dir);
211
+ const name = (cfg.name || 'freedom-app').replace(/[^a-zA-Z0-9_.-]/g, '-');
212
+ const outDir = String(cfg.outDir || 'dist').trim() || 'dist';
213
+
214
+ const platArg = rest.find((a) => a.startsWith('--platform'));
215
+ const plat = platArg
216
+ ? (platArg.includes('=') ? platArg.split('=')[1] : rest[rest.indexOf(platArg) + 1])
217
+ : nativePlatform();
218
+ if (!plat || !plat.startsWith('darwin')) {
219
+ console.error('[freedom] dmg 仅支持 macOS 平台(darwin-x64 / darwin-arm64)。');
220
+ return 1;
221
+ }
222
+
223
+ const baseDir = path.resolve(dir, outDir);
224
+ // 兼容 build --platform all 的 outDir/<plat> 布局
225
+ const candidates = [path.join(baseDir, `${name}.app`), path.join(baseDir, plat, `${name}.app`)];
226
+ const appDir = candidates.find((p) => fs.existsSync(p));
227
+ if (!appDir) {
228
+ console.error(`[freedom] 未找到 ${name}.app(已检查 ${candidates.join(' / ')})。`);
229
+ console.error(' 请先在 macOS 上运行 freedom build --platform mac 生成 .app。');
230
+ return 1;
231
+ }
232
+
233
+ const outPath = path.join(path.dirname(appDir), `${name}-${plat}.dmg`);
234
+ try {
235
+ const dmgPath = await makeDmg(appDir, outPath, name);
236
+ console.log(`[freedom] 已生成 dmg:${dmgPath}`);
237
+ return 0;
238
+ } catch (e) {
239
+ console.error(`[freedom] ${e.message}`);
240
+ return 1;
241
+ }
242
+ }
243
+
189
244
  function openBrowser(file) {
190
245
  const { spawn } = require('child_process');
191
246
  const plat = process.platform;
package/lib/dmg.js ADDED
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+
3
+ // freedom dmg:把已构建的 .app bundle 打包为 .dmg(macOS 分发格式)
4
+ //
5
+ // 说明:.dmg 依赖 macOS 系统自带的 hdiutil,只能在 macOS 上生成。
6
+ // Windows / Linux 上运行 freedom build 已直接产出 .app.zip(解压即得 .app,
7
+ // 拖入 /Applications 即可使用),无需 dmg;如仍需 dmg,把产物拷到 Mac 上执行
8
+ // freedom dmg 即可。
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { spawnSync } = require('child_process');
13
+
14
+ async function makeDmg(appDir, outPath, volName) {
15
+ if (process.platform !== 'darwin') {
16
+ throw new Error(
17
+ '.dmg 依赖 macOS 系统 hdiutil,只能在 macOS 上生成。\n' +
18
+ ' 当前平台可直接分发 .app.zip(解压即得 .app,拖入 /Applications 即可使用)。\n' +
19
+ ' 如需 .dmg,请把 .app 拷到 macOS 上运行:freedom dmg'
20
+ );
21
+ }
22
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
23
+ if (fs.existsSync(outPath)) fs.unlinkSync(outPath);
24
+
25
+ const args = [
26
+ 'create',
27
+ '-volname',
28
+ String(volName || path.basename(appDir, '.app')),
29
+ '-srcfolder',
30
+ appDir,
31
+ '-ov',
32
+ '-format',
33
+ 'UDZO',
34
+ outPath,
35
+ ];
36
+ const res = spawnSync('hdiutil', args, { encoding: 'utf8' });
37
+ if (res.error || res.status !== 0) {
38
+ throw new Error(`hdiutil 生成 dmg 失败:\n${(res.stderr || res.stdout || '').trim()}`);
39
+ }
40
+ return outPath;
41
+ }
42
+
43
+ module.exports = { makeDmg };
package/lib/tui.js ADDED
@@ -0,0 +1,331 @@
1
+ 'use strict';
2
+
3
+ // freedom tui —— 零依赖 ANSI 终端交互界面
4
+ // 纯 Node 标准库(readline + ANSI escape)实现,无第三方依赖,安装即用。
5
+
6
+ const path = require('path');
7
+ const readline = require('readline');
8
+ const { init } = require('./init');
9
+ const { build } = require('./build');
10
+ const { setConfig, showConfig } = require('./config');
11
+ const { tutorialFile, hasConfig, ALL_PLATFORMS } = require('./utils');
12
+
13
+ // ---------------- ANSI ----------------
14
+ const ESC = '\x1b';
15
+ const C = {
16
+ reset: `${ESC}[0m`, bold: `${ESC}[1m`, dim: `${ESC}[2m`, rev: `${ESC}[7m`, underline: `${ESC}[4m`,
17
+ fgRed: `${ESC}[31m`, fgGreen: `${ESC}[32m`, fgYellow: `${ESC}[33m`,
18
+ fgCyan: `${ESC}[36m`, fgMagenta: `${ESC}[35m`, fgWhite: `${ESC}[37m`, fgGray: `${ESC}[90m`,
19
+ };
20
+ const CLEAR = `${ESC}[2J${ESC}[H`;
21
+ const HIDE = `${ESC}[?25l`;
22
+ const SHOW = `${ESC}[?25h`;
23
+
24
+ function line(content, color = '') {
25
+ return color + content + C.reset;
26
+ }
27
+
28
+ class TUI {
29
+ constructor() {
30
+ this.out = process.stdout;
31
+ this.in = process.stdin;
32
+ this.active = false;
33
+ this.keyHandler = null;
34
+ }
35
+
36
+ enter() {
37
+ if (this.active) return;
38
+ this.active = true;
39
+ this.in.setRawMode(true);
40
+ this.in.resume();
41
+ this.in.setEncoding('utf8');
42
+ readline.emitKeypressEvents(this.in);
43
+ this.in.on('keypress', this._onKey);
44
+ this.out.write(HIDE + CLEAR);
45
+ }
46
+
47
+ exit() {
48
+ if (!this.active) return;
49
+ this.active = false;
50
+ this.in.removeListener('keypress', this._onKey);
51
+ try { this.in.setRawMode(false); } catch (e) { /* ignore */ }
52
+ this.in.pause();
53
+ this.out.write(SHOW + CLEAR);
54
+ }
55
+
56
+ _onKey = (str, key) => {
57
+ if (this.keyHandler) this.keyHandler(str, key);
58
+ };
59
+
60
+ _waitKey() {
61
+ return new Promise((resolve) => {
62
+ const done = (str, key) => {
63
+ this.keyHandler = null;
64
+ resolve({ str, key });
65
+ };
66
+ this.keyHandler = done;
67
+ });
68
+ }
69
+
70
+ _renderFrame(title, bodyLines, footer) {
71
+ const w = this.out.columns || 80;
72
+ const top = ` ${C.fgCyan}${C.bold}┌${'─'.repeat(Math.max(10, w - 6))}┐${C.reset}`;
73
+ const titleMid = ` ${C.fgCyan}${C.bold}│${C.reset}${C.fgWhite}${C.bold} ${title}${C.reset}`;
74
+ const bottom = ` ${C.fgCyan}${C.bold}└${'─'.repeat(Math.max(10, w - 6))}┘${C.reset}`;
75
+ const pad = (s) => ` ${s}`;
76
+ const lines = [
77
+ '',
78
+ ` ${C.fgCyan}${C.bold}▚ F R E E D O M T U I ${C.fgGray}v1.1.10${C.reset}`,
79
+ '',
80
+ top,
81
+ pad(titleMid),
82
+ ...bodyLines.map((l) => pad(typeof l === 'string' ? l : l.text)),
83
+ bottom,
84
+ '',
85
+ pad(footer ? C.fgGray + footer + C.reset : ''),
86
+ '',
87
+ ];
88
+ this.out.write(CLEAR + lines.join('\n'));
89
+ }
90
+
91
+ // 单选菜单:返回选中下标;null = 取消(q/Esc)
92
+ async menu(title, items, { selected = 0, footer = '↑ ↓ 选择 · Enter 确认 · q 返回' } = {}) {
93
+ let idx = selected;
94
+ const draw = () => {
95
+ const body = items.map((it, i) => {
96
+ if (i === idx) return { text: ` ${C.fgCyan}${C.rev} ▶ ${it} ${C.reset}` };
97
+ return ` ${C.fgGray}${it}${C.reset}`;
98
+ });
99
+ this._renderFrame(title, body, footer);
100
+ };
101
+ draw();
102
+ for (;;) {
103
+ const { key } = await this._waitKey();
104
+ if (key.name === 'up' || key.sequence === '\x1b[A') idx = (idx - 1 + items.length) % items.length;
105
+ else if (key.name === 'down' || key.sequence === '\x1b[B') idx = (idx + 1) % items.length;
106
+ else if (key.name === 'return') return idx;
107
+ else if (key.name === 'q' || key.name === 'escape') return null;
108
+ draw();
109
+ }
110
+ }
111
+
112
+ // 多选:Space 切换,Enter 确认,返回选中的下标数组
113
+ async multiselect(title, items, { checked = [], footer = '↑ ↓ 移动 · 空格 勾选 · Enter 确认 · q 返回' } = {}) {
114
+ let idx = 0;
115
+ const sel = new Set(checked);
116
+ const draw = () => {
117
+ const body = items.map((it, i) => {
118
+ const mark = sel.has(i) ? `${C.fgGreen}${C.bold}●${C.reset}` : `${C.fgGray}○${C.reset}`;
119
+ const cursor = i === idx ? `${C.fgCyan}▶${C.reset}` : ' ';
120
+ const txt = i === idx ? `${C.rev} ${it} ${C.reset}` : it;
121
+ return { text: ` ${cursor} ${mark} ${txt}` };
122
+ });
123
+ this._renderFrame(title, body, footer);
124
+ };
125
+ draw();
126
+ for (;;) {
127
+ const { key } = await this._waitKey();
128
+ if (key.name === 'up' || key.sequence === '\x1b[A') idx = (idx - 1 + items.length) % items.length;
129
+ else if (key.name === 'down' || key.sequence === '\x1b[B') idx = (idx + 1) % items.length;
130
+ else if (key.name === 'space') {
131
+ if (sel.has(idx)) sel.delete(idx); else sel.add(idx);
132
+ } else if (key.name === 'return') return [...sel].sort((a, b) => a - b);
133
+ else if (key.name === 'q' || key.name === 'escape') return null;
134
+ draw();
135
+ }
136
+ }
137
+
138
+ // 文本输入:返回字符串;null = 取消
139
+ async input(title, { initial = '', footer = '输入后回车确认 · Esc 取消' } = {}) {
140
+ let buf = initial;
141
+ const draw = () => {
142
+ this._renderFrame(title, [
143
+ { text: ' ' + C.fgYellow + '> ' + C.fgWhite + buf + (C.fgCyan + '▌' + C.reset) },
144
+ '',
145
+ { text: C.fgGray + '(自由填写,回车确认)' + C.reset },
146
+ ], footer);
147
+ };
148
+ draw();
149
+ for (;;) {
150
+ const { str, key } = await this._waitKey();
151
+ if (key.name === 'return') return buf;
152
+ if (key.name === 'escape' || key.name === 'q') return null;
153
+ if (key.name === 'backspace') buf = buf.slice(0, -1);
154
+ else if (str && str.length === 1) buf += str;
155
+ draw();
156
+ }
157
+ }
158
+
159
+ // 确认:返回 bool
160
+ async confirm(title, { footer = '← → 选择 · Enter 确认' } = {}) {
161
+ const yes = await this.menu(title, ['是', '否'], { footer });
162
+ return yes === 0;
163
+ }
164
+
165
+ // 消息:按任意键继续
166
+ async message(title, bodyLines, { footer = '按任意键继续' } = {}) {
167
+ this._renderFrame(title, bodyLines, footer);
168
+ await this._waitKey();
169
+ }
170
+
171
+ // 切换出 TUI 执行任务(任务输出直接走终端),完成后回到 TUI
172
+ async runTask(fn) {
173
+ this.exit();
174
+ try {
175
+ await fn();
176
+ } catch (e) {
177
+ console.error(`${C.fgRed}[freedom]${C.reset} 任务失败:${e.message}`);
178
+ }
179
+ this.enter();
180
+ }
181
+ }
182
+
183
+ // ---------------- 主流程 ----------------
184
+
185
+ const CONFIG_KEYS = [
186
+ ['name', '应用名 / 窗口标题 / exe 文件名'],
187
+ ['width', '窗口宽度'],
188
+ ['height', '窗口高度'],
189
+ ['minWidth', '窗口最小宽度'],
190
+ ['minHeight', '窗口最小高度'],
191
+ ['center', '启动居中(true/false)'],
192
+ ['debug', '开发者工具(true/false)'],
193
+ ['titlebar', '标题栏:native | hidden | frameless'],
194
+ ['outDir', '产物目录:dist(默认)| .(项目根)| 任意路径'],
195
+ ['backend', '任意语言后端进程(JSON)'],
196
+ ];
197
+
198
+ function openBrowser(file) {
199
+ const { spawn } = require('child_process');
200
+ const plat = process.platform;
201
+ const url = `file://${file.replace(/\\/g, '/')}`;
202
+ try {
203
+ if (plat === 'win32') spawn('cmd', ['/c', 'start', '', url], { detached: true, stdio: 'ignore' }).unref();
204
+ else if (plat === 'darwin') spawn('open', [url], { detached: true, stdio: 'ignore' }).unref();
205
+ else spawn('xdg-open', [url], { detached: true, stdio: 'ignore' }).unref();
206
+ } catch (e) { /* ignore */ }
207
+ }
208
+
209
+ async function buildFlow(tui, cwd) {
210
+ // 平台多选:默认勾选当前平台
211
+ const native = require('./utils').nativePlatform();
212
+ const checked = [ALL_PLATFORMS.indexOf(native)];
213
+ const picked = await tui.multiselect('选择目标平台(多选)', ALL_PLATFORMS, { checked });
214
+ if (picked === null) return;
215
+ const platforms = picked.map((i) => ALL_PLATFORMS[i]);
216
+ const platArg = picked.length === ALL_PLATFORMS.length ? 'all' : platforms.join(',');
217
+
218
+ await tui.runTask(async () => {
219
+ const { results } = await build(cwd, { platform: platArg });
220
+ for (const r of results) {
221
+ console.log(`${C.fgGreen}[freedom]${C.reset} [${r.plat}] 构建完成:${r.outFile}`);
222
+ }
223
+ });
224
+ }
225
+
226
+ async function initFlow(tui, cwd) {
227
+ const name = await tui.input('新建项目', { initial: '' });
228
+ if (name === null) return;
229
+ const dir = await tui.runTask(() => {
230
+ const d = init(name || '.', { force: false });
231
+ console.log(`${C.fgGreen}[freedom]${C.reset} 项目已创建:${d}`);
232
+ console.log(` cd ${d} && npm install && freedom build`);
233
+ });
234
+ void dir;
235
+ }
236
+
237
+ async function configFlow(tui, cwd) {
238
+ for (;;) {
239
+ if (!hasConfig(cwd)) {
240
+ await tui.message('配置', [{ text: C.fgRed + ' 未找到 freedom.config.js,请先创建项目。' + C.reset }]);
241
+ return;
242
+ }
243
+ const names = ['查看当前配置', ...CONFIG_KEYS.map((k) => k[0]), '返回'];
244
+ const idx = await tui.menu('修改配置', names);
245
+ if (idx === null || idx === names.length - 1) return;
246
+ if (idx === 0) {
247
+ const cfgText = await showConfig(cwd);
248
+ await tui.message('当前配置', cfgText.split('\n').map((l) => ({ text: l })));
249
+ continue;
250
+ }
251
+ const [key, desc] = CONFIG_KEYS[idx - 1];
252
+ const val = await tui.input(`${key}`, { initial: '' });
253
+ if (val === null) continue;
254
+ setConfig(cwd, key, coerce(val));
255
+ await tui.message('配置', [{ text: C.fgGreen + ` ${key} = ${val}` + C.reset }]);
256
+ }
257
+ }
258
+
259
+ async function shellFlow(tui) {
260
+ const { listLocal, downloadShell, buildShell } = require('./shell');
261
+ for (;;) {
262
+ const items = ['查看已就绪壳', '下载壳(无需 Go)', '本地编译壳(可选·需 Go)', '返回'];
263
+ const idx = await tui.menu('壳管理', items);
264
+ if (idx === null || idx === items.length - 1) return;
265
+
266
+ if (idx === 0) {
267
+ const ready = listLocal();
268
+ const rows = ready.length
269
+ ? ready.map((p) => ({ text: C.fgGreen + ` ✓ ${p}` + C.reset }))
270
+ : [{ text: C.fgGray + ' 暂无已就绪壳' + C.reset }];
271
+ await tui.message('已就绪壳', rows);
272
+ } else if (idx === 1) {
273
+ const p = await tui.menu('选择要下载的壳平台', ALL_PLATFORMS);
274
+ if (p === null) continue;
275
+ await tui.runTask(async () => {
276
+ const dest = await downloadShell(ALL_PLATFORMS[p]);
277
+ console.log(`${C.fgGreen}[freedom]${C.reset} 已下载 ${ALL_PLATFORMS[p]} 壳:${dest}`);
278
+ });
279
+ } else {
280
+ const p = await tui.menu('选择要编译的壳平台(可选·需 Go,壳已预编译随包分发,一般无需编译)', ALL_PLATFORMS);
281
+ if (p === null) continue;
282
+ await tui.runTask(async () => {
283
+ const dest = buildShell(ALL_PLATFORMS[p]);
284
+ console.log(`${C.fgGreen}[freedom]${C.reset} 已编译 ${ALL_PLATFORMS[p]} 壳:${dest}`);
285
+ });
286
+ }
287
+ }
288
+ }
289
+
290
+ async function tutorialFlow(tui) {
291
+ const file = tutorialFile();
292
+ openBrowser(file);
293
+ await tui.message('教程', [{ text: C.fgGreen + ` 已打开:${file}` + C.reset }]);
294
+ }
295
+
296
+ function coerce(value) {
297
+ if (value === 'true') return true;
298
+ if (value === 'false') return false;
299
+ const num = Number(value);
300
+ if (value !== '' && Number.isFinite(num) && String(num) === value.trim()) return num;
301
+ return value;
302
+ }
303
+
304
+ async function tui(cwd) {
305
+ if (!process.stdin.isTTY) {
306
+ console.error('[freedom] tui 需要交互式终端,请直接在本机终端中运行 freedom tui。');
307
+ return 1;
308
+ }
309
+ const app = new TUI();
310
+ app.enter();
311
+ let keep = true;
312
+ while (keep) {
313
+ const items = ['打包桌面应用', '新建项目', '修改配置', '壳管理', '打开教程', '退出'];
314
+ const idx = await app.menu('主菜单', items, {
315
+ footer: `工作目录:${cwd} ↑ ↓ 选择 · Enter 确认 · q 退出`,
316
+ });
317
+ if (idx === null) break;
318
+ switch (idx) {
319
+ case 0: await buildFlow(app, cwd); break;
320
+ case 1: await initFlow(app, cwd); break;
321
+ case 2: await configFlow(app, cwd); break;
322
+ case 3: await shellFlow(app); break;
323
+ case 4: await tutorialFlow(app); break;
324
+ case 5: keep = false; break;
325
+ }
326
+ }
327
+ app.exit();
328
+ return 0;
329
+ }
330
+
331
+ module.exports = { tui, TUI };
package/lib/utils.js CHANGED
@@ -42,6 +42,11 @@ function isWinPlat(plat) {
42
42
  return plat.startsWith('win');
43
43
  }
44
44
 
45
+ // macOS 平台(darwin-*):产物需升级为 .app bundle + .app.zip 供 mac 用户解压即用
46
+ function isMacPlat(plat) {
47
+ return plat.startsWith('darwin');
48
+ }
49
+
45
50
  // 平台 key -> 产物可执行文件名(Windows 带 .exe,其余无扩展名)
46
51
  function platformExeName(plat, appName) {
47
52
  return isWinPlat(plat) ? `${appName}.exe` : appName;
@@ -106,6 +111,7 @@ module.exports = {
106
111
  ALL_PLATFORMS,
107
112
  SHELL_EXE_NAME,
108
113
  isWinPlat,
114
+ isMacPlat,
109
115
  platformExeName,
110
116
  nativePlatform,
111
117
  localShellPath,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
- {
1
+ {
2
2
  "name": "@yufengtadian/freedom-cli",
3
- "version": "1.1.10",
3
+ "version": "1.10.12",
4
4
  "description": "Freedom WebView desktop shell packaging tool - no Go toolchain required, one command packs three-platform desktop apps",
5
5
  "keywords": ["desktop", "webview", "electron-alternative", "wails", "tauri", "frontend", "cross-platform"],
6
6
  "license": "MIT",
@@ -26,3 +26,4 @@
26
26
  "node": ">=18"
27
27
  }
28
28
  }
29
+
Binary file
Binary file
Binary file
Binary file