env-plugin 0.6.0 → 0.6.1
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/Container.js +18 -0
- package/dist/PostProxyServer.js +33 -6
- package/dist/client/assets/element-plus-aWS7wRSd.js.gz +0 -0
- package/dist/client/assets/index-CBMR4n-V.js.gz +0 -0
- package/dist/client/assets/index-a3AJbcK4.css.gz +0 -0
- package/dist/client/assets/vue-uvJWWccw.js.gz +0 -0
- package/dist/client/index.html +4 -4
- package/dist/controllers/DevServerController.js +9 -2
- package/dist/controllers/EnvController.js +42 -3
- package/dist/controllers/ImportExportController.js +43 -0
- package/dist/controllers/RequestLogController.js +33 -0
- package/dist/controllers/SystemSettingController.js +43 -0
- package/dist/index.js +5 -0
- package/dist/repositories/DevServerRepo.js +1 -3
- package/dist/repositories/EnvRepo.js +6 -3
- package/dist/repositories/PasswordRepo.js +5 -3
- package/dist/repositories/RouteRuleRepo.js +5 -3
- package/dist/repositories/SystemSettingRepo.js +42 -0
- package/dist/repositories/database.js +12 -0
- package/dist/routes/index.js +196 -28
- package/dist/service/EnvService.js +58 -0
- package/dist/service/ImportExportService.js +333 -0
- package/dist/service/PasswordService.js +8 -7
- package/dist/service/PreProxyServer.js +102 -9
- package/dist/service/RequestLogService.js +69 -0
- package/dist/service/RouteRuleService.js +14 -14
- package/dist/service/SystemSettingService.js +90 -0
- package/dist/types/index.js +3 -0
- package/dist/types/shared/EnvItem.js +8 -0
- package/dist/types/shared/ImportExport.js +55 -0
- package/dist/types/shared/RequestLog.js +28 -0
- package/dist/types/shared/SystemSetting.js +18 -0
- package/dist/utils/asyncHandler.js +12 -0
- package/dist/utils/resourceType.js +42 -0
- package/dist/utils/routeBuilder.js +19 -0
- package/package.json +16 -3
- package/templates/inject/envm-switcher.js +1418 -0
- package/dist/client/assets/element-plus-4FTV-s7u.js.gz +0 -0
- package/dist/client/assets/index-C2AH0x8U.css.gz +0 -0
- package/dist/client/assets/index-Db97pusF.js.gz +0 -0
- package/dist/client/assets/vue-CRjr1oeH.js.gz +0 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { v4 as uuidv4 } from "uuid";
|
|
2
|
+
import { AppError } from "../utils/errors.js";
|
|
2
3
|
/**
|
|
3
4
|
* 密码服务类
|
|
4
5
|
* 负责处理与密码相关的核心业务逻辑,包括密码的增删改查等操作
|
|
@@ -25,13 +26,13 @@ class PasswordService {
|
|
|
25
26
|
* 1. 校验输入参数合法性 2. 检查是否已存在相同名称 3. 如果设为默认密码则先清除其他默认密码 4. 生成唯一ID 5. 保存
|
|
26
27
|
* @param passwordItem - 待添加的密码信息(不含ID)
|
|
27
28
|
* @returns 新创建的密码
|
|
28
|
-
* @throws {
|
|
29
|
+
* @throws {AppError} 当输入参数不合法或已存在相同名称时抛出
|
|
29
30
|
*/
|
|
30
31
|
handleAdd(passwordItem) {
|
|
31
32
|
const { envId, name, isDefault } = passwordItem;
|
|
32
33
|
// 检查是否已存在相同名称的密码(同一环境下)
|
|
33
34
|
if (this.passwordRepo.existsByEnvIdAndName(envId, name)) {
|
|
34
|
-
throw new
|
|
35
|
+
throw new AppError(`添加失败,该环境下已存在名称为【${name}】的密码`);
|
|
35
36
|
}
|
|
36
37
|
// 如果设为默认密码,先清除其他默认密码
|
|
37
38
|
if (isDefault) {
|
|
@@ -54,19 +55,19 @@ class PasswordService {
|
|
|
54
55
|
* 1. 校验输入参数 2. 检查密码是否存在 3. 如果设为默认密码则先清除其他默认密码 4. 执行更新
|
|
55
56
|
* @param passwordItem - 包含待更新密码ID及字段的对象
|
|
56
57
|
* @returns 更新后的密码
|
|
57
|
-
* @throws {
|
|
58
|
+
* @throws {AppError} 当输入参数不合法或密码不存在时抛出
|
|
58
59
|
*/
|
|
59
60
|
handleUpdate(passwordItem) {
|
|
60
61
|
const { id, isDefault } = passwordItem;
|
|
61
62
|
// 检查密码是否存在
|
|
62
63
|
const existingPassword = this.passwordRepo.findOneById(id);
|
|
63
64
|
if (!existingPassword) {
|
|
64
|
-
throw new
|
|
65
|
+
throw new AppError(`更新失败,密码【${id}】不存在`);
|
|
65
66
|
}
|
|
66
67
|
// 如果更新了名称,检查是否与其他密码冲突
|
|
67
68
|
if (passwordItem.name && passwordItem.name !== existingPassword.name) {
|
|
68
69
|
if (this.passwordRepo.existsByEnvIdAndName(existingPassword.envId, passwordItem.name)) {
|
|
69
|
-
throw new
|
|
70
|
+
throw new AppError(`更新失败,该环境下已存在名称为【${passwordItem.name}】的密码`);
|
|
70
71
|
}
|
|
71
72
|
}
|
|
72
73
|
// 如果设为默认密码(从false改为true),先清除其他默认密码
|
|
@@ -84,14 +85,14 @@ class PasswordService {
|
|
|
84
85
|
* 删除指定密码
|
|
85
86
|
* 1. 校验输入参数 2. 检查密码是否存在 3. 执行删除操作
|
|
86
87
|
* @param passwordItem - 包含待删除密码ID的对象
|
|
87
|
-
* @throws {
|
|
88
|
+
* @throws {AppError} 当输入参数不合法或密码不存在时抛出
|
|
88
89
|
*/
|
|
89
90
|
handleDelete(passwordItem) {
|
|
90
91
|
const { id } = passwordItem;
|
|
91
92
|
// 检查密码是否存在
|
|
92
93
|
const existingPassword = this.passwordRepo.findOneById(id);
|
|
93
94
|
if (!existingPassword) {
|
|
94
|
-
throw new
|
|
95
|
+
throw new AppError(`删除失败,密码【${id}】不存在`);
|
|
95
96
|
}
|
|
96
97
|
// 执行删除
|
|
97
98
|
this.passwordRepo.delete(passwordItem);
|
|
@@ -5,8 +5,13 @@ import * as libCookie from "cookie";
|
|
|
5
5
|
import { minimatch } from "minimatch";
|
|
6
6
|
import * as fs from "fs";
|
|
7
7
|
import * as path from "path";
|
|
8
|
+
import * as zlib from "zlib";
|
|
8
9
|
import { getConfig } from "../utils/ResolveConfig.js";
|
|
9
10
|
import { devServerLogger } from "../utils/logger.js";
|
|
11
|
+
import { requestLogEmitter } from "./RequestLogService.js";
|
|
12
|
+
import { getInjectEnabled } from "./SystemSettingService.js";
|
|
13
|
+
import { classifyResourceType } from "../utils/resourceType.js";
|
|
14
|
+
import { v4 as uuidv4 } from "uuid";
|
|
10
15
|
class PreProxyServer {
|
|
11
16
|
/**
|
|
12
17
|
* 判断该端口是否已经有服务存在
|
|
@@ -109,6 +114,24 @@ class PreProxyServer {
|
|
|
109
114
|
}
|
|
110
115
|
return null;
|
|
111
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* 根据请求路径匹配路由规则,返回命中的 pathPrefix
|
|
119
|
+
* @param requestPath 请求路径
|
|
120
|
+
* @returns 命中的规则 pathPrefix,未命中返回 'default'
|
|
121
|
+
*/
|
|
122
|
+
getMatchedRule(requestPath) {
|
|
123
|
+
const routeRules = this.routeRuleRepo.getByEnvId(this.envId);
|
|
124
|
+
// 过滤出已启用的规则
|
|
125
|
+
const enabledRules = routeRules.filter((rule) => rule.enabled !== false);
|
|
126
|
+
// 按 pathPrefix 长度降序排序,确保最长前缀匹配优先
|
|
127
|
+
const sortedRules = [...enabledRules].sort((a, b) => b.pathPrefix.length - a.pathPrefix.length);
|
|
128
|
+
for (const rule of sortedRules) {
|
|
129
|
+
if (minimatch(requestPath, rule.pathPrefix, { dot: true })) {
|
|
130
|
+
return rule.pathPrefix;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return "default";
|
|
134
|
+
}
|
|
112
135
|
/**
|
|
113
136
|
* 生成代理中间件
|
|
114
137
|
* @returns
|
|
@@ -136,6 +159,9 @@ class PreProxyServer {
|
|
|
136
159
|
on: {
|
|
137
160
|
proxyReq: (proxyReq, req) => {
|
|
138
161
|
const requestPath = req.path || "/";
|
|
162
|
+
// 记录请求开始时间和日志 ID(用于 proxyRes 中的日志捕获)
|
|
163
|
+
req.__logStartTime = Date.now();
|
|
164
|
+
req.__logId = uuidv4();
|
|
139
165
|
// 优先使用路由规则的目标地址,否则使用环境默认的 apiBaseUrl
|
|
140
166
|
const customTarget = this.matchRouteRule(requestPath);
|
|
141
167
|
const target = customTarget || `${this.getEnvItem()?.apiBaseUrl}`;
|
|
@@ -143,6 +169,28 @@ class PreProxyServer {
|
|
|
143
169
|
this._rewrieCookieOnProxyReq(proxyReq, req);
|
|
144
170
|
},
|
|
145
171
|
proxyRes: (proxyRes, req, res) => {
|
|
172
|
+
// --- 请求日志捕获 ---
|
|
173
|
+
const startTime = req
|
|
174
|
+
.__logStartTime;
|
|
175
|
+
if (startTime) {
|
|
176
|
+
const duration = Date.now() - startTime;
|
|
177
|
+
const requestPath = req.path || "/";
|
|
178
|
+
const envItem = this.getEnvItem();
|
|
179
|
+
// 确定命中的路由规则
|
|
180
|
+
const matchedRule = this.getMatchedRule(requestPath);
|
|
181
|
+
requestLogEmitter.emit("log", {
|
|
182
|
+
id: req.__logId || uuidv4(),
|
|
183
|
+
timestamp: startTime,
|
|
184
|
+
method: req.method || "UNKNOWN",
|
|
185
|
+
url: requestPath,
|
|
186
|
+
statusCode: proxyRes.statusCode || 0,
|
|
187
|
+
duration,
|
|
188
|
+
matchedRule,
|
|
189
|
+
resourceType: classifyResourceType(matchedRule, proxyRes.headers["content-type"], requestPath),
|
|
190
|
+
envId: this.envId,
|
|
191
|
+
envName: envItem?.name || envItem?.apiBaseUrl || "",
|
|
192
|
+
});
|
|
193
|
+
}
|
|
146
194
|
this._rewriteSetCookieOnProxyRes(proxyRes);
|
|
147
195
|
this._rewriteLoginRedirect(proxyRes, req, res);
|
|
148
196
|
},
|
|
@@ -151,6 +199,21 @@ class PreProxyServer {
|
|
|
151
199
|
const customTarget = this.matchRouteRule(requestPath);
|
|
152
200
|
const target = customTarget || `${this.getEnvItem()?.apiBaseUrl}`;
|
|
153
201
|
proxyReq.setHeader("x-api-server", `${target}`);
|
|
202
|
+
// WebSocket 连接日志(无真实 HTTP 状态码,约定 101 Switching Protocols)
|
|
203
|
+
const matchedRule = this.getMatchedRule(requestPath);
|
|
204
|
+
const envItem = this.getEnvItem();
|
|
205
|
+
requestLogEmitter.emit("log", {
|
|
206
|
+
id: uuidv4(),
|
|
207
|
+
timestamp: Date.now(),
|
|
208
|
+
method: "WS",
|
|
209
|
+
url: requestPath,
|
|
210
|
+
statusCode: 101,
|
|
211
|
+
duration: 0,
|
|
212
|
+
matchedRule,
|
|
213
|
+
resourceType: "websocket",
|
|
214
|
+
envId: this.envId,
|
|
215
|
+
envName: envItem?.name || envItem?.apiBaseUrl || "",
|
|
216
|
+
});
|
|
154
217
|
},
|
|
155
218
|
},
|
|
156
219
|
});
|
|
@@ -211,18 +274,48 @@ class PreProxyServer {
|
|
|
211
274
|
try {
|
|
212
275
|
const body = Buffer.concat(chunks);
|
|
213
276
|
// 只对 HTML 且配置了注入脚本目录
|
|
214
|
-
|
|
277
|
+
// 且注入资源功能开关开启时,才执行脚本注入
|
|
278
|
+
if (contentType.includes("text/html") && getInjectEnabled()) {
|
|
215
279
|
const config = getConfig();
|
|
216
280
|
const scriptDir = config.injectScriptDir;
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
281
|
+
// 开发服务器(Vite/Webpack/Rspack 等)可能对响应开启 gzip/br 压缩,
|
|
282
|
+
// 此时 body 是压缩后的二进制数据:直接按 utf8 解码会得到乱码,
|
|
283
|
+
// 注入后返回的未压缩内容却仍带着 Content-Encoding 头,浏览器按
|
|
284
|
+
// 该编码解压就会报 ERR_CONTENT_DECODING_FAILED。
|
|
285
|
+
// 因此先解压再注入,最后按原编码重新压缩,保持响应头与响应体一致。
|
|
286
|
+
const contentEncoding = String(proxyRes.headers["content-encoding"] || "").toLowerCase();
|
|
287
|
+
let decodedBody = body;
|
|
288
|
+
if (contentEncoding === "gzip" || contentEncoding === "x-gzip") {
|
|
289
|
+
decodedBody = zlib.gunzipSync(body);
|
|
290
|
+
}
|
|
291
|
+
else if (contentEncoding === "deflate") {
|
|
292
|
+
decodedBody = zlib.inflateSync(body);
|
|
293
|
+
}
|
|
294
|
+
else if (contentEncoding === "br") {
|
|
295
|
+
decodedBody = zlib.brotliDecompressSync(body);
|
|
296
|
+
}
|
|
297
|
+
let html = decodedBody.toString("utf8");
|
|
298
|
+
// 读取用户自定义文件夹下所有 js 文件(排除 # 开头的文件)
|
|
299
|
+
const userScriptTags = scriptDir
|
|
300
|
+
? this.generateImportScripts(scriptDir)
|
|
301
|
+
: "";
|
|
302
|
+
// 始终注入内置的环境快速切换面板脚本
|
|
303
|
+
const builtInScriptTag = '<script type="module" src="/envm-inject/envm-switcher.js"></script>';
|
|
304
|
+
const allScriptTags = [userScriptTags, builtInScriptTag]
|
|
305
|
+
.filter(Boolean)
|
|
306
|
+
.join("\n");
|
|
307
|
+
html = html.replace(/<\/body>\s*<\/html>/gi, `${allScriptTags}</body></html>`);
|
|
308
|
+
let newBody = Buffer.from(html, "utf8");
|
|
309
|
+
// 若原响应为压缩内容,注入后按相同编码重新压缩
|
|
310
|
+
if (contentEncoding === "gzip" || contentEncoding === "x-gzip") {
|
|
311
|
+
newBody = zlib.gzipSync(newBody);
|
|
312
|
+
}
|
|
313
|
+
else if (contentEncoding === "deflate") {
|
|
314
|
+
newBody = zlib.deflateSync(newBody);
|
|
315
|
+
}
|
|
316
|
+
else if (contentEncoding === "br") {
|
|
317
|
+
newBody = zlib.brotliCompressSync(newBody);
|
|
220
318
|
}
|
|
221
|
-
let html = body.toString("utf8");
|
|
222
|
-
// 读取文件夹下所有 js 文件(排除 # 开头的文件)
|
|
223
|
-
const scriptTags = this.generateImportScripts(scriptDir);
|
|
224
|
-
html = html.replace(/<\/body>\s*<\/html>/gi, `${scriptTags}</body></html>`);
|
|
225
|
-
const newBody = Buffer.from(html, "utf8");
|
|
226
319
|
res.setHeader("Content-Length", newBody.length);
|
|
227
320
|
res.end(newBody);
|
|
228
321
|
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { EventEmitter } from "events";
|
|
2
|
+
import { proxyLogger } from "../utils/logger.js";
|
|
3
|
+
import { getLogEnabled } from "./SystemSettingService.js";
|
|
4
|
+
const MAX_LOG_ENTRIES = 500;
|
|
5
|
+
/** 模块级单例 EventEmitter — PreProxyServer 直接导入使用 */
|
|
6
|
+
export const requestLogEmitter = new EventEmitter();
|
|
7
|
+
class RequestLogService {
|
|
8
|
+
constructor() {
|
|
9
|
+
this.logs = [];
|
|
10
|
+
this.logSubscribers = new Set();
|
|
11
|
+
// 监听 PreProxyServer 发出的日志事件
|
|
12
|
+
requestLogEmitter.on("log", (entry) => {
|
|
13
|
+
this.addLog(entry);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* 添加日志条目(环形缓冲区,最多保留 MAX_LOG_ENTRIES 条)
|
|
18
|
+
*/
|
|
19
|
+
addLog(entry) {
|
|
20
|
+
// 请求日志记录开关关闭(默认暂停)时不记录、不推送
|
|
21
|
+
if (!getLogEnabled()) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (this.logs.length >= MAX_LOG_ENTRIES) {
|
|
25
|
+
this.logs.shift();
|
|
26
|
+
}
|
|
27
|
+
this.logs.push(entry);
|
|
28
|
+
// 通知所有订阅者(用于 WebSocket 实时推送)
|
|
29
|
+
for (const subscriber of this.logSubscribers) {
|
|
30
|
+
try {
|
|
31
|
+
subscriber(entry);
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
proxyLogger.error(err, "日志订阅者通知失败");
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* 获取日志列表(支持 URL 模糊匹配和状态码精确过滤)
|
|
40
|
+
*/
|
|
41
|
+
getLogs(filter) {
|
|
42
|
+
let result = [...this.logs];
|
|
43
|
+
if (filter?.url) {
|
|
44
|
+
const lower = filter.url.toLowerCase();
|
|
45
|
+
result = result.filter((e) => e.url.toLowerCase().includes(lower));
|
|
46
|
+
}
|
|
47
|
+
if (filter?.statusCode !== undefined) {
|
|
48
|
+
result = result.filter((e) => e.statusCode === filter.statusCode);
|
|
49
|
+
}
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* 获取全部日志历史
|
|
54
|
+
*/
|
|
55
|
+
getAllLogs() {
|
|
56
|
+
return [...this.logs];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* 订阅新日志条目(用于 WebSocket 客户端推送)
|
|
60
|
+
* 返回取消订阅函数
|
|
61
|
+
*/
|
|
62
|
+
subscribe(callback) {
|
|
63
|
+
this.logSubscribers.add(callback);
|
|
64
|
+
return () => {
|
|
65
|
+
this.logSubscribers.delete(callback);
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export { RequestLogService };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { v4 as uuidv4 } from "uuid";
|
|
2
|
+
import { AppError } from "../utils/errors.js";
|
|
2
3
|
/**
|
|
3
4
|
* 路由规则服务类
|
|
4
5
|
* 负责处理与路由规则相关的核心业务逻辑,包括路由规则的增删改查等操作
|
|
@@ -39,7 +40,7 @@ class RouteRuleService {
|
|
|
39
40
|
* 1. 校验输入参数合法性 2. 检查目标环境是否存在 3. 生成唯一ID 4. 保存
|
|
40
41
|
* @param routeRuleItem - 待添加的路由规则信息(不含ID)
|
|
41
42
|
* @returns 新创建的路由规则
|
|
42
|
-
* @throws {
|
|
43
|
+
* @throws {AppError} 当输入参数不合法或目标环境不存在时抛出
|
|
43
44
|
*/
|
|
44
45
|
handleAdd(routeRuleItem) {
|
|
45
46
|
const { envId, pathPrefix, targetEnvId } = routeRuleItem;
|
|
@@ -47,16 +48,16 @@ class RouteRuleService {
|
|
|
47
48
|
if (targetEnvId) {
|
|
48
49
|
const targetEnv = this.envRepo.findOneById(targetEnvId);
|
|
49
50
|
if (!targetEnv) {
|
|
50
|
-
throw new
|
|
51
|
+
throw new AppError(`添加失败,目标环境【${targetEnvId}】不存在`);
|
|
51
52
|
}
|
|
52
53
|
}
|
|
53
54
|
// 目标环境不能为空
|
|
54
55
|
if (!targetEnvId) {
|
|
55
|
-
throw new
|
|
56
|
+
throw new AppError("添加失败,目标环境不能为空");
|
|
56
57
|
}
|
|
57
58
|
// 检查是否已存在相同路径前缀的规则(同一环境下)
|
|
58
59
|
if (this.routeRuleRepo.existsByEnvIdAndPathPrefix(envId, pathPrefix)) {
|
|
59
|
-
throw new
|
|
60
|
+
throw new AppError(`添加失败,该环境下已存在路径前缀【${pathPrefix}】的规则`);
|
|
60
61
|
}
|
|
61
62
|
// 生成唯一ID并组装完整路由规则信息
|
|
62
63
|
const now = new Date().toISOString();
|
|
@@ -75,33 +76,32 @@ class RouteRuleService {
|
|
|
75
76
|
* 1. 校验输入参数 2. 检查规则是否存在 3. 检查目标环境是否存在 4. 执行更新
|
|
76
77
|
* @param routeRuleItem - 包含待更新路由规则ID及字段的对象
|
|
77
78
|
* @returns 更新后的路由规则
|
|
78
|
-
* @throws {
|
|
79
|
+
* @throws {AppError} 当输入参数不合法或规则/目标环境不存在时抛出
|
|
79
80
|
*/
|
|
80
81
|
handleUpdate(routeRuleItem) {
|
|
81
82
|
const { id, targetEnvId } = routeRuleItem;
|
|
82
83
|
// 检查路由规则是否存在
|
|
83
84
|
const existingRule = this.routeRuleRepo.findOneById(id);
|
|
84
85
|
if (!existingRule) {
|
|
85
|
-
throw new
|
|
86
|
+
throw new AppError(`更新失败,路由规则【${id}】不存在`);
|
|
86
87
|
}
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
if (shouldClearTarget) {
|
|
88
|
+
// 判断是否需要清空目标环境(只有明确发送空字符串时才清空)
|
|
89
|
+
if (targetEnvId === "") {
|
|
90
90
|
// 清空目标环境
|
|
91
91
|
routeRuleItem.targetEnvId = "";
|
|
92
92
|
}
|
|
93
|
-
else if (targetEnvId !== existingRule.targetEnvId) {
|
|
93
|
+
else if (targetEnvId !== undefined && targetEnvId !== existingRule.targetEnvId) {
|
|
94
94
|
// 更新了目标环境,检查目标环境是否存在
|
|
95
95
|
const targetEnv = this.envRepo.findOneById(targetEnvId);
|
|
96
96
|
if (!targetEnv) {
|
|
97
|
-
throw new
|
|
97
|
+
throw new AppError(`更新失败,目标环境【${targetEnvId}】不存在`);
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
100
|
// 如果更新了路径前缀,检查是否与其他规则冲突
|
|
101
101
|
if (routeRuleItem.pathPrefix &&
|
|
102
102
|
routeRuleItem.pathPrefix !== existingRule.pathPrefix) {
|
|
103
103
|
if (this.routeRuleRepo.existsByEnvIdAndPathPrefix(existingRule.envId, routeRuleItem.pathPrefix)) {
|
|
104
|
-
throw new
|
|
104
|
+
throw new AppError(`更新失败,该环境下已存在路径前缀【${routeRuleItem.pathPrefix}】的规则`);
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
107
|
// 添加更新时间
|
|
@@ -115,14 +115,14 @@ class RouteRuleService {
|
|
|
115
115
|
* 删除指定路由规则
|
|
116
116
|
* 1. 校验输入参数 2. 检查规则是否存在 3. 执行删除操作
|
|
117
117
|
* @param routeRuleItem - 包含待删除路由规则ID的对象
|
|
118
|
-
* @throws {
|
|
118
|
+
* @throws {AppError} 当输入参数不合法或规则不存在时抛出
|
|
119
119
|
*/
|
|
120
120
|
handleDelete(routeRuleItem) {
|
|
121
121
|
const { id } = routeRuleItem;
|
|
122
122
|
// 检查路由规则是否存在
|
|
123
123
|
const existingRule = this.routeRuleRepo.findOneById(id);
|
|
124
124
|
if (!existingRule) {
|
|
125
|
-
throw new
|
|
125
|
+
throw new AppError(`删除失败,路由规则【${id}】不存在`);
|
|
126
126
|
}
|
|
127
127
|
// 执行删除
|
|
128
128
|
this.routeRuleRepo.delete(routeRuleItem);
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { SystemSettingRepo } from "../repositories/SystemSettingRepo.js";
|
|
2
|
+
/**
|
|
3
|
+
* 模块级内存缓存:系统设置开关的单一事实来源。
|
|
4
|
+
*
|
|
5
|
+
* - 注入资源开关默认关闭(false)
|
|
6
|
+
* - 请求日志记录开关默认暂停(false)
|
|
7
|
+
*
|
|
8
|
+
* 这些函数必须纯内存同步、不访问 getDatabase(),否则会破坏
|
|
9
|
+
* PreProxyServer 集成测试(该测试未初始化数据库)。
|
|
10
|
+
*/
|
|
11
|
+
let injectEnabled = false;
|
|
12
|
+
let logEnabled = false;
|
|
13
|
+
/**
|
|
14
|
+
* 获取注入资源开关状态(纯内存、同步,供 PreProxyServer 直接使用)
|
|
15
|
+
* @returns 是否开启注入资源
|
|
16
|
+
*/
|
|
17
|
+
export function getInjectEnabled() {
|
|
18
|
+
return injectEnabled;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* 获取请求日志记录开关状态(纯内存、同步,供 RequestLogService 直接使用)
|
|
22
|
+
* @returns 是否开启请求日志记录
|
|
23
|
+
*/
|
|
24
|
+
export function getLogEnabled() {
|
|
25
|
+
return logEnabled;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* 系统设置服务
|
|
29
|
+
* 负责系统设置的读取与更新,通过 Repository 实现持久化
|
|
30
|
+
*/
|
|
31
|
+
class SystemSettingService {
|
|
32
|
+
constructor(repo = new SystemSettingRepo()) {
|
|
33
|
+
this.repo = repo;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 获取注入资源开关状态
|
|
37
|
+
* @returns 是否开启注入资源
|
|
38
|
+
*/
|
|
39
|
+
getInjectEnabled() {
|
|
40
|
+
return injectEnabled;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* 获取请求日志记录开关状态
|
|
44
|
+
* @returns 是否开启请求日志记录
|
|
45
|
+
*/
|
|
46
|
+
getLogEnabled() {
|
|
47
|
+
return logEnabled;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* 更新注入资源开关状态
|
|
51
|
+
* @param value - 是否开启注入资源
|
|
52
|
+
*/
|
|
53
|
+
setInjectEnabled(value) {
|
|
54
|
+
injectEnabled = value;
|
|
55
|
+
this.persist();
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 更新请求日志记录开关状态
|
|
59
|
+
* @param value - 是否开启请求日志记录
|
|
60
|
+
*/
|
|
61
|
+
setLogEnabled(value) {
|
|
62
|
+
logEnabled = value;
|
|
63
|
+
this.persist();
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* 初始化:从数据库读取持久化值同步到内存缓存。
|
|
67
|
+
* 数据库就绪后调用(在 index.ts 的 startDatabase 之后)。
|
|
68
|
+
* 空库时 seed 默认记录(注入关闭、日志暂停)。
|
|
69
|
+
*/
|
|
70
|
+
init() {
|
|
71
|
+
const existing = this.repo.getGlobal();
|
|
72
|
+
if (existing) {
|
|
73
|
+
injectEnabled = existing.injectEnabled;
|
|
74
|
+
// 兼容旧数据:早期版本可能没有 logEnabled 字段
|
|
75
|
+
logEnabled = existing.logEnabled ?? false;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
injectEnabled = false;
|
|
79
|
+
logEnabled = false;
|
|
80
|
+
this.persist();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* 将当前内存状态持久化到数据库(全量写入)
|
|
85
|
+
*/
|
|
86
|
+
persist() {
|
|
87
|
+
this.repo.upsert({ id: "global", injectEnabled, logEnabled });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
export { SystemSettingService };
|
package/dist/types/index.js
CHANGED
|
@@ -3,3 +3,6 @@ export * from "./shared/DevServerItem.js";
|
|
|
3
3
|
export * from "./shared/EnvmConfig.js";
|
|
4
4
|
export * from "./shared/RouteRule.js";
|
|
5
5
|
export * from "./shared/Password.js";
|
|
6
|
+
export * from "./shared/RequestLog.js";
|
|
7
|
+
export * from "./shared/ImportExport.js";
|
|
8
|
+
export * from "./shared/SystemSetting.js";
|
|
@@ -66,3 +66,11 @@ export const EnvSortSchema = z.object({
|
|
|
66
66
|
sortOrder: z.number(),
|
|
67
67
|
})),
|
|
68
68
|
});
|
|
69
|
+
/**
|
|
70
|
+
* 环境切换Schema
|
|
71
|
+
* 用于切换环境时的参数验证
|
|
72
|
+
*/
|
|
73
|
+
export const EnvSwitchSchema = z.object({
|
|
74
|
+
currentEnvId: z.string().describe("当前环境ID"),
|
|
75
|
+
targetEnvId: z.string().describe("目标环境ID"),
|
|
76
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// ---- 导出数据子 Schema ----
|
|
3
|
+
/** 导出的开发服务器(不含 id,通过 devServerUrl 做跨安装匹配) */
|
|
4
|
+
export const ExportDevServerSchema = z.object({
|
|
5
|
+
name: z.string(),
|
|
6
|
+
devServerUrl: z.string(),
|
|
7
|
+
description: z.string().optional(),
|
|
8
|
+
});
|
|
9
|
+
/** 导出的路由规则(targetEnvId 转为 targetEnvApiBaseUrl 做跨安装引用) */
|
|
10
|
+
export const ExportRouteRuleSchema = z.object({
|
|
11
|
+
pathPrefix: z.string().min(1),
|
|
12
|
+
targetEnvApiBaseUrl: z.string().optional(),
|
|
13
|
+
description: z.string().optional(),
|
|
14
|
+
enabled: z.boolean().optional().default(true),
|
|
15
|
+
});
|
|
16
|
+
/** 导出的密码 */
|
|
17
|
+
export const ExportPasswordSchema = z.object({
|
|
18
|
+
name: z.string().min(1),
|
|
19
|
+
username: z.string().min(1),
|
|
20
|
+
password: z.string().min(1),
|
|
21
|
+
description: z.string().optional(),
|
|
22
|
+
isDefault: z.boolean().optional().default(false),
|
|
23
|
+
});
|
|
24
|
+
/** 导出的环境(包含关联的 routeRules 和 passwords) */
|
|
25
|
+
export const ExportEnvSchema = z.object({
|
|
26
|
+
apiBaseUrl: z.string(),
|
|
27
|
+
port: z.number().int().min(1).max(65535),
|
|
28
|
+
name: z.string().optional(),
|
|
29
|
+
description: z.string().optional(),
|
|
30
|
+
devServerUrl: z.string().optional(),
|
|
31
|
+
homePage: z.string().optional(),
|
|
32
|
+
routeRules: z.array(ExportRouteRuleSchema).optional().default([]),
|
|
33
|
+
passwords: z.array(ExportPasswordSchema).optional().default([]),
|
|
34
|
+
});
|
|
35
|
+
// ---- 顶层导出文件 Schema ----
|
|
36
|
+
export const EXPORT_VERSION = "1.0.0";
|
|
37
|
+
export const ExportDataSchema = z.object({
|
|
38
|
+
version: z.literal(EXPORT_VERSION),
|
|
39
|
+
exportedAt: z.string(),
|
|
40
|
+
encrypted: z.boolean().optional().default(false),
|
|
41
|
+
devServers: z.array(ExportDevServerSchema).optional().default([]),
|
|
42
|
+
envs: z.array(ExportEnvSchema),
|
|
43
|
+
});
|
|
44
|
+
// ---- 导入/导出请求 Schema ----
|
|
45
|
+
export const ExportRequestSchema = z.object({
|
|
46
|
+
/** 要导出的环境 ID 列表;为空则导出全部 */
|
|
47
|
+
envIds: z.array(z.string()).optional(),
|
|
48
|
+
/** 加密密码;提供则对 passwords 中的 password 字段做 AES 加密 */
|
|
49
|
+
encryptPassword: z.string().optional(),
|
|
50
|
+
});
|
|
51
|
+
export const ImportRequestSchema = z.object({
|
|
52
|
+
data: ExportDataSchema,
|
|
53
|
+
conflictStrategy: z.enum(["skip", "overwrite"]).optional().default("skip"),
|
|
54
|
+
decryptPassword: z.string().optional(),
|
|
55
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** 资源类型(参考 Chrome DevTools Network 面板分类) */
|
|
3
|
+
export const ResourceTypeSchema = z.enum([
|
|
4
|
+
"fetch", // Fetch/XHR
|
|
5
|
+
"document", // 文档
|
|
6
|
+
"stylesheet", // CSS
|
|
7
|
+
"script", // JS
|
|
8
|
+
"font", // 字体
|
|
9
|
+
"image", // 图片
|
|
10
|
+
"media", // 媒体
|
|
11
|
+
"manifest", // 清单
|
|
12
|
+
"websocket", // 套接字
|
|
13
|
+
"wasm", // Wasm
|
|
14
|
+
"other", // 其他
|
|
15
|
+
]);
|
|
16
|
+
/** 单条请求日志 */
|
|
17
|
+
export const RequestLogEntrySchema = z.object({
|
|
18
|
+
id: z.string().describe("唯一标识(uuid)"),
|
|
19
|
+
timestamp: z.number().describe("请求开始时间戳(ms)"),
|
|
20
|
+
method: z.string().describe("HTTP 方法(GET/POST/PUT/DELETE 等)"),
|
|
21
|
+
url: z.string().describe("请求 URL 路径"),
|
|
22
|
+
statusCode: z.number().describe("HTTP 响应状态码"),
|
|
23
|
+
duration: z.number().describe("请求耗时(ms)"),
|
|
24
|
+
matchedRule: z.string().describe("命中的路由规则 pathPrefix,或 'default'"),
|
|
25
|
+
resourceType: ResourceTypeSchema.describe("资源类型"),
|
|
26
|
+
envId: z.string().describe("所属环境 ID"),
|
|
27
|
+
envName: z.string().describe("环境名称"),
|
|
28
|
+
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* 系统设置模型Schema
|
|
4
|
+
* 全局单例设置(id 固定为 "global")。
|
|
5
|
+
*/
|
|
6
|
+
export const SystemSettingModelSchema = z.object({
|
|
7
|
+
id: z.literal("global").describe("全局设置唯一标识"),
|
|
8
|
+
injectEnabled: z.boolean().describe("是否开启注入资源功能"),
|
|
9
|
+
logEnabled: z.boolean().describe("是否开启请求日志记录"),
|
|
10
|
+
});
|
|
11
|
+
/**
|
|
12
|
+
* 更新系统设置Schema
|
|
13
|
+
* 用于更新系统设置时的参数验证(全量更新)
|
|
14
|
+
*/
|
|
15
|
+
export const SystemSettingUpdateSchema = z.object({
|
|
16
|
+
injectEnabled: z.boolean().describe("是否开启注入资源功能"),
|
|
17
|
+
logEnabled: z.boolean().describe("是否开启请求日志记录"),
|
|
18
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 包装 async Express 路由处理器,使 rejected promise 自动转发到 next()。
|
|
3
|
+
* 这样 Express 的 globalErrorHandler 可以统一捕获异步错误,无需在每个 Controller 方法中手动 try/catch。
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* router.post("/start", toDTO(EnvPrimarySchema), asyncHandler(controller.handleStartServer));
|
|
7
|
+
*/
|
|
8
|
+
export const asyncHandler = (fn) => {
|
|
9
|
+
return (req, res, next) => {
|
|
10
|
+
Promise.resolve(fn(req, res, next)).catch(next);
|
|
11
|
+
};
|
|
12
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 根据命中规则、响应 Content-Type 和请求 URL 判断资源类型。
|
|
3
|
+
*
|
|
4
|
+
* 分类参考 Chrome DevTools Network 面板:
|
|
5
|
+
* - 命中路由规则的请求视为 API 请求(Fetch/XHR)
|
|
6
|
+
* - 其余按 Content-Type 归类,URL 扩展名作为兜底
|
|
7
|
+
*
|
|
8
|
+
* @param matchedRule 命中的路由规则 pathPrefix,'default' 表示未命中
|
|
9
|
+
* @param contentType 响应头 Content-Type(可能为数组)
|
|
10
|
+
* @param url 请求 URL 路径
|
|
11
|
+
*/
|
|
12
|
+
export function classifyResourceType(matchedRule, contentType, url) {
|
|
13
|
+
// 命中路由规则 → API 请求(Fetch/XHR)
|
|
14
|
+
if (matchedRule !== "default")
|
|
15
|
+
return "fetch";
|
|
16
|
+
const ct = (Array.isArray(contentType) ? contentType[0] : contentType || "").toLowerCase();
|
|
17
|
+
const path = url.toLowerCase();
|
|
18
|
+
if (ct.includes("wasm") || path.endsWith(".wasm"))
|
|
19
|
+
return "wasm";
|
|
20
|
+
if (ct.includes("manifest+json") ||
|
|
21
|
+
path.endsWith("manifest.json") ||
|
|
22
|
+
path.endsWith(".webmanifest"))
|
|
23
|
+
return "manifest";
|
|
24
|
+
if (ct.includes("font") || /\.(woff2?|ttf|otf|eot)$/.test(path))
|
|
25
|
+
return "font";
|
|
26
|
+
if (ct.startsWith("image/") ||
|
|
27
|
+
/\.(png|jpe?g|gif|svg|webp|ico|avif)$/.test(path))
|
|
28
|
+
return "image";
|
|
29
|
+
if (ct.startsWith("video/") || ct.startsWith("audio/"))
|
|
30
|
+
return "media";
|
|
31
|
+
if (ct.includes("text/css") || path.endsWith(".css"))
|
|
32
|
+
return "stylesheet";
|
|
33
|
+
if (ct.includes("javascript") ||
|
|
34
|
+
ct.includes("ecmascript") ||
|
|
35
|
+
/\.(m?js)$/.test(path))
|
|
36
|
+
return "script";
|
|
37
|
+
if (ct.includes("text/html") ||
|
|
38
|
+
path.endsWith(".html") ||
|
|
39
|
+
path.endsWith(".htm"))
|
|
40
|
+
return "document";
|
|
41
|
+
return "other";
|
|
42
|
+
}
|