lumigather 1.0.1 → 1.0.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 EIGHTfs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -29,16 +29,27 @@
29
29
 
30
30
  ## 用法
31
31
 
32
- ### 启动
32
+ ### 启动(两种方式)
33
+
34
+ 从 npm 安装(前台运行,Ctrl-C 结束;数据落 `~/.lumigather`):
35
+
36
+ ```bash
37
+ npx lumigather --port 8081
38
+ ```
39
+
40
+ 从源码仓库运行(后台 + PID + 日志 + 状态,数据落项目目录):
33
41
 
34
42
  ```bash
35
43
  ./start.sh start # 后台启动
36
- ./start.sh status # 查看运行状态
44
+ ./start.sh status # 查看运行状态(含 /api/status 健康检查)
37
45
  ./start.sh restart # 重启
38
46
  ./start.sh stop # 停止
39
47
  node server/boot.cjs # 前台直接启动(调试用)
40
48
  ```
41
49
 
50
+ > `start.sh` 的 PID 与日志跟随数据根:设了 `LUMIGATHER_DATA_DIR` 就落那里;
51
+ > 在 npm 包目录里运行会自动落 `~/.lumigather`(不会写进 `node_modules`)。
52
+
42
53
  启动后访问 `http://<NAS-IP>:<端口>/`,端口见启动日志与设置页。
43
54
 
44
55
  ### 面板与设置页
@@ -49,7 +60,7 @@ node server/boot.cjs # 前台直接启动(调试用)
49
60
  | 侧边栏 | 目录树,按目录跳转 |
50
61
  | 搜索框 | 在当前分类内按文件名搜索 |
51
62
  | 排序按钮 | 名称 / 数量 / 时间 |
52
- | 设置 → 标题与图标 | 修改站点标题、favicon(Emoji 或图片 URL);**设置值优先**,没设时用品牌默认(`BRAND_*` 环境变量 → `.env` → `assemble.json` 的 `brand` 段 → 内置默认)。Emoji 只用于顶栏图标,不写进 `<link rel="icon">` |
63
+ | 设置 → 标题与图标 | 修改站点标题、favicon(Emoji 或图片 URL);**设置值优先**,没设时用品牌默认(`BRAND_*` 环境变量 → `.env` → 内置默认)。Emoji 只用于顶栏图标,不写进 `<link rel="icon">` |
53
64
  | 设置 → 分类 | 增删分类,设置颜色与显示名 |
54
65
  | 设置 → 目录 | 添加图片根目录,指定所属分类 |
55
66
  | 设置 → 密码 | 设置或修改访问密码(设置页需登录) |
package/bin/lumigather.js CHANGED
@@ -2,53 +2,204 @@
2
2
  // ============================================================
3
3
  // npx / 全局安装入口
4
4
  //
5
- // 判据必须走 realpath:npx 与全局安装都会把 bin 变成指向 node_modules 的符号链接。
6
- // 若用 __filename 的字面路径去推断项目根,链接场景下会指向 bin 的父目录而失败,
7
- // 且失败方式极隐蔽 —— 进程直接退出、用户只看到"跑完什么都没发生"。
8
- //
9
- // 本文件只做三件事:定位项目根、补数据目录与端口、载入服务端入口。
10
- // 不复制任何服务端逻辑,仓库态用 start.sh 启动的行为完全不受影响。
5
+ // 三件事:
6
+ // 1. 「是否被直接执行」判据必须走 realpath:
7
+ // npx 与全局安装都会把 bin 变成指向 node_modules 的符号链接,用字面路径比较会判成
8
+ // 「不是直接执行」→ 进程静默 exit 0,用户只看到「跑完什么都没发生」。
9
+ // 2. 子命令 start / stop / restart / status 直接转调仓库自带的 start.sh,
10
+ // 不重写一套 PID/端口/日志管理;无子命令时保持原行为:前台启动(Ctrl+C 停)。
11
+ // 3. 被 import 时不启动服务,只导出纯函数(parseArgs / buildEnv / isDirectInvocation),便于单测。
11
12
  // ============================================================
12
13
  "use strict";
13
14
 
14
15
  const fs = require("fs");
15
16
  const os = require("os");
16
17
  const path = require("path");
