@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,526 @@
1
+ import { access, appendFile, cp, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { execFile, spawn } from "node:child_process";
3
+ import { dirname, join, sep } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { Injectable, Logger, inject } from "@morlay/zephyr";
6
+ import { CliError, appPackageNameOf } from "@morlay/zephyr-cli";
7
+ import { createRequire } from "node:module";
8
+ import { pathToFileURL } from "node:url";
9
+ // src/desktop-dirs.ts
10
+ /** Electron `userData` 在应用根下的目录名(各形态共用一条规则)。 */
11
+ const USER_DATA_SUBDIR = "electron";
12
+ /**
13
+ * 操作系统的 appData 目录(与 Electron `app.getPath("appData")` 同一口径)。
14
+ *
15
+ * **本仓库只有这一处算 appData**:壳侧只收结果。
16
+ * @param env - 环境变量(测试可注入)。
17
+ * @param platform - 平台(测试可注入)。
18
+ * @param home - 用户主目录。
19
+ * @returns 绝对路径。
20
+ */
21
+ function appDataHomeOf(env, platform, home) {
22
+ if (platform === "darwin") return join(home, "Library", "Application Support");
23
+ if (platform === "win32") return env.APPDATA ?? join(home, "AppData", "Roaming");
24
+ const xdg = env.XDG_CONFIG_HOME;
25
+ return xdg === void 0 || xdg === "" ? join(home, ".config") : xdg;
26
+ }
27
+ /**
28
+ * 应用根:`<appData>/<desktop.id>`(打包 / bundle / preview),dev 形态多一段 `dev`。
29
+ *
30
+ * 不做「按工作区哈希隔离」:目录名要可读;多工作区并行靠显式 `ZEPHYR_DESKTOP_USER_DATA`。
31
+ * @param input - appData 目录、桌面身份的应用 id 与形态。
32
+ * @returns 绝对路径。
33
+ */
34
+ function appRootOf(input) {
35
+ const root = join(input.appDataHome, input.desktopId);
36
+ return input.form === "dev" ? join(root, "dev") : root;
37
+ }
38
+ /**
39
+ * `userData`:应用根下的 `electron/`(Electron 的 `setPath` 不会替你建目录,调用方负责 `mkdir`)。
40
+ * @param appRoot - 应用根({@link appRootOf} 的结果)。
41
+ * @returns 绝对路径。
42
+ */
43
+ function userDataDirOf(appRoot) {
44
+ return join(appRoot, USER_DATA_SUBDIR);
45
+ }
46
+ /**
47
+ * 打包形态的启动器源码:算出部署值交给壳,然后加载壳的主进程入口。
48
+ *
49
+ * 为什么要有它:Finder 启动的进程没有环境变量,而 `userData` 只能在 ready 之前 `setPath`。
50
+ * 这份源码由 {@link import("./packager.ts")} 在打包时写进 app 目录,作为 `main` 的第一跳;
51
+ * 算法只有这里一处(壳不再自己算 appData)。
52
+ * @returns 启动器源码(ESM)。
53
+ */
54
+ function packagedBootstrap() {
55
+ return `// 打包形态的启动器:由 @morlay/zephyr-desktop-bundle 在打包时写入 app 目录。
56
+ // 它只做一件事:把部署值(userData 与数据根)交给壳,然后加载壳的主进程入口。
57
+ // 显式 ZEPHYR_DESKTOP_USER_DATA 优先(多实例 / 临时 profile 都靠它)。
58
+ import { app } from "electron";
59
+ import { readFile } from "node:fs/promises";
60
+ import { join } from "node:path";
61
+
62
+ const desktop = JSON.parse(await readFile(join(process.resourcesPath, "desktop.json"), "utf8"));
63
+ const root = join(app.getPath("appData"), desktop.id);
64
+ if (process.env.ZEPHYR_DESKTOP_USER_DATA === undefined) {
65
+ process.env.ZEPHYR_DESKTOP_USER_DATA = join(root, "${USER_DATA_SUBDIR}");
66
+ }
67
+ if (process.env.ZEPHYR_DESKTOP_DATA_DIR === undefined) {
68
+ process.env.ZEPHYR_DESKTOP_DATA_DIR = root;
69
+ }
70
+ // **同时把写法递过去**:root 就是 xdg 在 darwin/win32 上的落点(app.getPath("appData")/<id>),
71
+ // 而壳那边 dataDirSpec 的缺省是 workspace——不递的话,路径对、日志与 deployment-line 里的写法错
72
+ // (显示成「数据跟着工作区走」,实际落在应用数据目录)。写法只有启动器这一处算法,所以也在这里定。
73
+ if (process.env.ZEPHYR_DESKTOP_DATA_DIR_SPEC === undefined) {
74
+ process.env.ZEPHYR_DESKTOP_DATA_DIR_SPEC = "xdg";
75
+ }
76
+ await import("./dist/main.mjs");
77
+ `;
78
+ }
79
+ // src/runtime-smoke.ts
80
+ /** 壳与 loader 必须能从闭包解析的两项(少了装出来的应用起不来)。 */
81
+ const REQUIRED_MODULES = ["@morlay/zephyr", "@morlay/dsh-oxc-node"];
82
+ /**
83
+ * 跑三条判据,返回发现(**不抛**,好让调用方拼一条完整的错误)。
84
+ * @param runtimeDir - `Resources/runtime`(复制后的真目录)。
85
+ * @param actions - 解析与加载动作(测试可换替身)。
86
+ * @returns 发现报告。
87
+ */
88
+ async function runtimeSmokeOf(runtimeDir, actions = {}) {
89
+ const resolve = actions.resolve ?? resolveFrom;
90
+ const load = actions.load ?? loadEntry;
91
+ const links = await scopeLinksOf(runtimeDir);
92
+ const missing = [];
93
+ for (const name of [...REQUIRED_MODULES, ...await dependencyNamesOf(join(runtimeDir, "package.json"))]) if (await resolve(runtimeDir, name) === void 0) missing.push(name);
94
+ missing.push(...await missingInScopedOf(runtimeDir));
95
+ const loadFailure = await load(runtimeDir, join(runtimeDir, "bootstrap.mjs"));
96
+ return {
97
+ links,
98
+ missing: [...new Set(missing)],
99
+ ...loadFailure === void 0 ? {} : { loadFailure }
100
+ };
101
+ }
102
+ /**
103
+ * 三条判据有任一不成立就抛(装配链在打包这一步停下,而不是等到用户双击)。
104
+ *
105
+ * 链接分两类:realpath 在闭包内的是**合法**(pnpm 的正常形态),逃逸的才进错误。
106
+ * @param runtimeDir - `Resources/runtime`。
107
+ * @param actions - 解析与加载动作(测试可换替身)。
108
+ * @returns 通过时的报告(打包日志用它记「几个链接、几个逃逸」)。
109
+ * @throws CliError 有逃逸链接、缺包或入口加载失败。
110
+ */
111
+ async function assertRuntimeSmoke(runtimeDir, actions = {}) {
112
+ const report = await runtimeSmokeOf(runtimeDir, actions);
113
+ const escaping = report.links.filter((link) => !link.inside);
114
+ const problems = [];
115
+ if (escaping.length > 0) problems.push(`闭包里有逃逸链接(realpath 不在 ${runtimeDir} 内):${escaping.map((link) => `${link.name} -> ${link.target}`).join("、")}`);
116
+ if (report.missing.length > 0) problems.push(`从闭包解析不到:${report.missing.join("、")}`);
117
+ if (report.loadFailure !== void 0) problems.push(`装配文件 bootstrap.mjs 加载失败:${report.loadFailure}`);
118
+ if (problems.length === 0) return report;
119
+ throw new CliError([`运行时闭包不自包含(${runtimeDir}):`, ...problems.map((line) => ` · ${line}`)].join("\n"));
120
+ }
121
+ /**
122
+ * 打包产物里的 `Resources` 目录:mac 是 `<app>/Contents/Resources`,其它平台 `<app>/resources`。
123
+ * @param appDir - 打包产出的应用目录。
124
+ * @returns Resources 目录。
125
+ * @throws CliError 两种布局都不存在。
126
+ */
127
+ async function resourcesDirOf(appDir) {
128
+ const candidates = [join(appDir, "Contents", "Resources"), join(appDir, "resources")];
129
+ for (const candidate of candidates) try {
130
+ if ((await stat(candidate)).isDirectory()) return candidate;
131
+ } catch {}
132
+ throw new CliError(`找不到打包产物里的 Resources 目录:试过 ${candidates.join("、")}。`);
133
+ }
134
+ /**
135
+ * `node_modules/@morlay/*` 下的全部 symlink,并判断 realpath 是否仍在闭包内。
136
+ *
137
+ * 允许 symlink:pnpm 的顶层本来就是「相对链指进闭包内的 `.pnpm`」。判据是**落点**而不是形态——
138
+ * 绝对路径、指回源码、或干脆指向闭包外(含悬空)都算逃逸。
139
+ * @param runtimeDir - 闭包根。
140
+ * @returns 条目(按名字排序);没有 scope 目录就是空。
141
+ */
142
+ async function scopeLinksOf(runtimeDir) {
143
+ const scope = join(runtimeDir, "node_modules", "@morlay");
144
+ const entries = await readdir(scope, { withFileTypes: true }).catch(() => []);
145
+ const root = await realpath(runtimeDir).catch(() => runtimeDir);
146
+ const links = [];
147
+ for (const entry of entries) {
148
+ if (!entry.isSymbolicLink()) continue;
149
+ const path = join(scope, entry.name);
150
+ const target = await readlink(path).catch(() => "");
151
+ const resolved = await realpath(path).catch(() => void 0);
152
+ links.push({
153
+ name: entry.name,
154
+ target,
155
+ inside: resolved !== void 0 && (resolved === root || resolved.startsWith(`${root}${sep}`))
156
+ });
157
+ }
158
+ return links.sort((left, right) => left.name.localeCompare(right.name));
159
+ }
160
+ /**
161
+ * 一份清单里声明的依赖名。
162
+ * @param manifestPath - `package.json` 的绝对路径。
163
+ * @returns 依赖名(读不到清单就是空)。
164
+ */
165
+ async function dependencyNamesOf(manifestPath) {
166
+ const raw = await readFile(manifestPath, "utf8").catch(() => void 0);
167
+ if (raw === void 0) return [];
168
+ try {
169
+ const manifest = JSON.parse(raw);
170
+ return Object.keys(manifest.dependencies ?? {});
171
+ } catch {
172
+ return [];
173
+ }
174
+ }
175
+ /**
176
+ * `@morlay/*` 各包自己声明的依赖里解析不到的那些(从**真身**解析:CJS 的 `createRequire` 对
177
+ * 符号链接路径按字面走,会误报 MODULE_NOT_FOUND——实测 `dsh-storage` 的 storage-json 就是这样)。
178
+ * @param runtimeDir - 闭包根。
179
+ * @returns `@morlay/<包> -> <缺的包>` 形式的条目。
180
+ */
181
+ async function missingInScopedOf(runtimeDir) {
182
+ const scope = join(runtimeDir, "node_modules", "@morlay");
183
+ const entries = await readdir(scope, { withFileTypes: true }).catch(() => []);
184
+ const missing = [];
185
+ for (const entry of entries) {
186
+ const real = await realpath(join(scope, entry.name, "package.json")).catch(() => void 0);
187
+ if (real === void 0) continue;
188
+ for (const name of await dependencyNamesOf(real)) if (await resolveFromManifest(real, name) === void 0) missing.push(`@morlay/${entry.name} -> ${name}`);
189
+ }
190
+ return missing;
191
+ }
192
+ /**
193
+ * 从子进程的 stderr 里挑出最像原因的那一行(栈第一行通常是 node 内部路径,读的人看不出问题)。
194
+ * @param stderr - 子进程的 stderr。
195
+ * @returns 一行说明(挑不到就给尾部 500 字)。
196
+ */
197
+ function firstErrorLineOf(stderr) {
198
+ const lines = stderr.split("\n").map((line) => line.trim()).filter((line) => line !== "");
199
+ return (lines.find((line) => /^Error\b/u.test(line)) ?? lines.find((line) => /Cannot find|ERR_(MODULE|PACKAGE)_NOT_FOUND/u.test(line)) ?? lines.at(-1) ?? "").slice(-500);
200
+ }
201
+ /**
202
+ * 从闭包里解析一个包:先按包名,再按它的 `package.json`。
203
+ *
204
+ * 为什么要退一步:只给子路径导出(没有 `.`)的包(例如 `@oxc-project/runtime`)按包名解析会报
205
+ * `ERR_PACKAGE_PATH_NOT_EXPORTED`——那是**包装好了**,不是缺包。缺包时两种解析都失败。
206
+ * @param runtimeDir - 闭包根。
207
+ * @param name - 包名。
208
+ * @returns 入口(或清单)路径,或 `undefined`(确实没有这个包)。
209
+ */
210
+ function resolveFrom(runtimeDir, name) {
211
+ return resolveFromManifest(join(runtimeDir, "package.json"), name);
212
+ }
213
+ /**
214
+ * 从某份清单所在的位置解析一个包(先按包名,再按清单存在性)。
215
+ * @param manifestPath - 基准 `package.json`(用它的**真身**:符号链接路径会误报)。
216
+ * @param name - 包名。
217
+ * @returns 入口(或清单)路径,或 `undefined`。
218
+ */
219
+ async function resolveFromManifest(manifestPath, name) {
220
+ const require = createRequire(manifestPath);
221
+ try {
222
+ return require.resolve(name);
223
+ } catch {}
224
+ for (const base of require.resolve.paths(name) ?? []) {
225
+ const manifest = join(base, name, "package.json");
226
+ try {
227
+ await readFile(manifest);
228
+ return manifest;
229
+ } catch {}
230
+ }
231
+ }
232
+ /**
233
+ * 在闭包自己的 loader 下加载装配文件(子进程:不把宿主拖进打包进程)。
234
+ * @param runtimeDir - 宿主目录。
235
+ * @param entry - `bootstrap.mjs` 的绝对路径。
236
+ * @returns 失败说明,成功为 `undefined`。
237
+ */
238
+ async function loadEntry(runtimeDir, entry) {
239
+ const loader = await resolveFrom(runtimeDir, "@morlay/dsh-oxc-node");
240
+ if (loader === void 0) return "闭包里没有 @morlay/dsh-oxc-node(loader)";
241
+ const script = `await import(${JSON.stringify(pathToFileURL(entry).href)});`;
242
+ const env = { ...process.env };
243
+ delete env.NODE_OPTIONS;
244
+ delete env.ELECTRON_RUN_AS_NODE;
245
+ return new Promise((done) => {
246
+ const child = spawn(process.execPath, [
247
+ "--import",
248
+ pathToFileURL(loader).href,
249
+ "--eval",
250
+ script
251
+ ], {
252
+ cwd: runtimeDir,
253
+ env,
254
+ stdio: [
255
+ "ignore",
256
+ "ignore",
257
+ "pipe"
258
+ ]
259
+ });
260
+ let stderr = "";
261
+ child.stderr.on("data", (chunk) => {
262
+ stderr += chunk.toString("utf8");
263
+ });
264
+ child.once("error", (error) => done(error.message));
265
+ child.once("close", (code) => {
266
+ done(code === 0 ? void 0 : `子进程退出码 ${String(code)}:${firstErrorLineOf(stderr)}`);
267
+ });
268
+ });
269
+ }
270
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/decorate.js
271
+ function __decorate(decorators, target, key, desc) {
272
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
273
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
274
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
275
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
276
+ }
277
+ // src/packager.ts
278
+ const run = promisify(execFile);
279
+ /** 壳的包名(`dist/` 从这里取)。 */
280
+ const SHELL_PACKAGE = "@morlay/zephyr-desktop-shell";
281
+ /** 打包形态的启动器文件名(app 目录里,`main` 指它)。 */
282
+ const BOOTSTRAP_FILE = "bootstrap.mjs";
283
+ let Packager = class Packager {};
284
+ Packager = __decorate([Injectable()], Packager);
285
+ let PackagerDefault = class PackagerDefault extends Packager {
286
+ logger = inject(Logger);
287
+ /**
288
+ * @param config - electron-builder 配置。
289
+ * @param input - app 目录、宿主闭包与日志文件。
290
+ * @returns 产物位置。
291
+ */
292
+ async pack(config, input) {
293
+ await this.assemble(input);
294
+ const module = await import("electron-builder").catch(() => void 0);
295
+ if (module?.build === void 0) throw new CliError("没有装 electron-builder:desktop bundle 需要它(peerDependency)。");
296
+ process.chdir(input.appDir);
297
+ const appDir = (await this.step(input.logFile, `electron-builder 归档(asar)→ ${config.directories.output}`, () => module.build?.({
298
+ config,
299
+ dir: true
300
+ }) ?? Promise.resolve([])))[0] ?? await discoverAppDir(config.directories.output);
301
+ const runtimeDir = join(await resourcesDirOf(appDir), "runtime");
302
+ await this.step(input.logFile, `装宿主产物 → ${runtimeDir}`, () => copyRuntime(input, runtimeDir));
303
+ await this.step(input.logFile, "打包期冒烟:闭包自包含 + 入口能被 loader 加载", async () => {
304
+ await this.note(input.logFile, `[bundle] 冒烟对象:${runtimeDir}`);
305
+ const report = await assertRuntimeSmoke(runtimeDir);
306
+ const escaping = report.links.filter((link) => !link.inside).length;
307
+ await this.note(input.logFile, `[bundle] 闭包链接:${String(report.links.length)} 个,逃逸 ${String(escaping)} 个`);
308
+ return runtimeDir;
309
+ });
310
+ return { appDir };
311
+ }
312
+ /**
313
+ * 备 app 目录:deploy 壳(依赖合法进 asar)→ 宿主闭包放 `profile/` → 改入口。
314
+ * @param input - app 目录与宿主闭包。
315
+ */
316
+ async assemble(input) {
317
+ await this.step(input.logFile, `清空 app 目录(${input.appDir})`, async () => {
318
+ await rm(input.appDir, {
319
+ recursive: true,
320
+ force: true
321
+ });
322
+ await mkdir(input.appDir, { recursive: true });
323
+ });
324
+ await this.step(input.logFile, `重建壳包(${SHELL_PACKAGE} 的 dist)`, async () => {
325
+ await run("pnpm", [
326
+ "exec",
327
+ "devkit",
328
+ "build",
329
+ "--filter",
330
+ SHELL_PACKAGE
331
+ ], { cwd: await workspaceRootOf() });
332
+ });
333
+ await this.step(input.logFile, `pnpm --filter ${SHELL_PACKAGE} deploy → ${input.appDir}`, async () => {
334
+ await run("pnpm", [
335
+ "--filter",
336
+ SHELL_PACKAGE,
337
+ "deploy",
338
+ "--prod",
339
+ "--ignore-scripts",
340
+ input.appDir
341
+ ], { cwd: await workspaceRootOf() });
342
+ });
343
+ await this.step(input.logFile, "判壳的 preload 进了应用目录(dist/preload.mjs)", async () => {
344
+ const preload = join(input.appDir, "dist", "preload.mjs");
345
+ if (!await exists(preload)) throw new CliError(`壳的产物里没有 ${preload}:窗口的桥全在它里面(\`package.json\` 的 \`./preload\` 出口在不在?)`);
346
+ return preload;
347
+ });
348
+ await this.step(input.logFile, "让 electron-builder 的包遍历在 app 目录停下", async () => {
349
+ await writeFile(join(input.appDir, "pnpm-workspace.yaml"), "packages: []\n", "utf8");
350
+ });
351
+ await this.step(input.logFile, "写打包形态的启动器(部署值 → 壳)并改入口", async () => {
352
+ await writeFile(join(input.appDir, BOOTSTRAP_FILE), packagedBootstrap(), "utf8");
353
+ const manifestPath = join(input.appDir, "package.json");
354
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
355
+ if (manifest.dependencies?.electron !== void 0) delete manifest.dependencies.electron;
356
+ await rm(join(input.appDir, "node_modules", "electron"), {
357
+ recursive: true,
358
+ force: true
359
+ });
360
+ manifest.main = `./${BOOTSTRAP_FILE}`;
361
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
362
+ });
363
+ }
364
+ /**
365
+ * 跑一步并记日志(**同时写文件**:打包会跑几十秒到几分钟,控制台被截断时文件就是判据)。
366
+ * @param logFile - 日志文件。
367
+ * @param name - 步骤名。
368
+ * @param action - 这一步的动作。
369
+ * @returns 动作的返回值。
370
+ */
371
+ async step(logFile, name, action) {
372
+ const startedAt = Date.now();
373
+ await this.note(logFile, `[bundle] ${name} …`);
374
+ try {
375
+ const result = await action();
376
+ await this.note(logFile, `[bundle] ${name} ${String(Date.now() - startedAt)}ms`);
377
+ return result;
378
+ } catch (error) {
379
+ const detail = error instanceof Error ? error.message ?? String(error) : String(error);
380
+ await this.note(logFile, `[bundle] ${name} 失败(${String(Date.now() - startedAt)}ms):${detail}`);
381
+ throw error;
382
+ }
383
+ }
384
+ /**
385
+ * 一行日志:控制台 + 文件。
386
+ * @param logFile - 日志文件。
387
+ * @param line - 文本。
388
+ */
389
+ async note(logFile, line) {
390
+ this.logger.info("%s", line);
391
+ await appendFile(logFile, `${line}\n`, "utf8").catch(() => void 0);
392
+ }
393
+ /**
394
+ * @param result - 打包结果。
395
+ * @returns 安装后的路径。
396
+ */
397
+ async install(result) {
398
+ const target = join(installRoot(), result.appDir.split("/").at(-1) ?? "app");
399
+ await mkdir(installRoot(), { recursive: true });
400
+ await rm(target, {
401
+ recursive: true,
402
+ force: true
403
+ });
404
+ if (process.platform === "darwin") {
405
+ await run("ditto", [result.appDir, target], { maxBuffer: 67108864 }).catch((error) => {
406
+ throw new CliError(`安装到 ${target} 失败(先退出正在运行的旧版应用,或检查目标目录的写权限):${error instanceof Error ? error.message : String(error)}`);
407
+ });
408
+ return target;
409
+ }
410
+ await cp(result.appDir, target, {
411
+ recursive: true,
412
+ verbatimSymlinks: true
413
+ });
414
+ return target;
415
+ }
416
+ };
417
+ PackagerDefault = __decorate([Injectable()], PackagerDefault);
418
+ /** 宿主产物里的两项文件(装配入口与清单)。 */
419
+ const RUNTIME_FILES = ["bootstrap.mjs", "package.json"];
420
+ /** 宿主产物里的目录(前端静态面、源码面入口)——闭包不在这里:它由 `pnpm deploy` 直接装进目标。 */
421
+ const RUNTIME_DIRS = ["client_modules", "src"];
422
+ /**
423
+ * 把宿主产物装进 `Resources/runtime`:**闭包直接 deploy 到目标**,其余(前端静态面与源码面入口)按清单复制。
424
+ *
425
+ * 为什么不再整份复制:`build` 的闭包是 900MB 级(`node_modules` 一份),复制一次要 20 秒量级、磁盘上还躺着
426
+ * 两份同内容。而 `pnpm deploy` 本来就是「按清单装出一份可分发的应用」的那条规则——直接把它指到最终位置,
427
+ * 就少一次搬运,也少一份副本(`build` 那份仍留给 dev / preview 用)。
428
+ *
429
+ * 为什么其余的还要逐项复制:`<outputDir>` 里还躺着打包自己的中间物(`shell-app/`、`.app`、`bundle.log`),
430
+ * 而 `Resources/runtime` 就在其中——整份复制等于把产物目录往它自己的子目录里拷(Node 直接
431
+ * `ERR_FS_CP_EINVAL`)。清单本身就是「一份可分发的应用」的定义(设计决定 4)。
432
+ * @param input - app 目录、workspace 根与宿主产物根。
433
+ * @param runtimeDir - 目标(`Resources/runtime`)。
434
+ */
435
+ async function copyRuntime(input, runtimeDir) {
436
+ const absent = [];
437
+ for (const name of [...RUNTIME_FILES, ...RUNTIME_DIRS]) if (!await exists(join(input.profileDir, name))) absent.push(name);
438
+ if (absent.length > 0) throw new CliError(`宿主产物不齐(${input.profileDir}):缺 ${absent.join("、")}(先跑 zephyr build)。`);
439
+ await rm(runtimeDir, {
440
+ recursive: true,
441
+ force: true
442
+ });
443
+ await mkdir(runtimeDir, { recursive: true });
444
+ const staging = await mkdtemp(join(dirname(input.profileDir), ".zephyr-bundle-deploy-"));
445
+ try {
446
+ await run("pnpm", [
447
+ "--filter",
448
+ await appPackageNameOf(input.workspace),
449
+ "--config.inject-workspace-packages=true",
450
+ "deploy",
451
+ "--prod",
452
+ "--config.strictDepBuilds=false",
453
+ staging
454
+ ], {
455
+ cwd: input.workspace,
456
+ maxBuffer: 67108864
457
+ });
458
+ await rename(join(staging, "node_modules"), join(runtimeDir, "node_modules"));
459
+ } finally {
460
+ await rm(staging, {
461
+ recursive: true,
462
+ force: true
463
+ });
464
+ }
465
+ for (const name of RUNTIME_FILES) await cp(join(input.profileDir, name), join(runtimeDir, name), { verbatimSymlinks: true });
466
+ for (const name of RUNTIME_DIRS) await cp(join(input.profileDir, name), join(runtimeDir, name), {
467
+ recursive: true,
468
+ verbatimSymlinks: true
469
+ });
470
+ }
471
+ /**
472
+ * 工作区根(`pnpm-workspace.yaml` 所在目录):`pnpm --filter` 要在它下面跑。
473
+ * @returns 绝对路径。
474
+ * @throws CliError 找不到工作区根。
475
+ */
476
+ async function workspaceRootOf() {
477
+ for (let dir = shellPackageDir();; dir = dirname(dir)) {
478
+ if (await exists(join(dir, "pnpm-workspace.yaml"))) return dir;
479
+ if (dirname(dir) === dir) throw new CliError("找不到 pnpm-workspace.yaml:desktop bundle 要在 pnpm 工作区里跑。");
480
+ }
481
+ }
482
+ /**
483
+ * 壳包的目录。
484
+ * @returns 绝对路径。
485
+ */
486
+ function shellPackageDir() {
487
+ const entry = import.meta.resolve(`${SHELL_PACKAGE}/package.json`);
488
+ return dirname(new URL(entry).pathname);
489
+ }
490
+ /**
491
+ * 在产物目录里找一个应用(macOS 是 `.app`,其它平台是平铺的目录)。
492
+ * @param output - `directories.output`。
493
+ * @returns 应用目录的绝对路径。
494
+ */
495
+ async function discoverAppDir(output) {
496
+ const outer = await readdir(output).catch(() => []);
497
+ for (const entry of outer) {
498
+ const platformDir = join(output, entry);
499
+ const app = (await readdir(platformDir).catch(() => [])).find((name) => name.endsWith(".app"));
500
+ if (app !== void 0) return join(platformDir, app);
501
+ }
502
+ return output;
503
+ }
504
+ /**
505
+ * 系统应用目录(macOS 是 `/Applications`,Linux 是 `~/.local/share/applications`)。
506
+ * @returns 目录。
507
+ */
508
+ function installRoot() {
509
+ if (process.platform === "darwin") return "/Applications";
510
+ const home = process.env.HOME ?? "";
511
+ return join(home, ".local", "share", "applications");
512
+ }
513
+ /**
514
+ * 文件在不在(异步:命令行不占事件循环)。
515
+ * @param path - 绝对路径。
516
+ * @returns 判断结果。
517
+ */
518
+ async function exists(path) {
519
+ try {
520
+ await access(path);
521
+ return true;
522
+ } catch {
523
+ return false;
524
+ }
525
+ }
526
+ export { appRootOf as a, appDataHomeOf as i, PackagerDefault as n, userDataDirOf as o, __decorate as r, Packager as t };
@@ -0,0 +1,130 @@
1
+ import { ResolvedConfig, ZephyrLayout } from "@morlay/zephyr-cli";
2
+ /** 三平台图标的路径(缺的就是没生成)。 */
3
+ interface PreparedIcons {
4
+ readonly mac?: string;
5
+ readonly linux?: string;
6
+ readonly win?: string;
7
+ }
8
+ /** 一份可交给 electron-builder 的配置(字段子集,够本次用)。 */
9
+ interface ElectronBuilderConfig {
10
+ /**
11
+ * Electron 版本:**显式给**。
12
+ *
13
+ * app 目录是应用闭包,里面没有 `electron`(那是壳的 peer,由 electron-builder 自己提供),
14
+ * 不写这一项它会去 app 目录的 `node_modules` 里算版本并报
15
+ * `Cannot compute electron version from installed node modules`。
16
+ */
17
+ readonly electronVersion: string;
18
+ readonly appId: string;
19
+ readonly productName: string;
20
+ readonly artifactName: string;
21
+ readonly asar: boolean;
22
+ readonly asarUnpack: readonly string[];
23
+ /** 不做 native 重编(原生模块属于宿主闭包,已按随包 node 的 ABI 装好)。 */
24
+ readonly npmRebuild: boolean;
25
+ readonly directories: {
26
+ readonly output: string;
27
+ };
28
+ readonly files: readonly string[];
29
+ readonly extraResources: readonly {
30
+ readonly from: string;
31
+ readonly to: string;
32
+ }[];
33
+ readonly mac: {
34
+ readonly category: string;
35
+ readonly identity: null;
36
+ readonly icon?: string;
37
+ };
38
+ readonly win: {
39
+ readonly icon?: string;
40
+ };
41
+ readonly linux: {
42
+ readonly category: string;
43
+ readonly icon?: string;
44
+ };
45
+ }
46
+ /** 推导所需的三样东西。 */
47
+ interface ElectronBuilderInput {
48
+ /** 解析后的工作区配置(`desktop.id` / `desktop.name` 从它来)。 */
49
+ readonly resolved: ResolvedConfig;
50
+ /** 产物布局。 */
51
+ readonly layout: ZephyrLayout;
52
+ /** Electron 版本(由调用方解析:app 目录是应用闭包,里面没有 `electron`)。 */
53
+ readonly electronVersion: string;
54
+ /** 三平台图标(`desktop.icon` 的生成物);没配图标就是空。 */
55
+ readonly icons?: PreparedIcons;
56
+ }
57
+ /**
58
+ * 把配置与布局推导成 electron-builder 的配置。
59
+ * @param input - 工作区配置、布局与壳目录。
60
+ * @returns 配置对象。
61
+ * @throws CliError 缺 `desktop.id` / `desktop.name`。
62
+ */
63
+ declare function electronBuilderConfigOf(input: ElectronBuilderInput): ElectronBuilderConfig;
64
+ /** 一次打包的结果。 */
65
+ interface PackResult {
66
+ /** 产出的应用目录(`.zephyr/app/<平台>-<架构>/<产品名>.app` 之类)。 */
67
+ readonly appDir: string;
68
+ }
69
+ /** 打包所需的输入。 */
70
+ interface PackInput {
71
+ /** app 目录(electron-builder 的 projectDir)。 */
72
+ readonly appDir: string;
73
+ /** 宿主的那一份(`build` 的 `<outputDir>`:`bootstrap.mjs` + `client_modules/` + 闭包 + 源码面入口)。 */
74
+ readonly profileDir: string;
75
+ /** workspace 根:闭包**直接 deploy 到 `Resources/runtime`**(不再复制那 900MB)。 */
76
+ readonly workspace: string;
77
+ /** 步骤日志文件(每步一行,含耗时):卡住时从这里看最后一条。 */
78
+ readonly logFile: string;
79
+ }
80
+ /** 打包契约。 */
81
+ declare abstract class Packager {
82
+ /**
83
+ * 打一个当前平台的应用目录。
84
+ * @param config - electron-builder 配置。
85
+ * @param input - app 目录、宿主闭包与日志文件。
86
+ * @returns 产物位置。
87
+ */
88
+ abstract pack(config: ElectronBuilderConfig, input: PackInput): Promise<PackResult>;
89
+ /**
90
+ * 把产物装进系统应用目录。
91
+ * @param result - 打包结果。
92
+ * @returns 装到哪。
93
+ */
94
+ abstract install(result: PackResult): Promise<string>;
95
+ }
96
+ /** 默认实现:deploy 壳 → 叠宿主闭包 → electron-builder。 */
97
+ declare class PackagerDefault extends Packager {
98
+ private readonly logger;
99
+ /**
100
+ * @param config - electron-builder 配置。
101
+ * @param input - app 目录、宿主闭包与日志文件。
102
+ * @returns 产物位置。
103
+ */
104
+ pack(config: ElectronBuilderConfig, input: PackInput): Promise<PackResult>;
105
+ /**
106
+ * 备 app 目录:deploy 壳(依赖合法进 asar)→ 宿主闭包放 `profile/` → 改入口。
107
+ * @param input - app 目录与宿主闭包。
108
+ */
109
+ private assemble;
110
+ /**
111
+ * 跑一步并记日志(**同时写文件**:打包会跑几十秒到几分钟,控制台被截断时文件就是判据)。
112
+ * @param logFile - 日志文件。
113
+ * @param name - 步骤名。
114
+ * @param action - 这一步的动作。
115
+ * @returns 动作的返回值。
116
+ */
117
+ private step;
118
+ /**
119
+ * 一行日志:控制台 + 文件。
120
+ * @param logFile - 日志文件。
121
+ * @param line - 文本。
122
+ */
123
+ private note;
124
+ /**
125
+ * @param result - 打包结果。
126
+ * @returns 安装后的路径。
127
+ */
128
+ install(result: PackResult): Promise<string>;
129
+ }
130
+ export { ElectronBuilderConfig as a, PackagerDefault as i, PackResult as n, electronBuilderConfigOf as o, Packager as r, PackInput as t };
@@ -0,0 +1,18 @@
1
+ import { a as ElectronBuilderConfig, n as PackResult, r as Packager, t as PackInput } from "./packager-MGm6zQRf.mjs";
2
+ /** 记录调用、返回固定产物的打包器。 */
3
+ export declare class FakePackager extends Packager {
4
+ /** 每次打包收到的配置。 */
5
+ readonly packs: ElectronBuilderConfig[];
6
+ /** 每次安装收到的产物。 */
7
+ readonly installs: PackResult[];
8
+ /**
9
+ * @param _config - 配置。
10
+ * @returns 一个假的应用目录。
11
+ */
12
+ pack(_config: ElectronBuilderConfig, _input: PackInput): Promise<PackResult>;
13
+ /**
14
+ * @param result - 打包结果。
15
+ * @returns 装的路径。
16
+ */
17
+ install(result: PackResult): Promise<string>;
18
+ }