@xg-desgin/auto-deploy 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 XG Components
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
@@ -1,3 +1,160 @@
1
- # Temporary Holding Version
1
+ # @xg-desgin/auto-deploy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 基于 `ssh2` 与 `tar` 封装的自动化构建与 SSH/SFTP 远程服务器部署工具,提供 **Node API**、**Vite 构建插件** 与 **CLI 命令 (`xg-deploy`)** 三种使用方式。
4
+
5
+ ## 核心特性
6
+
7
+ - **压缩流式传输**:通过 `packDist()` 将本地构建目录打包为 `.tar.gz`,经 SFTP 上传到远程临时目录后自动解压并清理本地及远程临时压缩包。
8
+ - **多种 SSH 认证**:支持密码(`password`)、私钥内容(`privateKey`)及私钥文件(`privateKeyPath` + `passphrase`)。
9
+ - **独立配置文件**:通过 `loadDeployConfig()` 读取 JSON 配置文件,将服务器连接信息、构建命令、产物目录与远程路径统一配置在顶层。
10
+ - **支持试运行与跳过构建**:支持 `dryRun` 仅校验并打印部署计划,以及 `skipBuild` 跳过构建直接打包上传。
11
+ - **支持远程生命周期控制**:支持解压前清空目标目录(`cleanRemote`)和解压后执行自定义远程 shell 命令(`postCommands`)。
12
+
13
+ ---
14
+
15
+ ## 安装
16
+
17
+ ```bash
18
+ pnpm add -D @xg-desgin/auto-deploy
19
+ ```
20
+
21
+ ---
22
+
23
+ ## 配置文件说明
24
+
25
+ 使用 `loadDeployConfig({ cwd, configPath })` 读取并校验 JSON 配置文件。
26
+ 若未显式传入 `configPath`,将按以下顺序自动查找:
27
+ 1. `deploy.config.json`
28
+ 2. `scripts/deploy.config.json`
29
+
30
+ ### 配置文件示例
31
+
32
+ ```json
33
+ {
34
+ "host": "your-server-ip",
35
+ "port": 22,
36
+ "username": "root",
37
+ "password": "your-password",
38
+ "distDir": "dist",
39
+ "buildCommand": "pnpm build",
40
+ "remotePath": "/var/www/your-app",
41
+ "cleanRemote": false,
42
+ "postCommands": ["nginx -s reload"]
43
+ }
44
+ ```
45
+
46
+ ### `DeployConfigFile` 字段说明
47
+
48
+ | 字段 | 类型 | 必填 | 默认值 | 说明 |
49
+ | --- | --- | --- | --- | --- |
50
+ | `host` | `string` | 是 | - | 远程服务器地址 |
51
+ | `port` | `number` | 否 | `22` | SSH 端口号 |
52
+ | `username` | `string` | 是 | - | SSH 登录用户名 |
53
+ | `password` | `string` | 否* | - | SSH 登录密码(与 `privateKey` / `privateKeyPath` 至少配一项) |
54
+ | `privateKey` | `string` | 否* | - | SSH 私钥字符串内容 |
55
+ | `privateKeyPath` | `string` | 否* | - | SSH 私钥文件路径 |
56
+ | `passphrase` | `string` | 否 | - | 私钥密码 |
57
+ | `readyTimeout` | `number` | 否 | `30000` | SSH 连接超时时间(毫秒) |
58
+ | `distDir` | `string` | 否 | - | 本地构建输出目录 |
59
+ | `buildCommand` | `string` | 否 | - | 构建命令(未配置时跳过构建) |
60
+ | `remotePath` | `string` | 否 | - | 远程服务器目标部署目录 |
61
+ | `remoteTmpDir` | `string` | 否 | `'/tmp'` | 远程服务器临时上传目录 |
62
+ | `cleanRemote` | `boolean` | 否 | `false` | 解压前是否清空远程目标目录 |
63
+ | `postCommands` | `string[]` | 否 | - | 解压完成后在远程服务器执行的附加命令 |
64
+
65
+ ---
66
+
67
+ ## 使用方式
68
+
69
+ ### 1. Node API
70
+
71
+ 从 `@xg-desgin/auto-deploy` 导入所需方法:
72
+
73
+ ```ts
74
+ import { deploy, loadDeployConfig } from '@xg-desgin/auto-deploy';
75
+
76
+ const config = loadDeployConfig({ configPath: 'scripts/deploy.config.ui.json' });
77
+
78
+ const result = await deploy({
79
+ host: config.host,
80
+ port: config.port,
81
+ username: config.username,
82
+ password: config.password,
83
+ privateKey: config.privateKey,
84
+ privateKeyPath: config.privateKeyPath,
85
+ passphrase: config.passphrase,
86
+ readyTimeout: config.readyTimeout,
87
+ remoteTmpDir: config.remoteTmpDir,
88
+ remotePath: config.remotePath!,
89
+ distDir: config.distDir ?? 'dist',
90
+ buildCommand: config.buildCommand,
91
+ cleanRemote: config.cleanRemote,
92
+ postCommands: config.postCommands,
93
+ });
94
+
95
+ console.log('部署完成:', result);
96
+ ```
97
+
98
+ #### 导出的模块与函数
99
+
100
+ - `loadDeployConfig(options?)`: 读取并校验配置文件(校验 `host`、`username` 及认证字段)。
101
+ - `resolveConfigPath(configPath?, cwd?)`: 解析配置文件绝对路径。
102
+ - `deploy(options)`: 执行完整部署流程(可选构建 -> 打包 `.tar.gz` -> SFTP 上传与远程解压)。
103
+ - `packDist(distDir, tarFile?)`: 将指定目录打包为 `.tar.gz` 压缩包,返回压缩包路径。
104
+ - `uploadFile` / `uploadAndExtract` / `execSSH`: 底层 SSH/SFTP 工具函数。
105
+ - `defaultLogger`: 默认控制台日志器。
106
+
107
+ ---
108
+
109
+ ### 2. Vite 插件
110
+
111
+ 从 `@xg-desgin/auto-deploy/vite` 导入 `vitePluginAutoDeploy`,在 `vite build` 产物生成完毕(`closeBundle`)后自动打包并推送到远程服务器:
112
+
113
+ ```ts
114
+ import { defineConfig } from 'vite';
115
+ import { vitePluginAutoDeploy } from '@xg-desgin/auto-deploy/vite';
116
+
117
+ export default defineConfig({
118
+ plugins: [
119
+ vitePluginAutoDeploy({
120
+ enabled: process.env.AUTO_DEPLOY === 'true',
121
+ configPath: './deploy.config.json',
122
+ remotePath: '/var/www/your-app',
123
+ targetName: '我的应用',
124
+ }),
125
+ ],
126
+ });
127
+ ```
128
+
129
+ #### `ViteAutoDeployOptions` 选项
130
+
131
+ | 字段 | 类型 | 默认值 | 说明 |
132
+ | --- | --- | --- | --- |
133
+ | `enabled` | `boolean` | `true` | 是否启用自动部署,可结合环境变量控制 |
134
+ | `configPath` | `string` | 自动查找 | 配置文件路径 |
135
+ | `config` | `Partial<DeployConfigFile>` | - | 内联服务器配置,优先级高于配置文件 |
136
+ | `remotePath` | `string` | - | 远程目标目录,优先级高于配置文件 |
137
+ | `targetName` | `string` | - | 日志展示用的部署目标名称 |
138
+ | `cleanRemote` | `boolean` | `false` | 解压前是否清空远程目录 |
139
+ | `postCommands` | `string[]` | - | 解压后执行的远程命令 |
140
+ | `dryRun` | `boolean` | `false` | 试运行模式 |
141
+ | `logger` | `DeployLogger` | `defaultLogger` | 自定义日志器 |
142
+
143
+ ---
144
+
145
+ ### 3. CLI 命令行 (`xg-deploy`)
146
+
147
+ ```bash
148
+ xg-deploy --config scripts/deploy.config.ui.json
149
+ xg-deploy --dist dist --skip-build --dry-run
150
+ ```
151
+
152
+ #### 命令行参数
153
+
154
+ - `-c, --config <path>`: 指定部署配置文件路径
155
+ - `-t, --target <name>`: 指定部署目标名称
156
+ - `-d, --dist <dir>`: 指定本地构建产物目录
157
+ - `-b, --build <cmd>`: 指定构建命令
158
+ - `--skip-build`: 跳过构建阶段,直接打包并上传产物
159
+ - `--dry-run`: 试运行模式,仅打印部署计划,不实际执行构建与上传
160
+ - `-h, --help`: 显示帮助信息
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,185 @@
1
+ import d from "node:fs";
2
+ import i from "node:path";
3
+ import { execSync as h } from "node:child_process";
4
+ import { Client as y } from "ssh2";
5
+ const l = ["deploy.config.json", "scripts/deploy.config.json"];
6
+ function $(e, r = process.cwd()) {
7
+ if (e)
8
+ return i.resolve(r, e);
9
+ for (const t of l) {
10
+ const a = i.resolve(r, t);
11
+ if (d.existsSync(a))
12
+ return a;
13
+ }
14
+ return i.resolve(r, l[0]);
15
+ }
16
+ function T(e = {}) {
17
+ const r = e.cwd ?? process.cwd(), t = $(e.configPath, r);
18
+ if (!d.existsSync(t))
19
+ throw new Error(`缺少配置文件:${t}`);
20
+ let a;
21
+ try {
22
+ const n = d.readFileSync(t, "utf-8");
23
+ a = JSON.parse(n);
24
+ } catch (n) {
25
+ const o = n instanceof Error ? n.message : String(n);
26
+ throw new Error(`解析配置文件失败 (${t}):${o}`);
27
+ }
28
+ const s = [];
29
+ if (a.host || s.push("host"), a.username || s.push("username"), !a.password && !a.privateKey && !a.privateKeyPath && s.push("password (或 privateKey / privateKeyPath)"), s.length > 0)
30
+ throw new Error(`配置文件缺少必要字段 (${t}): ${s.join(", ")}`);
31
+ return a;
32
+ }
33
+ const w = {
34
+ info(e) {
35
+ console.log(e);
36
+ },
37
+ success(e) {
38
+ console.log(`\x1B[32m${e}\x1B[0m`);
39
+ },
40
+ warn(e) {
41
+ console.warn(`\x1B[33m${e}\x1B[0m`);
42
+ },
43
+ error(e) {
44
+ console.error(`\x1B[31m${e}\x1B[0m`);
45
+ }
46
+ };
47
+ function g(e, r) {
48
+ return new Promise((t, a) => {
49
+ e.exec(r, (s, n) => {
50
+ if (s) return a(s);
51
+ let o = "", m = "";
52
+ n.on("close", (c) => {
53
+ c === 0 ? t(o) : a(new Error(`命令执行失败 (${c}): ${m || o}`));
54
+ }).on("data", (c) => {
55
+ o += c.toString();
56
+ }).stderr.on("data", (c) => {
57
+ m += c.toString();
58
+ });
59
+ });
60
+ });
61
+ }
62
+ function x(e, r, t) {
63
+ return new Promise((a, s) => {
64
+ e.fastPut(r, t, (n) => {
65
+ if (n) return s(n);
66
+ a();
67
+ });
68
+ });
69
+ }
70
+ function p(e) {
71
+ const r = {
72
+ host: e.host,
73
+ port: e.port,
74
+ username: e.username,
75
+ readyTimeout: e.readyTimeout ?? 3e4
76
+ };
77
+ if (e.password && (r.password = e.password), e.privateKey)
78
+ r.privateKey = e.privateKey;
79
+ else if (e.privateKeyPath) {
80
+ const t = i.resolve(e.privateKeyPath);
81
+ if (!d.existsSync(t))
82
+ throw new Error(`SSH 私钥文件不存在:${t}`);
83
+ r.privateKey = d.readFileSync(t);
84
+ }
85
+ return e.passphrase && (r.passphrase = e.passphrase), r;
86
+ }
87
+ async function P(e) {
88
+ const r = e.remoteTmpDir || "/tmp", t = i.posix.join(r, `dist-${Date.now()}.tar.gz`), a = p(e), s = new y();
89
+ return await new Promise((n, o) => {
90
+ s.on("ready", () => {
91
+ e.onAuthenticated?.(), s.sftp(async (m, c) => {
92
+ if (m)
93
+ return s.end(), o(m);
94
+ try {
95
+ await x(c, e.tarFile, t), e.onUploaded?.();
96
+ const u = [];
97
+ e.cleanRemote && u.push(`rm -rf ${e.remotePath}`), u.push(
98
+ `mkdir -p ${e.remotePath}`,
99
+ `tar -xzf ${t} -C ${e.remotePath}`,
100
+ `rm -f ${t}`
101
+ ), e.postCommands?.length && u.push(...e.postCommands), await g(s, u.join(" && ")), s.end(), n();
102
+ } catch (u) {
103
+ s.end(), o(u);
104
+ }
105
+ });
106
+ }).on("error", (m) => {
107
+ o(m);
108
+ }).connect(a);
109
+ }), t;
110
+ }
111
+ function S(e, r) {
112
+ if (!d.existsSync(e))
113
+ throw new Error(`未找到构建输出目录:${e}`);
114
+ const t = r ?? i.resolve(i.dirname(e), `dist-${Date.now()}.tar.gz`);
115
+ return h(`tar -czf "${t}" -C "${e}" .`, { stdio: "pipe" }), t;
116
+ }
117
+ async function D(e) {
118
+ const r = e.logger ?? w, t = e.cwd ?? process.cwd(), a = Number(e.port) || 22, s = i.resolve(t, e.distDir), n = e.targetName || "应用产物", o = !!e.buildCommand && !e.skipBuild;
119
+ if (r.success("================================================"), r.success("🚀 自动化打包与远程服务器部署插件"), r.success(`================================================
120
+ `), r.info(`\x1B[34m[部署目标]\x1B[0m ${n}`), r.info("\x1B[34m[部署目标环境]\x1B[0m"), r.info(`- 主机: ${e.host}:${a}`), r.info(`- 用户: ${e.username}`), r.info(`- 本地产物目录: ${s}`), r.info(`- 远程目标目录: ${e.remotePath}
121
+ `), e.dryRun)
122
+ return r.warn("[Dry Run] 试运行模式:跳过实际构建、压缩与远程上传。"), {
123
+ targetName: n,
124
+ distDir: s,
125
+ remotePath: e.remotePath,
126
+ remoteTar: "",
127
+ host: e.host,
128
+ port: a,
129
+ dryRun: !0
130
+ };
131
+ const m = o ? 3 : 2;
132
+ let c = 1;
133
+ o && e.buildCommand && (r.info(`\x1B[34m[${c}/${m}] 正在构建 ${n} 生产产物...\x1B[0m`), r.info(`\x1B[36m> ${e.buildCommand}\x1B[0m`), h(e.buildCommand, { stdio: "inherit", cwd: t }), c += 1), r.info(`
134
+ \x1B[34m[${c}/${m}] 正在打包为单个压缩包以加速传输...\x1B[0m`);
135
+ const u = S(s, e.tarFile);
136
+ c += 1, r.info(`
137
+ \x1B[34m[${c}/${m}] 正在建立 SSH 连接并上传部署包...\x1B[0m`);
138
+ let f = "";
139
+ try {
140
+ f = await P({
141
+ host: e.host,
142
+ port: a,
143
+ username: e.username,
144
+ password: e.password,
145
+ privateKey: e.privateKey,
146
+ privateKeyPath: e.privateKeyPath,
147
+ passphrase: e.passphrase,
148
+ readyTimeout: e.readyTimeout,
149
+ tarFile: u,
150
+ remotePath: e.remotePath,
151
+ remoteTmpDir: e.remoteTmpDir,
152
+ cleanRemote: e.cleanRemote,
153
+ postCommands: e.postCommands,
154
+ onAuthenticated: () => {
155
+ r.success("✔ SSH 认证通过!正在上传部署包...");
156
+ },
157
+ onUploaded: () => {
158
+ r.success("✔ 压缩包上传完毕,正在解压并更新到目标目录...");
159
+ }
160
+ });
161
+ } finally {
162
+ d.existsSync(u) && d.unlinkSync(u);
163
+ }
164
+ return r.success(`
165
+ ================================================`), r.success(`🎉 部署成功!${n} 产物已同步至服务器:`), r.success(` ${e.username}@${e.host}:${e.remotePath}`), r.success(`================================================
166
+ `), {
167
+ targetName: n,
168
+ distDir: s,
169
+ remotePath: e.remotePath,
170
+ remoteTar: f,
171
+ host: e.host,
172
+ port: a,
173
+ dryRun: !1
174
+ };
175
+ }
176
+ export {
177
+ D as a,
178
+ x as b,
179
+ w as d,
180
+ g as e,
181
+ T as l,
182
+ S as p,
183
+ $ as r,
184
+ P as u
185
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ import { d as o, l as r, a as n } from "./chunks/deploy-B6r8Qb34.js";
3
+ function a(t) {
4
+ const e = {
5
+ skipBuild: !1,
6
+ dryRun: !1,
7
+ help: !1
8
+ };
9
+ for (let s = 0; s < t.length; s += 1) {
10
+ const i = t[s];
11
+ i === "--help" || i === "-h" ? e.help = !0 : i === "--skip-build" ? e.skipBuild = !0 : i === "--dry-run" ? e.dryRun = !0 : i.startsWith("--config=") ? e.configPath = i.slice(9) : (i === "--config" || i === "-c") && t[s + 1] ? e.configPath = t[++s] : i.startsWith("--target=") ? e.target = i.slice(9) : (i === "--target" || i === "-t") && t[s + 1] ? e.target = t[++s] : i.startsWith("--dist=") ? e.distDir = i.slice(7) : (i === "--dist" || i === "-d") && t[s + 1] ? e.distDir = t[++s] : i.startsWith("--build=") ? e.buildCommand = i.slice(8) : (i === "--build" || i === "-b") && t[s + 1] && (e.buildCommand = t[++s]);
12
+ }
13
+ return e;
14
+ }
15
+ function l() {
16
+ console.log(`
17
+ xg-deploy - 自动化构建与 SSH/SFTP 远程部署工具
18
+
19
+ 用法:
20
+ xg-deploy [options]
21
+
22
+ 选项:
23
+ -c, --config <path> 指定部署配置文件路径(默认自动查找 deploy.config.json 或 scripts/deploy.config.json)
24
+ -t, --target <name> 指定部署目标(对应配置文件中的 targets.<name>)
25
+ -d, --dist <dir> 指定本地构建产物目录
26
+ -b, --build <cmd> 指定构建命令
27
+ --skip-build 跳过构建阶段,直接打包并上传产物
28
+ --dry-run 试运行模式,仅打印部署计划,不实际执行构建和上传
29
+ -h, --help 显示帮助信息
30
+ `);
31
+ }
32
+ async function d() {
33
+ const t = a(process.argv.slice(2));
34
+ if (t.help) {
35
+ l();
36
+ return;
37
+ }
38
+ const e = r({ configPath: t.configPath });
39
+ if (!e.remotePath)
40
+ throw new Error("配置文件缺少必要字段:remotePath");
41
+ await n({
42
+ host: e.host,
43
+ port: e.port,
44
+ username: e.username,
45
+ password: e.password,
46
+ privateKey: e.privateKey,
47
+ privateKeyPath: e.privateKeyPath,
48
+ passphrase: e.passphrase,
49
+ readyTimeout: e.readyTimeout,
50
+ remoteTmpDir: e.remoteTmpDir,
51
+ remotePath: e.remotePath,
52
+ distDir: t.distDir ?? e.distDir ?? "dist",
53
+ buildCommand: t.buildCommand ?? e.buildCommand,
54
+ skipBuild: t.skipBuild,
55
+ targetName: t.target,
56
+ cleanRemote: e.cleanRemote,
57
+ postCommands: e.postCommands,
58
+ dryRun: t.dryRun
59
+ });
60
+ }
61
+ d().catch((t) => {
62
+ const e = t instanceof Error ? t.message : String(t);
63
+ o.error(`
64
+ ❌ 部署失败: ${e}`), process.exit(1);
65
+ });
@@ -0,0 +1,14 @@
1
+ import { DeployConfigFile } from './types.js';
2
+ export interface LoadConfigOptions {
3
+ cwd?: string;
4
+ configPath?: string;
5
+ defaultTarget?: string;
6
+ }
7
+ /**
8
+ * 解析配置文件路径:若显式传入 configPath 则直接使用,否则按默认候选路径查找
9
+ */
10
+ export declare function resolveConfigPath(configPath?: string, cwd?: string): string;
11
+ /**
12
+ * 读取并严格校验部署配置文件
13
+ */
14
+ export declare function loadDeployConfig(options?: LoadConfigOptions): DeployConfigFile;
@@ -0,0 +1,9 @@
1
+ import { DeployOptions, DeployResult } from './types.js';
2
+ /**
3
+ * 将本地构建目录打包为单个 .tar.gz 压缩包
4
+ */
5
+ export declare function packDist(distDir: string, tarFile?: string): string;
6
+ /**
7
+ * 执行完整自动化部署流程:可选构建 -> 本地打包 tar.gz -> SSH/SFTP 上传并解压
8
+ */
9
+ export declare function deploy(options: DeployOptions): Promise<DeployResult>;
@@ -0,0 +1,7 @@
1
+ export { loadDeployConfig, resolveConfigPath } from './config.js';
2
+ export type { LoadConfigOptions } from './config.js';
3
+ export { deploy, packDist } from './deploy.js';
4
+ export { defaultLogger } from './logger.js';
5
+ export { execSSH, uploadAndExtract, uploadFile } from './ssh.js';
6
+ export type { SshUploadOptions } from './ssh.js';
7
+ export type { DeployConfigFile, DeployLogger, DeployOptions, DeployResult, DeployTargetConfig, ResolvedDeployTarget, } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ import { d as o, a as s, e as l, l as d, p, r, u as t, b as f } from "./chunks/deploy-B6r8Qb34.js";
2
+ export {
3
+ o as defaultLogger,
4
+ s as deploy,
5
+ l as execSSH,
6
+ d as loadDeployConfig,
7
+ p as packDist,
8
+ r as resolveConfigPath,
9
+ t as uploadAndExtract,
10
+ f as uploadFile
11
+ };
@@ -0,0 +1,2 @@
1
+ import { DeployLogger } from './types.js';
2
+ export declare const defaultLogger: DeployLogger;
package/dist/ssh.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { Client, SFTPWrapper } from 'ssh2';
2
+ export interface SshUploadOptions {
3
+ host: string;
4
+ port: number;
5
+ username: string;
6
+ password?: string;
7
+ privateKey?: string | Buffer;
8
+ privateKeyPath?: string;
9
+ passphrase?: string;
10
+ readyTimeout?: number;
11
+ tarFile: string;
12
+ remotePath: string;
13
+ remoteTmpDir?: string;
14
+ cleanRemote?: boolean;
15
+ postCommands?: string[];
16
+ onAuthenticated?: () => void;
17
+ onUploaded?: () => void;
18
+ }
19
+ /**
20
+ * 在远程服务器执行单条 shell 命令
21
+ */
22
+ export declare function execSSH(conn: Client, command: string): Promise<string>;
23
+ /**
24
+ * 通过 SFTP 上传单个文件
25
+ */
26
+ export declare function uploadFile(sftp: SFTPWrapper, localFile: string, remoteFile: string): Promise<void>;
27
+ /**
28
+ * 建立 SSH 连接,上传 tar.gz 并远程解压部署
29
+ */
30
+ export declare function uploadAndExtract(options: SshUploadOptions): Promise<string>;
@@ -0,0 +1,100 @@
1
+ export interface DeployTargetConfig {
2
+ /** 部署目标显示名称 */
3
+ name?: string;
4
+ /** 本地包或应用目录(用于执行构建命令与定位 dist) */
5
+ pkgDir?: string;
6
+ /** 构建输出目录(默认 `<pkgDir>/dist` 或 `dist`) */
7
+ distDir?: string;
8
+ /** 构建命令(例如 `pnpm -C playground/ui build`) */
9
+ buildCommand?: string;
10
+ /** 远程服务器目标部署目录 */
11
+ remotePath: string;
12
+ /** 解压前是否清空远程目标目录 */
13
+ cleanRemote?: boolean;
14
+ /** 解压完成后在远程服务器执行的附加命令 */
15
+ postCommands?: string[];
16
+ }
17
+ export interface DeployConfigFile {
18
+ host: string;
19
+ port?: number;
20
+ username: string;
21
+ password?: string;
22
+ privateKey?: string;
23
+ privateKeyPath?: string;
24
+ passphrase?: string;
25
+ readyTimeout?: number;
26
+ distDir?: string;
27
+ buildCommand?: string;
28
+ remotePath?: string;
29
+ remoteTmpDir?: string;
30
+ cleanRemote?: boolean;
31
+ postCommands?: string[];
32
+ targets?: Record<string, DeployTargetConfig>;
33
+ }
34
+ export interface ResolvedDeployTarget {
35
+ target: string;
36
+ name: string;
37
+ pkgDir?: string;
38
+ distDir?: string;
39
+ buildCommand?: string;
40
+ remotePath: string;
41
+ cleanRemote?: boolean;
42
+ postCommands?: string[];
43
+ }
44
+ export interface DeployOptions {
45
+ /** 服务器地址 */
46
+ host: string;
47
+ /** SSH 端口,默认 22 */
48
+ port?: number;
49
+ /** SSH 用户名 */
50
+ username: string;
51
+ /** SSH 密码(与 privateKey / privateKeyPath 二选一) */
52
+ password?: string;
53
+ /** SSH 私钥内容 */
54
+ privateKey?: string | Buffer;
55
+ /** SSH 私钥文件路径 */
56
+ privateKeyPath?: string;
57
+ /** 私钥密码 */
58
+ passphrase?: string;
59
+ /** SSH 连接超时时间(毫秒),默认 30000 */
60
+ readyTimeout?: number;
61
+ /** 远程服务器部署目录 */
62
+ remotePath: string;
63
+ /** 远程服务器临时上传目录,默认 `/tmp` */
64
+ remoteTmpDir?: string;
65
+ /** 本地构建输出目录(如 `playground/ui/dist`) */
66
+ distDir: string;
67
+ /** 目标显示名称,用于日志展示 */
68
+ targetName?: string;
69
+ /** 可选构建命令,未设置或 skipBuild 为 true 时跳过构建 */
70
+ buildCommand?: string;
71
+ /** 执行构建命令的工作目录,默认 process.cwd() */
72
+ cwd?: string;
73
+ /** 是否跳过构建阶段,默认 false */
74
+ skipBuild?: boolean;
75
+ /** 是否在解压前清空远程目标目录,默认 false */
76
+ cleanRemote?: boolean;
77
+ /** 解压完成后在远程执行的附加 shell 命令 */
78
+ postCommands?: string[];
79
+ /** 本地临时压缩包路径,默认在 distDir 上级目录生成 `dist.tar.gz` */
80
+ tarFile?: string;
81
+ /** 试运行模式:仅校验并输出部署计划,不实际执行构建与远程上传 */
82
+ dryRun?: boolean;
83
+ /** 自定义日志输出 */
84
+ logger?: DeployLogger;
85
+ }
86
+ export interface DeployResult {
87
+ targetName: string;
88
+ distDir: string;
89
+ remotePath: string;
90
+ remoteTar: string;
91
+ host: string;
92
+ port: number;
93
+ dryRun: boolean;
94
+ }
95
+ export interface DeployLogger {
96
+ info(message: string): void;
97
+ success(message: string): void;
98
+ warn(message: string): void;
99
+ error(message: string): void;
100
+ }
package/dist/vite.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { Plugin } from 'vite';
2
+ import { DeployConfigFile, DeployLogger } from './types.js';
3
+ export interface ViteAutoDeployOptions {
4
+ /** 是否启用自动部署(默认 true,可结合环境变量控制) */
5
+ enabled?: boolean;
6
+ /** 配置文件路径(默认查找 deploy.config.json / scripts/deploy.config.json) */
7
+ configPath?: string;
8
+ /** 目标名称(对应配置文件中 targets.<name>) */
9
+ target?: string;
10
+ /** 内联服务器配置,优先级高于配置文件 */
11
+ config?: Partial<DeployConfigFile>;
12
+ /** 远程目标目录,优先级高于配置文件 */
13
+ remotePath?: string;
14
+ /** 显示名称 */
15
+ targetName?: string;
16
+ /** 解压前是否清空远程目录 */
17
+ cleanRemote?: boolean;
18
+ /** 解压后执行的远程命令 */
19
+ postCommands?: string[];
20
+ /** 试运行模式 */
21
+ dryRun?: boolean;
22
+ /** 自定义日志器 */
23
+ logger?: DeployLogger;
24
+ }
25
+ /**
26
+ * Vite 自动部署插件:在 `vite build` 产物生成完毕后自动打包并推送到远程服务器
27
+ */
28
+ export declare function vitePluginAutoDeploy(options?: ViteAutoDeployOptions): Plugin;
29
+ export default vitePluginAutoDeploy;
package/dist/vite.js ADDED
@@ -0,0 +1,46 @@
1
+ import i from "node:path";
2
+ import { l, a as n } from "./chunks/deploy-B6r8Qb34.js";
3
+ function f(e = {}) {
4
+ let a;
5
+ return {
6
+ name: "xg-auto-deploy",
7
+ apply: "build",
8
+ configResolved(t) {
9
+ a = t;
10
+ },
11
+ async closeBundle() {
12
+ if (e.enabled === !1)
13
+ return;
14
+ const t = a?.root ?? process.cwd(), m = a?.build.outDir ?? "dist", s = i.resolve(t, m), r = {
15
+ ...e.config?.host && e.config?.username ? e.config : l({ cwd: t, configPath: e.configPath }),
16
+ ...e.config
17
+ }, o = e.remotePath ?? r.remotePath;
18
+ if (!o)
19
+ throw new Error("缺少远程部署目录配置:请在插件选项或配置文件中设置 remotePath");
20
+ await n({
21
+ host: r.host,
22
+ port: r.port,
23
+ username: r.username,
24
+ password: r.password,
25
+ privateKey: r.privateKey,
26
+ privateKeyPath: r.privateKeyPath,
27
+ passphrase: r.passphrase,
28
+ readyTimeout: r.readyTimeout,
29
+ remoteTmpDir: r.remoteTmpDir,
30
+ remotePath: o,
31
+ distDir: s,
32
+ cwd: t,
33
+ skipBuild: !0,
34
+ targetName: e.targetName ?? e.target ?? "Vite 产物",
35
+ cleanRemote: e.cleanRemote ?? r.cleanRemote,
36
+ postCommands: e.postCommands ?? r.postCommands,
37
+ dryRun: e.dryRun,
38
+ logger: e.logger
39
+ });
40
+ }
41
+ };
42
+ }
43
+ export {
44
+ f as default,
45
+ f as vitePluginAutoDeploy
46
+ };
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@xg-desgin/auto-deploy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "基于 SSH/SFTP 的自动化构建与远程服务器部署工具(支持 Node API、CLI 与 Vite 插件)",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "bin": {
10
+ "xg-deploy": "./dist/cli.js"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ },
17
+ "./vite": {
18
+ "types": "./dist/vite.d.ts",
19
+ "import": "./dist/vite.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "dependencies": {
30
+ "ssh2": "^1.17.0"
31
+ },
32
+ "peerDependencies": {
33
+ "vite": ">=5.0.0"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "vite": {
37
+ "optional": true
38
+ }
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^22.0.0",
42
+ "typescript": "^5.6.0",
43
+ "vite": "^7.0.0",
44
+ "vite-plugin-dts": "^4.5.0",
45
+ "vitest": "^5.1.0"
46
+ },
47
+ "scripts": {
48
+ "build": "vite build",
49
+ "dev": "vite build --watch",
50
+ "test": "vitest run",
51
+ "typecheck": "tsc --noEmit"
52
+ }
6
53
  }