18
+ const { spawnSync } = require("child_process");
19
+
20
+ // 包安装态的数据根默认值:放到用户目录,升级不会连带覆盖缓存与上传
21
+ const DEFAULT_DATA_DIRNAME = ".lumigather";
22
+ // 转调 start.sh 的子命令(与 start.sh 的用法保持一致)
23
+ const SUBCOMMANDS = ["start", "stop", "restart", "status"];
24
+
25
+ /**
26
+ * 参数解析(纯函数,不读 process)。
27
+ * @param {string[]} argv 不含 node 与脚本路径的参数表
28
+ * @returns {{help:boolean, version:boolean, command:string|null, port:string|null, unknown:string[]}}
29
+ */
30
+ function parseArgs(argv) {
31
+ const out = { help: false, version: false, command: null, port: null, unknown: [] };
32
+ const list = Array.isArray(argv) ? argv : [];
33
+ for (let i = 0; i < list.length; i++) {
34
+ const a = String(list[i]);
35
+ if (a === "--help" || a === "-h") { out.help = true; continue; }
36
+ if (a === "--version" || a === "-v") { out.version = true; continue; }
37
+ if (a === "--port" && list[i + 1] !== undefined) { out.port = String(list[i + 1]); i++; continue; }
38
+ if (a.startsWith("--port=")) { out.port = a.slice("--port=".length); continue; }
39
+ if (!a.startsWith("-") && out.command === null && SUBCOMMANDS.includes(a)) { out.command = a; continue; }
40
+ out.unknown.push(a);
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /**
46
+ * 计算要注入子进程/当前进程的环境变量(纯函数,不写 process.env)。
47
+ * 数据根优先级与 server/lib/paths.js 一致:LUMIGATHER_DATA_DIR → GALLERY_DATA_DIR → DATA_DIR;
48
+ * 都没设置时才用 <home>/.lumigather(包安装态的默认落点)。
49
+ * @param {{args?:object, env?:object, home?:string}} opts
50
+ * @returns {{LUMIGATHER_DATA_DIR:string, PORT?:string}}
51
+ */
52
+ function buildEnv(opts) {
53
+ const o = opts || {};
54
+ const env = o.env || process.env;
55
+ const home = o.home || os.homedir();
56
+ const args = o.args || { port: null };
57
+ const explicit = env.LUMIGATHER_DATA_DIR || env.GALLERY_DATA_DIR || env.DATA_DIR || "";
58
+ const dataDir = String(explicit).trim()
59
+ ? String(explicit).trim()
60
+ : path.join(home, DEFAULT_DATA_DIRNAME);
61
+ const patch = { LUMIGATHER_DATA_DIR: dataDir };
62
+ if (args.port) patch.PORT = String(args.port);
63
+ return patch;
64
+ }
17
65
 
18
- // 解析符号链接后再定位项目根:npx 缓存目录、全局安装目录都是链接
19
- const SELF = fs.realpathSync(__filename);
20
- const PROJECT_ROOT = path.resolve(path.dirname(SELF), "..");
66
+ /** realpath 兜底:路径不存在时退回 resolve,避免判据因异常路径直接抛错 */
67
+ function realpathOr(p) {
68
+ try {
69
+ return fs.realpathSync(String(p));
70
+ } catch (_) {
71
+ return path.resolve(String(p));
72
+ }
73
+ }
21
74
 
22
- const argv = process.argv.slice(2);
75
+ /**
76
+ * 是否「被直接执行」:比较 realpath,不比较字面路径。
77
+ * @param {string|undefined} argv1 process.argv[1]
78
+ * @param {string} self 本文件路径(__filename)
79
+ * @returns {boolean}
80
+ */
81
+ function isDirectInvocation(argv1, self) {
82
+ if (!argv1) return false; // node -e / node 无脚本:一定不是直接执行本文件
83
+ return realpathOr(argv1) === realpathOr(self);
84
+ }
85
+
86
+ /** 由本文件位置定位项目根(解析符号链接后取上一级) */
87
+ function projectRootFrom(self) {
88
+ return path.resolve(path.dirname(realpathOr(self || __filename)), "..");
89
+ }
23
90
 
24
- if (argv.includes("--help") || argv.includes("-h")) {
25
- console.log([
26
- "用法: lumigather [--port <端口>]",
91
+ /** 读 package.json 的版本号;缺文件时返回 0.0.0,不因缺元数据让 --version 崩掉 */
92
+ function appVersion(root) {
93
+ try {
94
+ return String(require(path.join(root, "package.json")).version || "0.0.0");
95
+ } catch (_) {
96
+ return "0.0.0";
97
+ }
98
+ }
99
+
100
+ /** bash 定位:环境变量覆盖 → /bin/bash → PATH 里的 bash */
101
+ function bashBin() {
102
+ if (process.env.BASH) return process.env.BASH;
103
+ if (fs.existsSync("/bin/bash")) return "/bin/bash";
104
+ return "bash";
105
+ }
106
+
107
+ /** 帮助文本 */
108
+ function helpText(root, dataDir) {
109
+ return [
110
+ "用法: lumigather [子命令] [--port <端口>]",
111
+ "",
112
+ "子命令(转调仓库自带的 start.sh,后台运行):",
113
+ " start 启动 lumigather start [--port N]",
114
+ " stop 停止 lumigather stop",
115
+ " restart 重启 lumigather restart [--port N]",
116
+ " status 查看状态 lumigather status",
27
117
  "",
118
+ "不带子命令 = 前台直接启动(日志打在终端,Ctrl+C 停止)",
119
+ "",
120
+ "选项:",
28
121
  " --port <端口> 监听端口(也可用环境变量 PORT,缺省由服务端决定)",
122
+ " --version 显示版本号",
29
123
  " --help 显示本帮助",
30
124
  "",
31
- "数据目录: " + (process.env.GALLERY_DATA_DIR || process.env.DATA_DIR || path.join(os.homedir(), ".lumigather")),
32
- " 可用环境变量 GALLERY_DATA_DIR 覆盖",
33
- ].join("\n"));
34
- process.exit(0);
125
+ "项目根: " + root,
126
+ "数据目录: " + dataDir,
127
+ " 可用环境变量 LUMIGATHER_DATA_DIR 覆盖(旧名 GALLERY_DATA_DIR 仍兼容)",
128
+ ].join("\n");
35
129
  }
36
130
 
37
- // 数据根:包方式安装时默认落到用户目录,避免升级时连带覆盖缓存与用户上传内容。
38
- // 显式设置了环境变量则尊重设置(与 server/lib/paths.js 的优先级保持一致)。
39
- if (!process.env.GALLERY_DATA_DIR && !process.env.DATA_DIR) {
40
- process.env.GALLERY_DATA_DIR = path.join(os.homedir(), ".lumigather");
131
+ /**
132
+ * 转调 start.sh:先注入数据根,保证后台进程与前台 CLI 用同一个数据根
133
+ * (否则包安装态会退回到 <包目录>/cache-*,升级即丢)。
134
+ * @returns {number} 子进程退出码
135
+ */
136
+ function runStartSh(root, command, port, patch) {
137
+ const script = path.join(root, "start.sh");
138
+ if (!fs.existsSync(script)) {
139
+ console.error("找不到 " + script + ":安装包不完整(start.sh 应随包分发)");
140
+ return 2;
141
+ }
142
+ const args = [script, command];
143
+ if (port) args.push("--port", String(port));
144
+ const r = spawnSync(bashBin(), args, {
145
+ stdio: "inherit",
146
+ env: Object.assign({}, process.env, patch),
147
+ });
148
+ if (r.error) {
149
+ console.error("调用 start.sh 失败:" + r.error.message);
150
+ return 2;
151
+ }
152
+ return typeof r.status === "number" ? r.status : 1;
41
153
  }
42
154
 
43
- // 端口:--port N / --port=N 优先;未给则保留已有 PORT 环境变量,交给服务端取缺省
44
- for (let i = 0; i < argv.length; i++) {
45
- const a = argv[i];
46
- if (a === "--port" && argv[i + 1]) { process.env.PORT = argv[i + 1]; break; }
47
- if (a.startsWith("--port=")) { process.env.PORT = a.slice("--port=".length); break; }
155
+ /**
156
+ * 主流程:帮助 / 版本 / 子命令 / 前台启动。
157
+ * @returns {number|null} 需要立即退出时返回退出码;前台启动(服务接管进程)返回 null
158
+ */
159
+ function main(argv, ctx) {
160
+ const o = ctx || {};
161
+ const root = o.root || projectRootFrom(__filename);
162
+ const args = parseArgs(argv);
163
+ const patch = buildEnv({ args, env: o.env, home: o.home });
164
+
165
+ if (args.help) {
166
+ console.log(helpText(root, patch.LUMIGATHER_DATA_DIR));
167
+ return 0;
168
+ }
169
+ if (args.version) {
170
+ console.log(appVersion(root));
171
+ return 0;
172
+ }
173
+ if (args.unknown.length) {
174
+ console.error("未知参数:" + args.unknown.join(" ") + "(用 --help 看用法)");
175
+ return 2;
176
+ }
177
+ if (args.command) {
178
+ return runStartSh(root, args.command, args.port, patch);
179
+ }
180
+
181
+ // 无子命令:前台启动。先落环境变量,服务端与 start.sh 看到同一个数据根。
182
+ Object.assign(process.env, patch);
183
+ fs.mkdirSync(process.env.LUMIGATHER_DATA_DIR, { recursive: true });
184
+ require(path.join(root, "server", "boot.cjs"));
185
+ return null;
48
186
  }
49
187
 
50
- // 数据目录必须存在:缓存与上传都写在它下面
51
- fs.mkdirSync(process.env.GALLERY_DATA_DIR, { recursive: true });
188
+ module.exports = {
189
+ DEFAULT_DATA_DIRNAME,
190
+ SUBCOMMANDS,
191
+ parseArgs,
192
+ buildEnv,
193
+ isDirectInvocation,
194
+ projectRootFrom,
195
+ appVersion,
196
+ helpText,
197
+ runStartSh,
198
+ main,
199
+ };
52
200
 
53
- // 交给服务端入口,由它负责监听、日志与优雅退出
54
- require(path.join(PROJECT_ROOT, "server", "boot.cjs"));
201
+ // 只有「直接执行」才启动;被 import(require/import)时只导出上面的纯函数。
202
+ if (isDirectInvocation(process.argv[1], __filename)) {
203
+ const code = main(process.argv.slice(2));
204
+ if (code !== null && code !== undefined) process.exit(code);
205
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lumigather",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "局域网 Mod 图片画廊:目录浏览、压缩包直出、序列帧合成 GIF",
5
5
  "bin": {
6
6
  "lumigather": "bin/lumigather.js"
@@ -8,14 +8,17 @@
8
8
  "files": [
9
9
  "bin/",
10
10
  "server/",
11
- "README.md"
11
+ "README.md",
12
+ "LICENSE",
13
+ "start.sh"
12
14
  ],
13
15
  "engines": {
14
16
  "node": ">=18"
15
17
  },
16
18
  "scripts": {
17
19
  "start": "node bin/lumigather.js",
18
- "prepublishOnly": "bash scripts/prepublish-guard.sh"
20
+ "prepublishOnly": "node scripts/prepublish-guard.js",
21
+ "verify:pack": "bash scripts/verify-pack.sh"
19
22
  },
20
23
  "keywords": [
21
24
  "gallery",
@@ -30,5 +33,9 @@
30
33
  "bugs": {
31
34
  "url": "https://github.com/EIGHTfs/Lumigather/issues"
32
35
  },
33
- "homepage": "https://github.com/EIGHTfs/Lumigather#readme"
36
+ "homepage": "https://github.com/EIGHTfs/Lumigather#readme",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/EIGHTfs/Lumigather.git"
40
+ }
34
41
  }
@@ -264,6 +264,19 @@ function createServer(opts) {
264
264
  if (onReady) onReady(port);
265
265
  });
266
266
 
267
+ // 启动失败的「人话」:不把原始 EADDRINUSE 堆栈丢给用户。
268
+ // 为什么:端口占用是首次运行最常见的失败(8080/8081/8642 都常被占),
269
+ // 堆栈只说「address already in use」,不说下一步该做什么。
270
+ // 退出码 2 专指「启动期失败」,与业务异常的 1 区分,脚本/监控可据此判定。
271
+ server.on("error", (e) => {
272
+ if (e && e.code === "EADDRINUSE") {
273
+ console.error("端口 " + port + " 已被占用:用 --port <其他端口> 换一个,或先停掉占用该端口的进程");
274
+ process.exit(2);
275
+ }
276
+ console.error("服务启动失败:" + (e && e.message ? e.message : String(e)));
277
+ process.exit(2);
278
+ });
279
+
267
280
  return server;
268
281
  }
269
282
 
@@ -8,6 +8,18 @@
8
8
  // ============================================================
9
9
  "use strict";
10
10
 
11
+ // 进程启动时刻:本模块在装配阶段被 require(监听之前),取到的即进程启动时间
12
+ const STARTED_AT = Date.now();
13
+
14
+ /** 项目版本号:package.json 缺失(极简部署)时返回空串,不让状态查询因缺文件而 500 */
15
+ function appVersion() {
16
+ try {
17
+ return String(require("../../package.json").version || "");
18
+ } catch (_) {
19
+ return "";
20
+ }
21
+ }
22
+
11
23
  module.exports = function register(api) {
12
24
  const { route, routePublic, sendJson, readBody, cfg, auth, setSessionCookie } = api;
13
25
 
@@ -49,8 +61,11 @@ module.exports = function register(api) {
49
61
  return sendJson(res, { ok: true }, 200);
50
62
  });
51
63
 
52
- // GET /api/status —— 前端据此决定跳登录页还是进主界面
64
+ // GET /api/status —— 前端据此决定跳登录页还是进主界面;启停脚本/监控也用它判活
53
65
  // 字段契约:ok / needsSetup(未设密码)/ needsAuth(密码已设置)/ authed(当前会话已登录)/ port
66
+ // + uptimeSec(进程已运行秒数)/ version(项目 package.json 的版本号,读不到时为空串)
67
+ // 为什么放在 /api/status 而不另开健康端点:启停脚本与监控已经在看这个端点,
68
+ // 追加字段零成本;另开端点只会多一个要被各下游实现的契约。
54
69
  // authed 必须由服务端按 session 判定——needsAuth 只是「密码已设置」,
55
70
  // 前端拿 needsAuth 当登录态会在设密码后恒判未登录(gallery 收藏「请先登录」事故根因)。
56
71
  routePublic("*", "/api/status", (req, res) => {
@@ -60,7 +75,9 @@ module.exports = function register(api) {
60
75
  needsSetup: !c.passwordHash,
61
76
  needsAuth: !!c.passwordHash,
62
77
  authed: auth.isValidSession(auth.extractToken(req)),
63
- port: c.port || 8643
78
+ port: c.port || 8643,
79
+ uptimeSec: Math.max(0, Math.floor((Date.now() - STARTED_AT) / 1000)),
80
+ version: appVersion()
64
81
  }, 200);
65
82
  });
66
83
 
package/server/server.log CHANGED
@@ -98,3 +98,11 @@
98
98
  [2026-11-01 18:55:30] 运行环境: Node v22.22.3
99
99
  [2026-11-01 18:55:30] [lumigather/auto-update] autoUpdate 未启用
100
100
  [2026-11-01 18:55:30] 🎮 Gallery running at http://localhost:8081 (局域网: http://<本机IP>:8081)
101
+ [2026-11-01 19:18:18] 服务启动: http://localhost:8081 (局域网: http://<本机IP>:8081)
102
+ [2026-11-01 19:18:18] 运行环境: Node v22.22.3
103
+ [2026-11-01 19:18:18] [lumigather/auto-update] autoUpdate 未启用
104
+ [2026-11-01 19:18:18] 🎮 Gallery running at http://localhost:8081 (局域网: http://<本机IP>:8081)
105
+ [2026-11-01 19:19:53] 服务启动: http://localhost:8081 (局域网: http://<本机IP>:8081)
106
+ [2026-11-01 19:19:53] 运行环境: Node v22.22.3
107
+ [2026-11-01 19:19:53] [lumigather/auto-update] autoUpdate 未启用
108
+ [2026-11-01 19:19:53] 🎮 Gallery running at http://localhost:8081 (局域网: http://<本机IP>:8081)
package/start.sh ADDED
@@ -0,0 +1,529 @@
1
+ #!/usr/bin/env bash
2
+ # ============================================================
3
+ # POSIX 启停脚本(Linux / 群晖 / macOS 共用)
4
+ # 用法:
5
+ # ./start.sh start [--port PORT]
6
+ # ./start.sh restart [--port PORT] # 默认命令
7
+ # ./start.sh stop
8
+ # ./start.sh status
9
+ # ./start.sh --port PORT # 兼容旧用法(等价 restart)
10
+ # ./start.sh --set-password "新密码"
11
+ # PID:项目根 / 项目全称.pid(见 pid-file-at-project-root)
12
+ # ============================================================
13
+ set -uo pipefail
14
+
15
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
16
+ PROJECT_NAME="$(basename "$ROOT")"
17
+ SERVER_DIR="$ROOT/server"
18
+
19
+ # ---------- 数据根:写路径一律不许落在包目录里 ----------
20
+ # 为什么不能直接 `PID_FILE="$ROOT/xxx.pid"`:
21
+ # 装成 npm 包后 ROOT = <...>/node_modules/lumigather,PID/日志/配置全落进包目录
22
+ # ⇒ 升级即丢(npm 会整体替换该目录),且包目录可能只读。
23
+ # 与服务端同一口径(server/lib/config.js 读的是 <dataRoot>/server/config.json):
24
+ # ① LUMIGATHER_DATA_DIR / GALLERY_DATA_DIR / DATA_DIR 显式指定 → 用它
25
+ # ② 没指定且脚本在 node_modules 里(= 以包方式安装)→ 落 ~/.lumigather
26
+ # ③ 否则(从 git 仓库直接跑)→ 落项目根,保持原有行为一字不变
27
+ if [ -n "${LUMIGATHER_DATA_DIR:-}" ]; then
28
+ DATA_ROOT="$LUMIGATHER_DATA_DIR"
29
+ elif [ -n "${GALLERY_DATA_DIR:-}" ]; then
30
+ DATA_ROOT="$GALLERY_DATA_DIR"
31
+ elif [ -n "${DATA_DIR:-}" ]; then
32
+ DATA_ROOT="$DATA_DIR"
33
+ elif [[ "$ROOT" == */node_modules/* ]]; then
34
+ DATA_ROOT="$HOME/.lumigather"
35
+ echo "提示:检测到以 npm 包方式运行,数据根自动落到 $DATA_ROOT(可用 LUMIGATHER_DATA_DIR 覆盖)" >&2
36
+ else
37
+ DATA_ROOT="$ROOT"
38
+ fi
39
+ PID_FILE="$DATA_ROOT/${PROJECT_NAME}.pid"
40
+ LOG_FILE="$DATA_ROOT/logs/server.log"
41
+ # 与服务端同源:config.json 在 <数据根>/server/ 下(见 server/lib/config.js)
42
+ CONFIG_FILE="$DATA_ROOT/server/config.json"
43
+ # 默认端口:优先读 server/config.schema.json 的 port.default —— 各项目端口不同
44
+ # (gallery 8081、gbmd/iwara 8642),通用脚本不该写死某一个项目的端口。
45
+ # 读不到(未声明/无 schema)才回落到 8642。
46
+ SCHEMA_PORT=""
47
+ if [ -f "$ROOT/server/config.schema.json" ]; then
48
+ SCHEMA_PORT="$(sed -n 's/.*"port"[^}]*"default"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$ROOT/server/config.schema.json" 2>/dev/null | head -n 1)"
49
+ fi
50
+ DEFAULT_PORT="${DEFAULT_PORT:-${SCHEMA_PORT:-8642}}"
51
+ LOG_ROTATE_BYTES=$((10 * 1024 * 1024))
52
+ STOP_WAIT_SEC=10
53
+ START_WAIT_SEC="${START_WAIT_SEC:-15}" # 启动前等端口释放的上限(秒)
54
+
55
+ # ---------- 颜色(stdout 是终端才开;NO_COLOR / TERM=dumb 关闭)----------
56
+ C_GREEN="" C_YELLOW="" C_RED="" C_DIM="" C_RESET=""
57
+ if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-}" != "dumb" ]; then
58
+ C_GREEN=$'\033[32m'
59
+ C_YELLOW=$'\033[33m'
60
+ C_RED=$'\033[31m'
61
+ C_DIM=$'\033[2m'
62
+ C_RESET=$'\033[0m'
63
+ fi
64
+ ok() { printf '%s%s%s\n' "$C_GREEN" "$*" "$C_RESET"; }
65
+ warn() { printf '%s%s%s\n' "$C_YELLOW" "$*" "$C_RESET"; }
66
+ err() { printf '%s%s%s\n' "$C_RED" "$*" "$C_RESET"; }
67
+ dim() { printf '%s%s%s\n' "$C_DIM" "$*" "$C_RESET"; }
68
+
69
+ # 历史 PID 位置(迁移兼容):老版本把这些 PID 落在 server/ 或 /tmp。
70
+ # 只按「本项目名」枚举,不硬编码具体项目——否则换项目名后这里就成了死代码
71
+ # (曾写死 gbmd.pid / gbmd-macos.pid,别的项目复用时既清不掉旧 PID 也读不到)。
72
+ legacy_pid_files() {
73
+ printf '%s\n' \
74
+ "$SERVER_DIR/app.pid" \
75
+ "$SERVER_DIR/${PROJECT_NAME}.pid" \
76
+ "/tmp/${PROJECT_NAME}.pid" \
77
+ "/tmp/${PROJECT_NAME}-macos.pid" \
78
+ "/tmp/start-${PROJECT_NAME}.pid"
79
+ }
80
+
81
+ # 项目自带工具目录:命名为 tool/ 与 tools/ 的都有(gallery 用 tools/),两个都认。
82
+ TOOL_DIR=""
83
+ for d in "$ROOT/tools" "$ROOT/tool"; do
84
+ if [ -d "$d" ]; then TOOL_DIR="$d"; break; fi
85
+ done
86
+ export PATH="${TOOL_DIR:+$TOOL_DIR/node/bin:}/usr/local/bin:/opt/homebrew/bin:/opt/node/bin:/var/packages/Node.js_v24/target/usr/local/bin:/var/packages/Node.js_v22/target/usr/local/bin:/var/packages/Node.js_v20/target/usr/local/bin:$PATH"
87
+ if [ -n "$TOOL_DIR" ]; then export FFMPEG="${FFMPEG:-$TOOL_DIR/ffmpeg}"; fi
88
+
89
+ # ---------- Node 定位 ----------
90
+ # start.sh 是「独立可搬运」脚本:它会被直接拷进项目根,而项目里没有 scripts/。
91
+ # 因此这里内联定位逻辑,不 source 外部文件——否则换了环境就找不到 node
92
+ # (表现为脚本刚启动就报 lib-node.sh 不存在)。
93
+ # 候选顺序与 scripts/lib-node.sh 保持一致,改一处要同步改另一处。
94
+ find_node() {
95
+ local c nvm
96
+ for c in \
97
+ "$ROOT/tool/node/bin/node" \
98
+ /usr/local/bin/node \
99
+ /opt/homebrew/bin/node \
100
+ /opt/node/bin/node \
101
+ /var/packages/Node.js_v24/target/usr/local/bin/node \
102
+ /var/packages/Node.js_v22/target/usr/local/bin/node \
103
+ /var/packages/Node.js_v20/target/usr/local/bin/node \
104
+ /var/packages/DeepSeekHarness-NAS/target/bin/node \
105
+ node; do
106
+ if [ -x "$c" ]; then NODE_BIN="$c"; return 0; fi
107
+ if command -v "$c" >/dev/null 2>&1; then NODE_BIN="$(command -v "$c")"; return 0; fi
108
+ done
109
+ for nvm in "$HOME"/.nvm/versions/node/*/bin/node; do
110
+ if [ -x "$nvm" ]; then NODE_BIN="$nvm"; return 0; fi
111
+ done
112
+ return 1
113
+ }
114
+
115
+ if ! find_node; then
116
+ err "❌ 找不到 node。请安装 Node.js,或把官方二进制解压到 tool/node/"
117
+ exit 1
118
+ fi
119
+ ok "✓ Node: $NODE_BIN ($("$NODE_BIN" -v 2>/dev/null))"
120
+
121
+ file_size() {
122
+ local f="$1"
123
+ [ -f "$f" ] || { echo 0; return; }
124
+ stat -c%s "$f" 2>/dev/null || stat -f%z "$f" 2>/dev/null || wc -c < "$f"
125
+ }
126
+
127
+ human_size() {
128
+ local n="$1"
129
+ if [ "$n" -ge 1048576 ]; then awk -v n="$n" 'BEGIN{printf "%.1fMB", n/1048576}'; else awk -v n="$n" 'BEGIN{printf "%.1fKB", n/1024}'; fi
130
+ }
131
+
132
+ # ---------- 配置验证(不打印 Cookie / Token / 密码哈希)----------
133
+ validate_config() {
134
+ if [ ! -f "$CONFIG_FILE" ]; then
135
+ warn "⚠️ 无 $CONFIG_FILE ,启动后会按默认值生成"
136
+ return 0
137
+ fi
138
+ local out rc=0
139
+ out="$("$NODE_BIN" -e '
140
+ const fs = require("fs");
141
+ const p = process.argv[1];
142
+ const def = Number(process.argv[2]);
143
+ let raw;
144
+ try { raw = fs.readFileSync(p, "utf8"); }
145
+ catch (e) {
146
+ const code = e && e.code ? e.code : "";
147
+ console.log((code === "EACCES" || code === "EPERM" ? "NO_PERM " : "READ_FAIL ") + (e.message || code));
148
+ process.exit(2);
149
+ }
150
+ let c;
151
+ try { c = JSON.parse(raw); }
152
+ catch (e) { console.log("JSON_FAIL " + e.message); process.exit(3); }
153
+ if (!c || typeof c !== "object" || Array.isArray(c)) {
154
+ console.log("NOT_OBJECT");
155
+ process.exit(4);
156
+ }
157
+ if (c.port != null && c.port !== "") {
158
+ const n = Number(c.port);
159
+ if (!Number.isInteger(n) || n < 1 || n > 65535) {
160
+ console.log("BAD_PORT " + String(c.port));
161
+ process.exit(5);
162
+ }
163
+ }
164
+ const port = (c.port == null || c.port === "") ? def : Number(c.port);
165
+ console.log("OK " + port);
166
+ ' "$CONFIG_FILE" "$DEFAULT_PORT" 2>&1)" || rc=$?
167
+ case "$out" in
168
+ OK\ *) ok "✓ config.json 格式正常 port=${out#OK }"; return 0 ;;
169
+ NO_PERM\ *) warn "⚠️ 无权限读 config.json,跳过格式校验"; return 0 ;;
170
+ esac
171
+ err "❌ config.json 校验失败:$out"
172
+ return 1
173
+ }
174
+
175
+ config_port() {
176
+ "$NODE_BIN" -e '
177
+ try {
178
+ const c = require(process.argv[1]);
179
+ const d = Number(process.argv[2]);
180
+ const n = Number(c.port);
181
+ console.log(Number.isInteger(n) && n >= 1 && n <= 65535 ? n : d);
182
+ } catch (e) { console.log(process.argv[2]); }
183
+ ' "$CONFIG_FILE" "$DEFAULT_PORT" 2>/dev/null || echo "$DEFAULT_PORT"
184
+ }
185
+
186
+ rotate_log() {
187
+ [ -f "$LOG_FILE" ] || return 0
188
+ local sz
189
+ sz="$(file_size "$LOG_FILE")"
190
+ [ "$sz" -gt "$LOG_ROTATE_BYTES" ] || return 0
191
+ local ts dest
192
+ ts="$(date +%Y%m%d-%H%M%S)"
193
+ dest="${LOG_FILE}.${ts}"
194
+ mv "$LOG_FILE" "$dest" || return 0
195
+ if command -v gzip >/dev/null 2>&1; then
196
+ gzip -f "$dest" && dest="${dest}.gz"
197
+ fi
198
+ warn "⚠️ 日志超过 10MB,已轮转: $dest ($(human_size "$sz"))"
199
+ }
200
+
201
+ pid_alive() {
202
+ local p="$1"
203
+ [ -n "$p" ] && kill -0 "$p" 2>/dev/null
204
+ }
205
+
206
+ read_pid_file() {
207
+ local f="$1"
208
+ [ -f "$f" ] && [ -s "$f" ] || return 1
209
+ tr -d ' \t\r\n' < "$f"
210
+ }
211
+
212
+ collect_live_pids() {
213
+ local f p seen=" "
214
+ for f in "$PID_FILE" $(legacy_pid_files); do
215
+ p="$(read_pid_file "$f" 2>/dev/null || true)"
216
+ if pid_alive "$p"; then
217
+ case "$seen" in
218
+ *" $p "*) ;;
219
+ *) seen="$seen$p "; printf '%s\n' "$p" ;;
220
+ esac
221
+ fi
222
+ done
223
+ # 端口兜底:被外部(宿主/手动 nohup)拉起时不会写 PID 文件,只靠 PID 文件
224
+ # 会误判「未运行」而漏杀,随后 start 阶段又因端口占用起不来。
225
+ # 这里按监听端口反查 PID(仅认本项目 node 进程,避免误杀同端口其他程序)。
226
+ local port
227
+ port="$(config_port 2>/dev/null || true)"
228
+ [ -n "$port" ] || return 0
229
+ local lp
230
+ lp="$(port_pids "$port")"
231
+ for p in $lp; do
232
+ case "$seen" in
233
+ *" $p "*) ;;
234
+ *) seen="$seen$p "; printf '%s\n' "$p" ;;
235
+ esac
236
+ done
237
+ }
238
+
239
+ # 本机是否已有进程监听该端口(精确匹配端口号,不看 PID)
240
+ # 注意:必须用「末尾锚定」的端口匹配。旧写法 `$4 ~ ":8642"` 是子串匹配,
241
+ # 会连 ":18642" / ":86421" 一起命中——同机跑多实例时互相误判、误杀。
242
+ port_in_use() {
243
+ local port="$1" out=""
244
+ if command -v ss >/dev/null 2>&1; then
245
+ out="$(ss -tln 2>/dev/null)"
246
+ elif command -v netstat >/dev/null 2>&1; then
247
+ out="$(netstat -tln 2>/dev/null)"
248
+ fi
249
+ [ -n "$out" ] || return 1
250
+ # 第 4 列形如 0.0.0.0:8642 / [::]:8642 / :::8642 / 127.0.0.1:8642
251
+ printf '%s\n' "$out" | awk -v p="$port" '
252
+ $4 ~ ("[.:]" p "$") { found = 1; exit }
253
+ END { exit(found ? 0 : 1) }'
254
+ }
255
+
256
+ # 监听指定端口的进程 PID(取本项目 node 进程;优先 ss,退回 netstat)
257
+ port_pids() {
258
+ local port="$1" out=""
259
+ if command -v ss >/dev/null 2>&1; then
260
+ out="$(ss -tlnp 2>/dev/null | awk -v p="$port" '$4 ~ ("[.:]" p "$") {print}')"
261
+ elif command -v netstat >/dev/null 2>&1; then
262
+ out="$(netstat -tlnp 2>/dev/null | awk -v p="$port" '$4 ~ ("[.:]" p "$") {print}')"
263
+ fi
264
+ [ -n "$out" ] || return 0
265
+ # ss 格式:users:(("node",pid=1234,fd=20)) → 取 pid=NNN
266
+ # netstat 格式:最后一列是 "1234/node" → 取斜杠前的数字
267
+ printf '%s\n' "$out" | grep -o 'pid=[0-9]*' | cut -d= -f2
268
+ printf '%s\n' "$out" | awk '{n=split($NF,a,"/"); if (n>1 && a[1] ~ /^[0-9]+$/) print a[1]}'
269
+ }
270
+
271
+ # 等端口真正释放(旧进程退出 ≠ 端口立刻可用:TIME_WAIT、子进程继承 fd)
272
+ # 返回 0 = 已释放,1 = 超时仍被占用
273
+ wait_port_free() {
274
+ local port="$1" timeout="${2:-10}" i=0
275
+ while [ "$i" -lt "$((timeout * 2))" ]; do
276
+ port_in_use "$port" || return 0
277
+ sleep 0.5
278
+ i=$((i + 1))
279
+ done
280
+ return 1
281
+ }
282
+
283
+ listen_line() {
284
+ local port="$1"
285
+ if command -v ss >/dev/null 2>&1; then
286
+ ss -tln 2>/dev/null | awk -v p=":$port" '$0 ~ p {print; exit}'
287
+ elif command -v netstat >/dev/null 2>&1; then
288
+ netstat -tln 2>/dev/null | awk -v p=":$port" '$0 ~ p {print; exit}'
289
+ fi
290
+ }
291
+
292
+ start_server() {
293
+ local port_opt=""
294
+ while [ $# -gt 0 ]; do
295
+ case "$1" in
296
+ --port) port_opt="${2:-}"; shift 2 ;;
297
+ *) shift ;;
298
+ esac
299
+ done
300
+ validate_config || return 1
301
+ local port="${port_opt:-$(config_port)}"
302
+ local live
303
+ live="$(collect_live_pids | head -n 1 || true)"
304
+ if [ -n "$live" ]; then
305
+ warn "⚠️ 已在运行 (PID $live, 端口 $port)。如需重启: ./start.sh restart"
306
+ return 1
307
+ fi
308
+ # 端口仍被占但找不到归属进程:典型是上一次重启刚发的 SIGTERM 还没走完,
309
+ # 连接处于 TIME_WAIT、或子进程临时继承了监听 fd(非 root 看不到其 PID)。
310
+ # 旧逻辑此处直接启动,bind 失败后进程秒退,表现为「重启后服务没起来」。
311
+ # 这里先等端口真正空出来,等到就继续启动,等不到才报错退出。
312
+ if port_in_use "$port"; then
313
+ warn "⏳ 端口 $port 仍被占用,等待释放(最多 ${START_WAIT_SEC}s)..."
314
+ if ! wait_port_free "$port" "$START_WAIT_SEC"; then
315
+ err "❌ 端口 $port 等待 ${START_WAIT_SEC}s 仍未释放,放弃启动。"
316
+ err " 排查:netstat -tlnp | grep :$port 或换端口: ./start.sh --port <新端口>"
317
+ return 1
318
+ fi
319
+ ok "✓ 端口 $port 已释放"
320
+ fi
321
+ rm -f "$PID_FILE"
322
+ # 代码目录 + 数据目录都要在:日志写 <数据根>/logs、配置写 <数据根>/server
323
+ mkdir -p "$SERVER_DIR" "$DATA_ROOT/logs" "$DATA_ROOT/server"
324
+ rotate_log
325
+ cd "$SERVER_DIR" || exit 1
326
+ # 让服务端与脚本用同一个数据根(否则脚本把 PID/日志写到 A、服务端把缓存写到 B)
327
+ export LUMIGATHER_DATA_DIR="$DATA_ROOT"
328
+ local cmd=("$NODE_BIN" boot.cjs)
329
+ if [ -n "$port_opt" ]; then
330
+ export PORT="$port_opt"
331
+ cmd+=("--port" "$port_opt")
332
+ fi
333
+ if command -v setsid >/dev/null 2>&1; then
334
+ setsid nohup "${cmd[@]}" >> "$LOG_FILE" 2>&1 < /dev/null &
335
+ else
336
+ nohup "${cmd[@]}" >> "$LOG_FILE" 2>&1 < /dev/null &
337
+ fi
338
+ echo $! > "$PID_FILE"
339
+ local new_pid
340
+ new_pid="$(cat "$PID_FILE")"
341
+
342
+ local okflag=0 i
343
+ for i in $(seq 1 8); do
344
+ sleep 1
345
+ if curl -sf -m 3 "http://127.0.0.1:$port/api/status" > /dev/null 2>&1; then
346
+ okflag=1
347
+ break
348
+ fi
349
+ pid_alive "$new_pid" || break
350
+ done
351
+ if [ "$okflag" = 1 ]; then
352
+ ok "✅ 启动成功 PID=$new_pid 端口=$port"
353
+ echo " 页面: http://<本机IP>:$port"
354
+ echo " 日志: $LOG_FILE"
355
+ echo " PID: $PID_FILE"
356
+ else
357
+ err "❌ 启动失败(8 秒内未通过健康检查),最近日志:"
358
+ tail -15 "$LOG_FILE" 2>/dev/null
359
+ return 1
360
+ fi
361
+ }
362
+
363
+ stop_one() {
364
+ local pid="$1"
365
+ warn "⏹ SIGTERM PID=$pid (最多等 ${STOP_WAIT_SEC}s)"
366
+ kill "$pid" 2>/dev/null || true
367
+ local i
368
+ for i in $(seq 1 "$STOP_WAIT_SEC"); do
369
+ if ! pid_alive "$pid"; then
370
+ ok "✓ PID $pid 已在 ${i}s 内退出"
371
+ return 0
372
+ fi
373
+ sleep 1
374
+ done
375
+ if pid_alive "$pid"; then
376
+ warn "⚠️ ${STOP_WAIT_SEC}s 未退出,SIGKILL PID=$pid"
377
+ kill -9 "$pid" 2>/dev/null || true
378
+ sleep 1
379
+ fi
380
+ if pid_alive "$pid"; then
381
+ err "❌ PID $pid 仍在,请检查"
382
+ return 1
383
+ fi
384
+ ok "✓ PID $pid 已强制结束"
385
+ }
386
+
387
+ stop_server() {
388
+ local pids
389
+ pids="$(collect_live_pids || true)"
390
+ if [ -z "$pids" ]; then
391
+ warn "⚠️ 未运行(无有效 PID)"
392
+ rm -f "$PID_FILE"
393
+ local f
394
+ for f in $(legacy_pid_files); do rm -f "$f"; done
395
+ return 0
396
+ fi
397
+ local rc=0
398
+ for p in $pids; do
399
+ stop_one "$p" || rc=1
400
+ done
401
+ rm -f "$PID_FILE"
402
+ local f
403
+ for f in $(legacy_pid_files); do rm -f "$f"; done
404
+ if [ "$rc" = 0 ]; then
405
+ ok "✅ 已停止"
406
+ else
407
+ err "❌ 停止未完成"
408
+ fi
409
+ return "$rc"
410
+ }
411
+
412
+ status_server() {
413
+ # 与 start_server 用同一套参数解析:不认 --port 时,用非默认端口起的实例会被判成「未运行」
414
+ # (下面查监听与 /api/status 都用 port,而 port 默认取自配置里的端口)。
415
+ local port_opt=""
416
+ while [ $# -gt 0 ]; do
417
+ case "$1" in
418
+ --port) port_opt="${2:-}"; shift 2 ;;
419
+ *) shift ;;
420
+ esac
421
+ done
422
+ local port
423
+ port="${port_opt:-$(config_port)}"
424
+ echo "======== $PROJECT_NAME ========"
425
+ echo "根目录: $ROOT"
426
+ echo "PID文件: $PID_FILE$([ -f "$PID_FILE" ] && echo " (存在)" || echo " (无)")"
427
+ echo "配置: $CONFIG_FILE"
428
+ validate_config || true
429
+
430
+ local p
431
+ p="$(read_pid_file "$PID_FILE" 2>/dev/null || true)"
432
+ if pid_alive "$p"; then
433
+ ok "进程: ✓ PID $p"
434
+ ps -o pid=,ppid=,etime=,rss=,stat=,args= -p "$p" 2>/dev/null | while IFS= read -r line; do
435
+ dim " $line"
436
+ done
437
+ elif [ -n "$p" ]; then
438
+ err "进程: ✗ PID 文件有 $p 但进程已退出"
439
+ else
440
+ err "进程: ✗ 未运行"
441
+ fi
442
+
443
+ local extra extra_other=""
444
+ extra="$(ps -eo pid,args 2>/dev/null | awk -v root="$ROOT" '
445
+ $0 ~ /boot\.cjs/ && $0 ~ /node/ && index($0, root) { print $1 }
446
+ ' || true)"
447
+ for p2 in $extra; do
448
+ if [ "$p2" != "${p:-}" ]; then extra_other="$extra_other $p2"; fi
449
+ done
450
+ extra_other="$(echo "$extra_other" | xargs)"
451
+ if [ -n "$extra_other" ]; then
452
+ warn "进程: ⚠️ 未记入 PID 文件: $extra_other"
453
+ fi
454
+
455
+ local lis
456
+ lis="$(listen_line "$port")"
457
+ if [ -n "$lis" ]; then
458
+ ok "监听: ✓ 端口 $port"
459
+ dim " $lis"
460
+ else
461
+ warn "监听: 未发现 :$port"
462
+ fi
463
+
464
+ local curlout code time body
465
+ # 2026-10-11:临时文件改由 mktemp 派生(原来写死 /tmp/...,换环境/多实例会撞车;路径卫生门禁会拦)
466
+ body="$(mktemp 2>/dev/null || echo "./.status-body.$")"
467
+ curlout="$(curl -sS -m 5 -o "$body" -w '%{http_code} %{time_total}' "http://127.0.0.1:$port/api/status" 2>/dev/null || echo "000 0")"
468
+ code="${curlout%% *}"
469
+ time="${curlout#* }"
470
+ if [ "$code" = "200" ]; then
471
+ ok "HTTP: ✓ GET /api/status $code ${time}s"
472
+ head -c 240 "$body" 2>/dev/null; echo
473
+ else
474
+ err "HTTP: ✗ GET /api/status HTTP $code"
475
+ fi
476
+ rm -f "$body"
477
+
478
+ if [ -f "$LOG_FILE" ]; then
479
+ local sz mtime
480
+ sz="$(file_size "$LOG_FILE")"
481
+ mtime="$(date -r "$LOG_FILE" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || stat -c %y "$LOG_FILE" 2>/dev/null | cut -d. -f1)"
482
+ echo "日志: $LOG_FILE $(human_size "$sz") 更新 $mtime"
483
+ if [ "$sz" -gt "$LOG_ROTATE_BYTES" ]; then
484
+ warn "日志: 已超过 10MB,下次 start/restart 会轮转压缩"
485
+ fi
486
+ echo "-------- 最近 8 行 --------"
487
+ tail -8 "$LOG_FILE" 2>/dev/null
488
+ else
489
+ warn "日志: 尚无 $LOG_FILE"
490
+ fi
491
+ }
492
+
493
+ if [ "${1:-}" = "--set-password" ]; then
494
+ if [ -z "${2:-}" ]; then
495
+ err "❌ 请提供新密码: --set-password \"新密码\""
496
+ exit 1
497
+ fi
498
+ "$NODE_BIN" "$SERVER_DIR/boot.cjs" --set-password "$2"
499
+ ok "✓ 密码已设置"
500
+ exit 0
501
+ fi
502
+
503
+ CMD="${1:-restart}"
504
+ if [ "$CMD" = "--port" ]; then
505
+ CMD="restart"
506
+ elif [ "$CMD" = "start" ] || [ "$CMD" = "stop" ] || [ "$CMD" = "restart" ] || [ "$CMD" = "status" ]; then
507
+ shift
508
+ else
509
+ CMD="restart"
510
+ fi
511
+
512
+ case "$CMD" in
513
+ start) start_server "$@" ;;
514
+ stop) stop_server ;;
515
+ restart)
516
+ # 不再用固定 sleep 1:stop 只保证进程退出,端口未必立刻可用。
517
+ # start_server 内部会等端口释放(START_WAIT_SEC),这里只做一次
518
+ # 短暂的进程回收间隔,避免 stop 刚 kill 完就 bind。
519
+ stop_server
520
+ sleep 1
521
+ start_server "$@"
522
+ ;;
523
+ status) status_server "$@" ;;
524
+ *)
525
+ err "❌ 未知命令: $CMD"
526
+ echo "可用命令: start, stop, restart, status"
527
+ exit 1
528
+ ;;
529
+ esac