@dongnanyang/deploy-cli 0.6.1 → 0.7.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.
package/dist/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  const argv = process.argv.slice(2);
3
3
  if (argv.length === 0 || argv[0] === "tui") await import("./main.js");
4
4
  else {
5
- const cli = await import("./cli-DEqPcFVu.js");
5
+ const cli = await import("./cli-Dl4SYt_0.js");
6
6
  process.exitCode = await cli.main(argv);
7
7
  }
8
8
  //#endregion
@@ -2,7 +2,7 @@ import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-CVqF
2
2
  import { readFileSync } from "fs";
3
3
  import { resolve } from "path";
4
4
  import { parse, stringify } from "yaml";
5
- import { accessSync, constants, existsSync as existsSync$1, lstatSync, readdirSync as readdirSync$1, renameSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync$1 } from "node:fs";
5
+ import { accessSync, constants, existsSync as existsSync$1, lstatSync, readFileSync as readFileSync$1, readdirSync as readdirSync$1, renameSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync$1 } from "node:fs";
6
6
  import { join as join$1, resolve as resolve$1 } from "node:path";
7
7
  import { spawn } from "node:child_process";
8
8
  //#region src/core/project.ts
@@ -17,6 +17,7 @@ const VALID_SSL = [
17
17
  "acme",
18
18
  "custom"
19
19
  ];
