@morlay/zephyr-desktop-bundle 0.0.0-stage → 0.2.0-alpha.0

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.
@@ -0,0 +1,101 @@
1
+ // electron-builder 配置的推导:**纯函数**,因为它几乎全是「字段从哪来」的判断。
2
+ //
3
+ // 三件事在这里定死:
4
+ // 1. 产物落在 `.zephyr/app/`(与 dist / runtime 同级,整目录可删);
5
+ // 2. asar 打开,只有 native(`*.node`)拆到 `app.asar.unpacked`;
6
+ // 3. **运行时不在这里复制**:宿主闭包由 `PackagerDefault` 直接 `pnpm deploy` 到
7
+ // `Resources/runtime`(快,且保留 pnpm 的相对链),这里只放静态面与身份文件。
8
+ import { join } from "node:path";
9
+ import type { PreparedIcons } from "./icons.ts";
10
+ import type { ResolvedConfig } from "@morlay/zephyr-cli";
11
+ import { CliError, type ZephyrLayout } from "@morlay/zephyr-cli";
12
+
13
+ /** 一份可交给 electron-builder 的配置(字段子集,够本次用)。 */
14
+ export interface ElectronBuilderConfig {
15
+ /**
16
+ * Electron 版本:**显式给**。
17
+ *
18
+ * app 目录是应用闭包,里面没有 `electron`(那是壳的 peer,由 electron-builder 自己提供),
19
+ * 不写这一项它会去 app 目录的 `node_modules` 里算版本并报
20
+ * `Cannot compute electron version from installed node modules`。
21
+ */
22
+ readonly electronVersion: string;
23
+ readonly appId: string;
24
+ readonly productName: string;
25
+ readonly artifactName: string;
26
+ readonly asar: boolean;
27
+ readonly asarUnpack: readonly string[];
28
+ /** 不做 native 重编(原生模块属于宿主闭包,已按随包 node 的 ABI 装好)。 */
29
+ readonly npmRebuild: boolean;
30
+ readonly directories: { readonly output: string };
31
+ readonly files: readonly string[];
32
+ readonly extraResources: readonly { readonly from: string; readonly to: string }[];
33
+ readonly mac: {
34
+ readonly category: string;
35
+ readonly identity: null;
36
+ readonly icon?: string;
37
+ };
38
+ readonly win: { readonly icon?: string };
39
+ readonly linux: { readonly category: string; readonly icon?: string };
40
+ }
41
+
42
+ /** 推导所需的三样东西。 */
43
+ export interface ElectronBuilderInput {
44
+ /** 解析后的工作区配置(`desktop.id` / `desktop.name` 从它来)。 */
45
+ readonly resolved: ResolvedConfig;
46
+ /** 产物布局。 */
47
+ readonly layout: ZephyrLayout;
48
+ /** Electron 版本(由调用方解析:app 目录是应用闭包,里面没有 `electron`)。 */
49
+ readonly electronVersion: string;
50
+ /** 三平台图标(`desktop.icon` 的生成物);没配图标就是空。 */
51
+ readonly icons?: PreparedIcons;
52
+ }
53
+
54
+ /**
55
+ * 把配置与布局推导成 electron-builder 的配置。
56
+ * @param input - 工作区配置、布局与壳目录。
57
+ * @returns 配置对象。
58
+ * @throws CliError 缺 `desktop.id` / `desktop.name`。
59
+ */
60
+ export function electronBuilderConfigOf(input: ElectronBuilderInput): ElectronBuilderConfig {
61
+ const desktop = input.resolved.config.desktop;
62
+ if (desktop === undefined) {
63
+ throw new CliError("配置里没有 desktop 段:desktop bundle 需要 desktop.id 与 desktop.name。");
64
+ }
65
+ return {
66
+ electronVersion: input.electronVersion,
67
+ appId: desktop.id,
68
+ productName: desktop.name,
69
+ artifactName: "${productName}-${version}-${os}-${arch}.${ext}",
70
+ asar: true,
71
+ asarUnpack: ["**/*.node"],
72
+ // 不做 native 重编:壳自己不用那些原生模块(它们在宿主闭包里,按随包 node 的 ABI 装好了),
73
+ // 按 Electron 的 ABI 再编一遍既不对,也会往 `~/.electron-gyp` 写东西。
74
+ npmRebuild: false,
75
+ directories: { output: join(input.layout.root, "app") },
76
+ // **逐项列,不用通配**(通配实测会漏件):壳产出的字节、启动器、清单。
77
+ // 壳的 `node_modules` 由 electron-builder 按 `package.json` 的 dependencies 自己收集(app 目录是
78
+ // `pnpm --filter 壳 deploy` 的产物,依赖图完整)。
79
+ // 宿主的产物**不在这里**:它在 `<outputDir>`(`bootstrap.mjs` / `client_modules/` / `src/` / 闭包),
80
+ // 由 `PackagerDefault` 复制进 `Resources/runtime`(真目录,壳要 `chdir` 进去)。
81
+ files: ["dist/**", "bootstrap.mjs", "package.json"],
82
+ // 宿主的那一份(产物五样)**不在这里**:`PackagerDefault` 在打包之后把 `<outputDir>` 复制进
83
+ // `Resources/runtime`(真目录,壳要 `chdir` 进去;asar 里不行)。
84
+ // 身份文件放 asar 外:按路径读它的东西(壳、启动器)不必依赖 asar 补丁。
85
+ extraResources: [
86
+ // 窗口尺寸与应用身份要在壳里读得到:环境变量只覆盖 dev 形态,打包形态靠这份文件。
87
+ { from: join(input.layout.root, "desktop.json"), to: "desktop.json" },
88
+ ],
89
+ // **不签名**:产物是给自己/内测用的目录,签名只会引入钥匙串与证书依赖。
90
+ mac: {
91
+ category: "public.app-category.developer-tools",
92
+ identity: null,
93
+ ...(input.icons?.mac === undefined ? {} : { icon: input.icons.mac }),
94
+ },
95
+ win: input.icons?.win === undefined ? {} : { icon: input.icons.win },
96
+ linux: {
97
+ category: "Development",
98
+ ...(input.icons?.linux === undefined ? {} : { icon: input.icons.linux }),
99
+ },
100
+ };
101
+ }
package/src/icons.ts ADDED
@@ -0,0 +1,96 @@
1
+ // 应用图标:把 `desktop.icon`(svg/png)转成 electron-builder 认的三平台图标。
2
+ //
3
+ // 三平台的口径:
4
+ // - **macOS**:`icon.icns`——先用 sharp 生成 `icon.iconset/` 的 10 个尺寸,再交给系统的 `iconutil` 打包;
5
+ // - **Windows / Linux**:512 的 png(electron-builder 会自己从 png 转 ico)。
6
+ //
7
+ // 生成物落在产物根的 `icon/`(可重建),配置里显式给 `mac/win/linux.icon`——不给的话 electron-builder 会去
8
+ // 项目根扫 `icon.*`,闭包里那份应用自己的 svg 会被当成图标并解析失败。
9
+ import { execFile } from "node:child_process";
10
+ import { access, mkdir, rm } from "node:fs/promises";
11
+ import { join, resolve } from "node:path";
12
+ import { promisify } from "node:util";
13
+ import sharp from "sharp";
14
+ import { CliError } from "@morlay/zephyr-cli";
15
+
16
+ /** 三平台图标的路径(缺的就是没生成)。 */
17
+ export interface PreparedIcons {
18
+ readonly mac?: string;
19
+ readonly linux?: string;
20
+ readonly win?: string;
21
+ }
22
+
23
+ /** macOS iconset 的尺寸与文件名(`iconutil` 只认这套命名)。 */
24
+ const MAC_ICONSET_SIZES: readonly (readonly [number, string])[] = [
25
+ [16, "icon_16x16.png"],
26
+ [32, "icon_16x16@2x.png"],
27
+ [32, "icon_32x32.png"],
28
+ [64, "icon_32x32@2x.png"],
29
+ [128, "icon_128x128.png"],
30
+ [256, "icon_128x128@2x.png"],
31
+ [256, "icon_256x256.png"],
32
+ [512, "icon_256x256@2x.png"],
33
+ [512, "icon_512x512.png"],
34
+ [1024, "icon_512x512@2x.png"],
35
+ ];
36
+
37
+ /** 等比缩放的透明底(图标不能有白边)。 */
38
+ const CONTAIN_BACKGROUND = { r: 0, g: 0, b: 0, alpha: 0 } as const;
39
+
40
+ /**
41
+ * 生成三平台图标。
42
+ * @param options - 工作区、产物根与 `desktop.icon` 的相对路径。
43
+ * @returns 各平台图标的绝对路径(没配图标就是空对象)。
44
+ * @throws CliError 图标文件不存在。
45
+ */
46
+ export async function prepareIcons(options: {
47
+ readonly workspace: string;
48
+ readonly outRoot: string;
49
+ readonly icon: string | undefined;
50
+ }): Promise<PreparedIcons> {
51
+ if (options.icon === undefined || options.icon === "") return {};
52
+ const source = resolve(options.workspace, options.icon);
53
+ if (!(await exists(source))) {
54
+ throw new CliError(`配置里的 desktop.icon 指向的文件不存在:${source}`);
55
+ }
56
+ const outDir = join(options.outRoot, "icon");
57
+ await rm(outDir, { recursive: true, force: true });
58
+ await mkdir(outDir, { recursive: true });
59
+
60
+ const png512 = join(outDir, "icon-512.png");
61
+ await sharp(source)
62
+ .resize(512, 512, { fit: "contain", background: CONTAIN_BACKGROUND })
63
+ .png()
64
+ .toFile(png512);
65
+ let icons: PreparedIcons = { linux: png512, win: png512 };
66
+
67
+ // `icon.icns` 只有 macOS 能产(`iconutil` 是系统命令);其它平台上打 mac 包本来也不是这里的活。
68
+ if (process.platform === "darwin") {
69
+ const iconset = join(outDir, "icon.iconset");
70
+ await mkdir(iconset, { recursive: true });
71
+ for (const [size, name] of MAC_ICONSET_SIZES) {
72
+ await sharp(source)
73
+ .resize(size, size, { fit: "contain", background: CONTAIN_BACKGROUND })
74
+ .png()
75
+ .toFile(join(iconset, name));
76
+ }
77
+ const icns = join(outDir, "icon.icns");
78
+ await promisify(execFile)("iconutil", ["-c", "icns", iconset, "-o", icns]);
79
+ icons = { ...icons, mac: icns };
80
+ }
81
+ return icons;
82
+ }
83
+
84
+ /**
85
+ * 文件在不在。
86
+ * @param path - 绝对路径。
87
+ * @returns 判断结果。
88
+ */
89
+ async function exists(path: string): Promise<boolean> {
90
+ try {
91
+ await access(path);
92
+ return true;
93
+ } catch {
94
+ return false;
95
+ }
96
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ // `@morlay/zephyr-desktop-bundle` 的公开面:一个 provide 函数 + 可单独引用的契约与推导。
2
+ export { provideDesktopBundle } from "./provide.ts";
3
+ export { electronBuilderConfigOf, type ElectronBuilderConfig } from "./electron-builder.ts";
4
+ export { Packager, PackagerDefault, type PackResult } from "./packager.ts";
5
+ export { BundleCommand } from "./commands/bundle.ts";
6
+ export { DesktopCommand } from "./commands/desktop.ts";
7
+ export { DesktopDevCommand } from "./commands/dev.ts";
@@ -0,0 +1,396 @@
1
+ // 打包动作的接缝:**配置推导**留在纯函数里,**真正调用 electron-builder** 放在这里。
2
+ //
3
+ // app 目录怎么来:**用 `pnpm --filter @morlay/zephyr-desktop-shell deploy` 装**(壳的依赖图完整、lock
4
+ // 一致,electron-builder 才会按图收集进 asar)。手拷进去的包它不认——那是之前 `oxc-transform`
5
+ // 静默消失的原因。
6
+ //
7
+ // <app>/
8
+ // ├── dist/ 壳的产物(deploy 自带,壳的 `files` 里有 `dist`)
9
+ // ├── node_modules/ 壳的依赖(含 `@morlay/dsh-oxc-node` → `oxc-transform`)
10
+ // ├── bootstrap.mjs 打包形态的启动器(部署值 → 壳,见 `desktop-dirs.ts`)
11
+ // └── package.json 入口改写为 `./bootstrap.mjs`
12
+ //
13
+ // 宿主的那一份(`build` 的 `<outputDir>`:`bootstrap.mjs` / `client_modules/` / `src/` / 闭包 /
14
+ // `package.json`)在打包之后整份复制进 `Resources/runtime`——它是自包含的一份应用,壳在那里 `chdir`。
15
+ import {
16
+ access,
17
+ appendFile,
18
+ cp,
19
+ mkdir,
20
+ mkdtemp,
21
+ readFile,
22
+ readdir,
23
+ rename,
24
+ rm,
25
+ writeFile,
26
+ } from "node:fs/promises";
27
+ import { execFile } from "node:child_process";
28
+ import { dirname, join } from "node:path";
29
+ import { promisify } from "node:util";
30
+ import { inject, Injectable, Logger } from "@morlay/zephyr";
31
+ import { appPackageNameOf, CliError } from "@morlay/zephyr-cli";
32
+ import { packagedBootstrap } from "./desktop-dirs.ts";
33
+ import type { ElectronBuilderConfig } from "./electron-builder.ts";
34
+ import { assertRuntimeSmoke, resourcesDirOf } from "./runtime-smoke.ts";
35
+
36
+ const run = promisify(execFile);
37
+
38
+ /** 壳的包名(`dist/` 从这里取)。 */
39
+ const SHELL_PACKAGE = "@morlay/zephyr-desktop-shell";
40
+
41
+ /** 打包形态的启动器文件名(app 目录里,`main` 指它)。 */
42
+ const BOOTSTRAP_FILE = "bootstrap.mjs";
43
+
44
+ /** 一次打包的结果。 */
45
+ export interface PackResult {
46
+ /** 产出的应用目录(`.zephyr/app/<平台>-<架构>/<产品名>.app` 之类)。 */
47
+ readonly appDir: string;
48
+ }
49
+
50
+ /** 打包所需的输入。 */
51
+ export interface PackInput {
52
+ /** app 目录(electron-builder 的 projectDir)。 */
53
+ readonly appDir: string;
54
+ /** 宿主的那一份(`build` 的 `<outputDir>`:`bootstrap.mjs` + `client_modules/` + 闭包 + 源码面入口)。 */
55
+ readonly profileDir: string;
56
+ /** workspace 根:闭包**直接 deploy 到 `Resources/runtime`**(不再复制那 900MB)。 */
57
+ readonly workspace: string;
58
+ /** 步骤日志文件(每步一行,含耗时):卡住时从这里看最后一条。 */
59
+ readonly logFile: string;
60
+ }
61
+
62
+ /** 打包契约。 */
63
+ @Injectable()
64
+ export abstract class Packager {
65
+ /**
66
+ * 打一个当前平台的应用目录。
67
+ * @param config - electron-builder 配置。
68
+ * @param input - app 目录、宿主闭包与日志文件。
69
+ * @returns 产物位置。
70
+ */
71
+ abstract pack(config: ElectronBuilderConfig, input: PackInput): Promise<PackResult>;
72
+
73
+ /**
74
+ * 把产物装进系统应用目录。
75
+ * @param result - 打包结果。
76
+ * @returns 装到哪。
77
+ */
78
+ abstract install(result: PackResult): Promise<string>;
79
+ }
80
+
81
+ /** 默认实现:deploy 壳 → 叠宿主闭包 → electron-builder。 */
82
+ @Injectable()
83
+ export class PackagerDefault extends Packager {
84
+ private readonly logger = inject(Logger);
85
+
86
+ /**
87
+ * @param config - electron-builder 配置。
88
+ * @param input - app 目录、宿主闭包与日志文件。
89
+ * @returns 产物位置。
90
+ */
91
+ async pack(config: ElectronBuilderConfig, input: PackInput): Promise<PackResult> {
92
+ await this.assemble(input);
93
+ const module = (await import("electron-builder").catch(() => undefined)) as
94
+ | { build?: (options: { config: unknown; dir: boolean }) => Promise<readonly string[]> }
95
+ | undefined;
96
+ if (module?.build === undefined) {
97
+ throw new CliError("没有装 electron-builder:desktop bundle 需要它(peerDependency)。");
98
+ }
99
+ process.chdir(input.appDir);
100
+ const outputs = await this.step(
101
+ input.logFile,
102
+ `electron-builder 归档(asar)→ ${config.directories.output}`,
103
+ () => module.build?.({ config, dir: true }) ?? Promise.resolve([]),
104
+ );
105
+ const appDir = outputs[0] ?? (await discoverAppDir(config.directories.output));
106
+ const runtimeDir = join(await resourcesDirOf(appDir), "runtime");
107
+ await this.step(input.logFile, `装宿主产物 → ${runtimeDir}`, () =>
108
+ copyRuntime(input, runtimeDir),
109
+ );
110
+ // 装完先证明它自包含:不自包含的包装出来是「双击没反应」。
111
+ await this.step(input.logFile, "打包期冒烟:闭包自包含 + 入口能被 loader 加载", async () => {
112
+ await this.note(input.logFile, `[bundle] 冒烟对象:${runtimeDir}`);
113
+ const report = await assertRuntimeSmoke(runtimeDir);
114
+ const escaping = report.links.filter((link) => !link.inside).length;
115
+ await this.note(
116
+ input.logFile,
117
+ `[bundle] 闭包链接:${String(report.links.length)} 个,逃逸 ${String(escaping)} 个`,
118
+ );
119
+ return runtimeDir;
120
+ });
121
+ return { appDir };
122
+ }
123
+
124
+ /**
125
+ * 备 app 目录:deploy 壳(依赖合法进 asar)→ 宿主闭包放 `profile/` → 改入口。
126
+ * @param input - app 目录与宿主闭包。
127
+ */
128
+ private async assemble(input: PackInput): Promise<void> {
129
+ await this.step(input.logFile, `清空 app 目录(${input.appDir})`, async () => {
130
+ await rm(input.appDir, { recursive: true, force: true });
131
+ await mkdir(input.appDir, { recursive: true });
132
+ });
133
+ await this.step(input.logFile, `重建壳包(${SHELL_PACKAGE} 的 dist)`, async () => {
134
+ // 壳的 `dist/` 是 deploy 从**壳包自己的 `files`** 里带出来的:源码改了却没 build,打出来的包里
135
+ // 还是旧壳(症状:新加的启动路径不生效,日志里仍是上一条链的报错)。与 `bundle` 无条件先建应用
136
+ // 产物同一个理由——包必须与源码一致;这一步只要几秒。
137
+ //
138
+ // **与 dev 同一条链**(`devkit build`,入口从 `exports` 推导):同一个包不能有两份入口清单,
139
+ // 两条链会分叉(一条有 `src/preload.ts`、另一条没有),后果是「一条路径好、另一条静默坏」。
140
+ // 壳的 preload 是出口(`./preload`),两条路径都由这一条链出产物。
141
+ await run("pnpm", ["exec", "devkit", "build", "--filter", SHELL_PACKAGE], {
142
+ cwd: await workspaceRootOf(),
143
+ });
144
+ });
145
+ await this.step(
146
+ input.logFile,
147
+ `pnpm --filter ${SHELL_PACKAGE} deploy → ${input.appDir}`,
148
+ async () => {
149
+ // **按应用的依赖 deploy**:闭包里既有宿主需要的包,也含壳额外要的(`@morlay/zephyr`、
150
+ // `@morlay/dsh-oxc-node` 已写进应用的 dependencies)。这样 app 目录里的 `node_modules` 就是
151
+ // 「外面那份工作区」在 asar 内的等价物——宿主与壳都按同一套解析规则找到包。
152
+ // 壳的 app 目录:只装**壳**的依赖(`dist/` 由壳包自己的 `files` 带出来)。宿主闭包在
153
+ // `Resources/runtime`,由本类在 electron-builder 出目录之后自己装(`copyRuntime`,
154
+ // 见下面的「装宿主产物 → …」那一步),不进 electron-builder 的配置——两边各管各的依赖图,
155
+ // 不合并。
156
+ await run(
157
+ "pnpm",
158
+ ["--filter", SHELL_PACKAGE, "deploy", "--prod", "--ignore-scripts", input.appDir],
159
+ { cwd: await workspaceRootOf() },
160
+ );
161
+ },
162
+ );
163
+ // deploy 只搬壳的 `files`:桥(`__DSH_BROWSER_PANE__` / `dshDesktop` / `__DSH_STORAGE__` /
164
+ // `<html data-platform>`)全在 preload 里,它不在 asar 内就等于桌面能力全没了(面板不注册、
165
+ // 窗口拖不动)。**打包期就判**,别等人打开应用才发现。
166
+ await this.step(input.logFile, "判壳的 preload 进了应用目录(dist/preload.mjs)", async () => {
167
+ const preload = join(input.appDir, "dist", "preload.mjs");
168
+ if (!(await exists(preload))) {
169
+ throw new CliError(
170
+ `壳的产物里没有 ${preload}:窗口的桥全在它里面(\`package.json\` 的 \`./preload\` 出口在不在?)`,
171
+ );
172
+ }
173
+ return preload;
174
+ });
175
+ await this.step(input.logFile, "让 electron-builder 的包遍历在 app 目录停下", async () => {
176
+ // 不写这个,electron-builder 会向上找到工作区、跑一遍 pnpm 收集(几十秒到几分钟,还可能改包)。
177
+ await writeFile(join(input.appDir, "pnpm-workspace.yaml"), "packages: []\n", "utf8");
178
+ });
179
+
180
+ await this.step(input.logFile, "写打包形态的启动器(部署值 → 壳)并改入口", async () => {
181
+ // 启动器是第一跳:Finder 启动没有环境变量,而 `userData` 只能在 ready 之前 `setPath`。
182
+ // 算法只有 `desktop-dirs.ts` 一处(壳不自己拼 appData),这里只把源码落到 app 目录。
183
+ await writeFile(join(input.appDir, BOOTSTRAP_FILE), packagedBootstrap(), "utf8");
184
+ const manifestPath = join(input.appDir, "package.json");
185
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as {
186
+ main?: string;
187
+ dependencies?: Record<string, string>;
188
+ };
189
+ // deploy 会把壳的 peer `electron` 装成 dependency,electron-builder 只允许它在 devDependencies。
190
+ // 只改清单:`node_modules/electron` 还要留着给它算版本。
191
+ if (manifest.dependencies?.electron !== undefined) delete manifest.dependencies.electron;
192
+ // **必须连包一起删**:`pnpm deploy` 把壳的 peer `electron` 装进了 `node_modules`,打包后
193
+ // `require("electron")` 会解析到那个 **npm 包**(导出的是可执行文件路径字符串),
194
+ // `electron.app` 于是是 `undefined`(症状:启动即崩 `Cannot read properties of undefined (reading 'setPath')`)。
195
+ // 版本已由 `electronVersion` 显式给出,不依赖它算。
196
+ await rm(join(input.appDir, "node_modules", "electron"), { recursive: true, force: true });
197
+ manifest.main = `./${BOOTSTRAP_FILE}`;
198
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
199
+ });
200
+ }
201
+
202
+ /**
203
+ * 跑一步并记日志(**同时写文件**:打包会跑几十秒到几分钟,控制台被截断时文件就是判据)。
204
+ * @param logFile - 日志文件。
205
+ * @param name - 步骤名。
206
+ * @param action - 这一步的动作。
207
+ * @returns 动作的返回值。
208
+ */
209
+ private async step<T>(logFile: string, name: string, action: () => Promise<T>): Promise<T> {
210
+ const startedAt = Date.now();
211
+ await this.note(logFile, `[bundle] ${name} …`);
212
+ try {
213
+ const result = await action();
214
+ await this.note(logFile, `[bundle] ${name} ${String(Date.now() - startedAt)}ms`);
215
+ return result;
216
+ } catch (error) {
217
+ const detail = error instanceof Error ? (error.message ?? String(error)) : String(error);
218
+ await this.note(
219
+ logFile,
220
+ `[bundle] ${name} 失败(${String(Date.now() - startedAt)}ms):${detail}`,
221
+ );
222
+ throw error;
223
+ }
224
+ }
225
+
226
+ /**
227
+ * 一行日志:控制台 + 文件。
228
+ * @param logFile - 日志文件。
229
+ * @param line - 文本。
230
+ */
231
+ private async note(logFile: string, line: string): Promise<void> {
232
+ this.logger.info("%s", line);
233
+ await appendFile(logFile, `${line}\n`, "utf8").catch(() => undefined);
234
+ }
235
+
236
+ /**
237
+ * @param result - 打包结果。
238
+ * @returns 安装后的路径。
239
+ */
240
+ async install(result: PackResult): Promise<string> {
241
+ const target = join(installRoot(), result.appDir.split("/").at(-1) ?? "app");
242
+ await mkdir(installRoot(), { recursive: true });
243
+ // **先删目标再复制**:`ditto` / `cp` 对已存在的目录都是**合并**语义——目标端独有的旧文件一个都不会走。
244
+ // 于是旧包、旧闭包、旧布局(上一代产物里的 `entry.mjs` / `src/client`)会与新产物混成一棵树,
245
+ // 症状是「同一份源码,装出来的应用里少了东西」(实测:旧 `client_modules` 留着 132 个上一版模块、
246
+ // 旧 `node_modules` 留着 11 个仓库里已删的包)。删掉再装,安装结果 = 产物的逐字节副本。
247
+ await rm(target, { recursive: true, force: true });
248
+ if (process.platform === "darwin") {
249
+ // macOS 上用 `ditto`:按原样保留 framework 的符号链接与元数据(签名的 .app 也靠它整份搬)。
250
+ // `maxBuffer` 放大:`ditto` 往 stderr 打进度/警告,默认 1MB 会炸出
251
+ // "stderr maxBuffer length exceeded"(看起来像安装失败,其实已经拷完了)。
252
+ await run("ditto", [result.appDir, target], { maxBuffer: 64 * 1024 * 1024 }).catch(
253
+ (error: unknown) => {
254
+ throw new CliError(
255
+ `安装到 ${target} 失败(先退出正在运行的旧版应用,或检查目标目录的写权限):${
256
+ error instanceof Error ? error.message : String(error)
257
+ }`,
258
+ );
259
+ },
260
+ );
261
+ return target;
262
+ }
263
+ await cp(result.appDir, target, { recursive: true, verbatimSymlinks: true });
264
+ return target;
265
+ }
266
+ }
267
+
268
+ /** 宿主产物里的两项文件(装配入口与清单)。 */
269
+ const RUNTIME_FILES = ["bootstrap.mjs", "package.json"] as const;
270
+
271
+ /** 宿主产物里的目录(前端静态面、源码面入口)——闭包不在这里:它由 `pnpm deploy` 直接装进目标。 */
272
+ const RUNTIME_DIRS = ["client_modules", "src"] as const;
273
+
274
+ /**
275
+ * 把宿主产物装进 `Resources/runtime`:**闭包直接 deploy 到目标**,其余(前端静态面与源码面入口)按清单复制。
276
+ *
277
+ * 为什么不再整份复制:`build` 的闭包是 900MB 级(`node_modules` 一份),复制一次要 20 秒量级、磁盘上还躺着
278
+ * 两份同内容。而 `pnpm deploy` 本来就是「按清单装出一份可分发的应用」的那条规则——直接把它指到最终位置,
279
+ * 就少一次搬运,也少一份副本(`build` 那份仍留给 dev / preview 用)。
280
+ *
281
+ * 为什么其余的还要逐项复制:`<outputDir>` 里还躺着打包自己的中间物(`shell-app/`、`.app`、`bundle.log`),
282
+ * 而 `Resources/runtime` 就在其中——整份复制等于把产物目录往它自己的子目录里拷(Node 直接
283
+ * `ERR_FS_CP_EINVAL`)。清单本身就是「一份可分发的应用」的定义(设计决定 4)。
284
+ * @param input - app 目录、workspace 根与宿主产物根。
285
+ * @param runtimeDir - 目标(`Resources/runtime`)。
286
+ */
287
+ async function copyRuntime(input: PackInput, runtimeDir: string): Promise<void> {
288
+ const absent: string[] = [];
289
+ for (const name of [...RUNTIME_FILES, ...RUNTIME_DIRS]) {
290
+ if (!(await exists(join(input.profileDir, name)))) absent.push(name);
291
+ }
292
+ if (absent.length > 0) {
293
+ throw new CliError(
294
+ `宿主产物不齐(${input.profileDir}):缺 ${absent.join("、")}(先跑 zephyr build)。`,
295
+ );
296
+ }
297
+ await rm(runtimeDir, { recursive: true, force: true });
298
+ await mkdir(runtimeDir, { recursive: true });
299
+ // 闭包:`deploy` 只接受空目录。**装到 `target` 内的暂存目录再 rename 进来**——直接 deploy 进 `.app` 会在
300
+ // 写 `.pnpm` 里的文件时 `EPERM`(实测 `write …/Resources/runtime/node_modules/.pnpm/…: Operation not
301
+ // permitted`;同一路径下 mkdir / hardlink / clonefile 都正常,是 deploy 自己那套写法的限制)。
302
+ // 暂存与目标同设备,`rename` 是原子移动:既没有那 900MB 的复制,也不受 `.app` 内那条限制影响。
303
+ const staging = await mkdtemp(join(dirname(input.profileDir), ".zephyr-bundle-deploy-"));
304
+ try {
305
+ await run(
306
+ "pnpm",
307
+ [
308
+ "--filter",
309
+ await appPackageNameOf(input.workspace),
310
+ "--config.inject-workspace-packages=true",
311
+ "deploy",
312
+ "--prod",
313
+ "--config.strictDepBuilds=false",
314
+ staging,
315
+ ],
316
+ { cwd: input.workspace, maxBuffer: 64 * 1024 * 1024 },
317
+ );
318
+ await rename(join(staging, "node_modules"), join(runtimeDir, "node_modules"));
319
+ } finally {
320
+ await rm(staging, { recursive: true, force: true });
321
+ }
322
+ // `verbatimSymlinks` 是必须的:pnpm 的相对链要原样保留,否则 `cp` 会把链接解析成绝对路径,
323
+ // 装出来的应用指回构建机的源码树(冒烟会直接报「逃逸链接」)。
324
+ for (const name of RUNTIME_FILES) {
325
+ await cp(join(input.profileDir, name), join(runtimeDir, name), { verbatimSymlinks: true });
326
+ }
327
+ for (const name of RUNTIME_DIRS) {
328
+ await cp(join(input.profileDir, name), join(runtimeDir, name), {
329
+ recursive: true,
330
+ verbatimSymlinks: true,
331
+ });
332
+ }
333
+ }
334
+
335
+ /**
336
+ * 工作区根(`pnpm-workspace.yaml` 所在目录):`pnpm --filter` 要在它下面跑。
337
+ * @returns 绝对路径。
338
+ * @throws CliError 找不到工作区根。
339
+ */
340
+ async function workspaceRootOf(): Promise<string> {
341
+ for (let dir = shellPackageDir(); ; dir = dirname(dir)) {
342
+ if (await exists(join(dir, "pnpm-workspace.yaml"))) return dir;
343
+ if (dirname(dir) === dir) {
344
+ throw new CliError("找不到 pnpm-workspace.yaml:desktop bundle 要在 pnpm 工作区里跑。");
345
+ }
346
+ }
347
+ }
348
+
349
+ /**
350
+ * 壳包的目录。
351
+ * @returns 绝对路径。
352
+ */
353
+ function shellPackageDir(): string {
354
+ const entry = import.meta.resolve(`${SHELL_PACKAGE}/package.json`);
355
+ return dirname(new URL(entry).pathname);
356
+ }
357
+
358
+ /**
359
+ * 在产物目录里找一个应用(macOS 是 `.app`,其它平台是平铺的目录)。
360
+ * @param output - `directories.output`。
361
+ * @returns 应用目录的绝对路径。
362
+ */
363
+ async function discoverAppDir(output: string): Promise<string> {
364
+ const outer = await readdir(output).catch(() => [] as string[]);
365
+ for (const entry of outer) {
366
+ const platformDir = join(output, entry);
367
+ const inner = await readdir(platformDir).catch(() => [] as string[]);
368
+ const app = inner.find((name) => name.endsWith(".app"));
369
+ if (app !== undefined) return join(platformDir, app);
370
+ }
371
+ return output;
372
+ }
373
+
374
+ /**
375
+ * 系统应用目录(macOS 是 `/Applications`,Linux 是 `~/.local/share/applications`)。
376
+ * @returns 目录。
377
+ */
378
+ function installRoot(): string {
379
+ if (process.platform === "darwin") return "/Applications";
380
+ const home = process.env.HOME ?? "";
381
+ return join(home, ".local", "share", "applications");
382
+ }
383
+
384
+ /**
385
+ * 文件在不在(异步:命令行不占事件循环)。
386
+ * @param path - 绝对路径。
387
+ * @returns 判断结果。
388
+ */
389
+ async function exists(path: string): Promise<boolean> {
390
+ try {
391
+ await access(path);
392
+ return true;
393
+ } catch {
394
+ return false;
395
+ }
396
+ }