20
+ const VALID_UPDATE = ["git-pull", "none"];
20
21
  /** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
21
22
  var ProjectConfigError = class extends Error {
22
23
  field;
@@ -46,15 +47,15 @@ function loadProject(dir) {
46
47
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
47
48
  return validate(parsed);
48
49
  }
49
- /** 校验并规范化 deploy.yaml 模型:name → type 合法性 → 类型必填字段 → nginx.domain 非空 */
50
+ /** 校验并规范化 deploy.yaml 模型:name → type 合法性 → 类型必填字段 → nginx.domain 非空 → deploy 段值域 */
50
51
  function validate(raw) {
51
52
  const name = raw.name;
52
53
  if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
53
54
  const type = raw.type;
54
55
  if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
55
56
  if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
56
- if (type === "image" && (typeof raw.image !== "string" || raw.image === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
57
- if (type === "static" && (typeof raw.root !== "string" || raw.root === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
57
+ if (type === "image" && (typeof raw.image !== "string" || raw.image.trim() === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
58
+ if (type === "static" && (typeof raw.root !== "string" || raw.root.trim() === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
58
59
  if (raw.nginx !== void 0 && raw.nginx !== null) {
59
60
  const nginx = raw.nginx;
60
61
  if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
@@ -62,6 +63,19 @@ function validate(raw) {
62
63
  if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
63
64
  if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
64
65
  }
66
+ if (raw.deploy !== void 0 && raw.deploy !== null) {
67
+ const deploy = raw.deploy;
68
+ if (typeof deploy !== "object" || Array.isArray(deploy)) throw new ProjectConfigError("deploy 应为对象", "deploy");
69
+ const dp = deploy;
70
+ if (dp.update !== void 0 && dp.update !== null) {
71
+ if (typeof dp.update !== "string" || !VALID_UPDATE.includes(dp.update)) throw new ProjectConfigError(`deploy.update 非法: ${JSON.stringify(dp.update)},合法值: git-pull | none(不设=不自动更新)`, "deploy.update");
72
+ }
73
+ if (dp.build !== void 0 && dp.build !== null && typeof dp.build !== "string") throw new ProjectConfigError("deploy.build 应为字符串(构建命令)", "deploy.build");
74
+ for (const hook of ["pre", "post"]) {
75
+ const hooks = dp[hook];
76
+ if (hooks !== void 0 && hooks !== null && (!Array.isArray(hooks) || hooks.some((c) => typeof c !== "string"))) throw new ProjectConfigError(`deploy.${hook} 应为字符串数组(命令列表)`, `deploy.${hook}`);
77
+ }
78
+ }
65
79
  const d = raw;
66
80
  if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
67
81
  return d;
@@ -111,18 +125,33 @@ function removeProject(cfg, name) {
111
125
  projects
112
126
  };
113
127
  }
114
- /** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment) */
128
+ /** image 型生成的 docker-compose.yml 标记头(护栏 marker):既有同名文件无此头则拒绝覆盖(终审 M1:防绑架项目文件) */
129
+ const COMPOSE_MARKER = "# generated by deploy-cli — do not edit";
130
+ /** 既有文件内容是否带 COMPOSE_MARKER 头(首行) */
131
+ function hasComposeMarker(content) {
132
+ return content.split("\n", 1)[0]?.trim() === COMPOSE_MARKER;
133
+ }
134
+ /** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment),首行带 COMPOSE_MARKER 标记头 */
115
135
  function generateCompose(d) {
116
136
  if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
117
- if (typeof d.image !== "string" || d.image === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
137
+ if (typeof d.image !== "string" || d.image.trim() === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
118
138
  const service = { image: d.image };
119
139
  if (d.ports && d.ports.length > 0) service.ports = d.ports;
120
140
  if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
121
141
  if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
122
- return stringify({ services: { [d.name]: service } });
142
+ return `${COMPOSE_MARKER}\n${stringify({ services: { [d.name]: service } })}`;
123
143
  }
124
144
  //#endregion
125
145
  //#region src/core/exec.ts
146
+ /**
147
+ * stderr 摘要(失败信息用):优先命中 /error|fatal|failed/i 的行(至多尾 3 条),无命中取尾部 3 行。
148
+ * docker compose / nginx 等工具把进度打在 stderr 前部,取前部会挤掉真错误行(M1-T5 评审修复,R12 同缺陷同修)。
149
+ */
150
+ function stderrSummary(stderr) {
151
+ const lines = stderr.trim().split("\n").filter((line) => line.trim() !== "");
152
+ const errors = lines.filter((line) => /error|fatal|failed/i.test(line));
153
+ return (errors.length > 0 ? errors.slice(-3) : lines.slice(-3)).join(" ");
154
+ }
126
155
  /** 仅 spawn 失败(ENOENT)与超时抛出 */
127
156
  var ExecError = class extends Error {
128
157
  result;
@@ -212,13 +241,15 @@ async function run(cmd, args, opts = {}) {
212
241
  settled = true;
213
242
  clearTimeout(timeoutTimer);
214
243
  clearTimeout(killTimer);
244
+ const stderr = err.flush();
215
245
  const result = {
216
246
  code: code ?? (timedOut ? 124 : 1),
217
247
  stdout: out.flush(),
218
- stderr: err.flush() + timeoutNote
248
+ stderr: stderr + timeoutNote
219
249
  };
220
250
  if (timedOut) {
221
- reject(new ExecError(`timeout: ${cmdLine}`, result));
251
+ const summary = stderrSummary(stderr);
252
+ reject(new ExecError(`timeout: ${cmdLine}${summary ? `: ${summary}` : ""}`, result));
222
253
  return;
223
254
  }
224
255
  resolve(result);
@@ -235,11 +266,9 @@ function logsArgs(idOrName, o) {
235
266
  args.push(idOrName);
236
267
  return args;
237
268
  }
238
- /** 失败信息:命令原文 + exit 码 + stderr 摘要(优先 error/fatal/failed 行,无则取尾部 3 行——docker compose 等工具把进度打在 stderr 前部,取前 3 行会挤掉真错误) */
269
+ /** 失败信息:命令原文 + exit 码 + stderr 摘要(stderrSummary:优先错误行、否则尾部——docker compose 等工具把进度打在 stderr 前部) */
239
270
  function execFailureMessage(cmd, args, result) {
240
- const lines = result.stderr.trim().split("\n").filter((line) => line.trim() !== "");
241
- const errors = lines.filter((line) => /error|fatal|failed/i.test(line));
242
- const summary = (errors.length > 0 ? errors.slice(-3) : lines.slice(-3)).join(" ");
271
+ const summary = stderrSummary(result.stderr);
243
272
  return `命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`;
244
273
  }
245
274
  /** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 (l) => void */
@@ -376,9 +405,9 @@ function validateSpec(spec) {
376
405
  function validateAbsPath(field, value) {
377
406
  if (!ABS_PATH_RE.test(value)) throw new Error(`NginxSiteSpec.${field} 非法: ${JSON.stringify(value)},须为绝对路径且不含 conf 元字符与空白`);
378
407
  }
379
- /** 失败信息:命令原文 + exit 码 + stderr 摘要(包裹为 ExecError,附完整结果) */
408
+ /** 失败信息:命令原文 + exit 码 + stderr 摘要(stderrSummary:优先错误行、否则尾部,R12 与 docker.ts 同口径;包裹为 ExecError,附完整结果) */
380
409
  function execFailure(cmd, args, result, note) {
381
- const summary = result.stderr.trim().split("\n").filter((line) => line.trim() !== "").slice(0, 3).join(" ");
410
+ const summary = stderrSummary(result.stderr);
382
411
  return new ExecError(`${note ? `${note}: ` : ""}命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`, result);
383
412
  }
384
413
  /**
@@ -668,6 +697,15 @@ function expectOk(result, cmd, args, hint) {
668
697
  if (result.code !== 0) throw new Error(`${execFailureMessage(cmd, args, result)}${hint ? `;${hint}` : ""}`);
669
698
  }
670
699
  /**
700
+ * 流水线步超时(终审 M1 明文落定:全部步骤都挂超时,不保留「构建步不设超时、靠 Ctrl-C」的无超时步——
701
+ * git pull 挂起不得永久挂死流水线;超时走 ExecError,消息含 stderr 摘要)。
702
+ * 长步 600s:update(git pull)/pre/post 钩子(可能跑迁移)/build/up(docker 构建与镜像拉取耗时不可控),
703
+ * docker 子进程(含 health 步的 docker ps 查询)同为 600s;
704
+ * 短步 120s:nginx 配置下发(nginx -t / reload / acme 签发)。
705
+ */
706
+ const STEP_TIMEOUT_LONG_MS = 6e5;
707
+ const STEP_TIMEOUT_SHORT_MS = 12e4;
708
+ /**
671
709
  * 部署流水线(失败即停):update(git pull) → pre → build → up → nginx → health → post(R10 上线后钩子)。
672
710
  * 步骤跳过口径:update 仅 deploy.update==='git-pull' 时执行(缺省/none 跳过);pre/post 无钩子跳过;
673
711
  * static 型跳过 build/up(自定义 build 也不跑);image 型无自定义 build 跳过 build(compose 文件在 up 步才生成);
@@ -675,7 +713,13 @@ function expectOk(result, cmd, args, hint) {
675
713
  * 某步失败(含 Runner reject:spawn 失败/超时)→ 该步 fail 事件 + 后续步骤绝不执行。
676
714
  */
677
715
  async function runDeploy(project, opts) {
678
- const runner = opts.runner ?? run;
716
+ const rawRunner = opts.runner ?? run;
717
+ /** 给 shell-out 挂默认超时(终审 M1 防挂起):调用方显式传 timeoutMs 时以其为准 */
718
+ const withTimeout = (ms) => (cmd, args, o = {}) => rawRunner(cmd, args, {
719
+ ...o,
720
+ timeoutMs: o.timeoutMs ?? ms
721
+ });
722
+ const runner = withTimeout(STEP_TIMEOUT_LONG_MS);
679
723
  const docker = opts.docker ?? createDocker(runner);
680
724
  const emit = opts.onEvent;
681
725
  /** 包裹单步:start → fn → ok;fn 抛错 → fail 事件 + 停(返回结果由调用方 return) */
@@ -739,7 +783,11 @@ async function runDeploy(project, opts) {
739
783
  if (project.type !== "static") {
740
784
  const upFile = project.type === "image" ? "docker-compose.yml" : composeFile;
741
785
  const stopped = await step("up", `docker compose -f ${upFile} up -d`, async () => {
742
- if (project.type === "image") writeFileSync$1(resolve$1(opts.cwd, upFile), generateCompose(project), "utf-8");
786
+ if (project.type === "image") {
787
+ const target = resolve$1(opts.cwd, upFile);
788
+ if (existsSync$1(target) && !hasComposeMarker(readFileSync$1(target, "utf-8"))) throw new Error(`${upFile} 已存在且非 deploy-cli 生成(缺 marker 头 "${COMPOSE_MARKER}"),拒绝覆盖;请改名/移走该文件,或改用 compose 型项目`);
789
+ writeFileSync$1(target, generateCompose(project), "utf-8");
790
+ }
743
791
  expectOk(await docker.composeUp(opts.cwd, upFile), "docker", [
744
792
  "compose",
745
793
  "-f",
@@ -752,7 +800,7 @@ async function runDeploy(project, opts) {
752
800
  }
753
801
  if ((opts.applyNginx ?? true) && project.nginx) {
754
802
  const stopped = await step("nginx", void 0, async () => {
755
- await (opts.nginx ?? createNginx(runner)).applySite(buildSpec(project, false));
803
+ await (opts.nginx ?? createNginx(withTimeout(STEP_TIMEOUT_SHORT_MS))).applySite(buildSpec(project, false));
756
804
  });
757
805
  if (stopped) return stopped;
758
806
  }
@@ -1227,8 +1275,9 @@ async function ps(args, options = {}) {
1227
1275
  if (all) listOpts.all = true;
1228
1276
  if (nameFilter) listOpts.name = nameFilter;
1229
1277
  const containers = await docker.listContainers(listOpts);
1278
+ const rows = projectName === void 0 ? containers : containers.filter((c) => containerBelongsToProject(c.name, projectName));
1230
1279
  log("NAME IMAGE STATE PORTS");
1231
- for (const container of containers) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
1280
+ for (const container of rows) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
1232
1281
  return 0;
1233
1282
  } catch (err) {
1234
1283
  error(err instanceof Error ? err.message : String(err));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dongnanyang/deploy-cli",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Local CLI TUI for SSH tunnels & deploy scripts",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,6 +16,7 @@
16
16
  "build": "tsdown",
17
17
  "start": "node bin/deploy-cli.js",
18
18
  "test": "vitest run",
19
+ "typecheck": "tsc --noEmit",
19
20
  "prepublishOnly": "npm run build",
20
21
  "docs:dev": "vitepress dev docs",
21
22
  "docs:build": "vitepress build docs",
@@ -30,6 +31,8 @@
30
31
  "yaml": "^2.9.1"
31
32
  },
32
33
  "devDependencies": {
34
+ "@types/node": "^26.6.11",
35
+ "@types/ssh2": "^1.15.6",
33
36
  "@vitejs/plugin-vue-jsx": "5.1.5",
34
37
  "@vue-tui/vite": "^0.3.0",
35
38
  "tsdown": "^0.12.0",