vafast 0.3.2 → 0.3.4

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.
Files changed (136) hide show
  1. package/dist/auth/token.d.ts +13 -11
  2. package/dist/auth/token.js +118 -111
  3. package/dist/auth/token.js.map +1 -0
  4. package/dist/defineRoute.d.ts +5 -2
  5. package/dist/defineRoute.js +7 -2
  6. package/dist/defineRoute.js.map +1 -0
  7. package/dist/index.d.ts +30 -14
  8. package/dist/index.js +2247 -15
  9. package/dist/index.js.map +1 -0
  10. package/dist/middleware/auth.d.ts +8 -6
  11. package/dist/middleware/auth.js +198 -99
  12. package/dist/middleware/auth.js.map +1 -0
  13. package/dist/middleware/authMiddleware.d.ts +5 -2
  14. package/dist/middleware/authMiddleware.js +55 -11
  15. package/dist/middleware/authMiddleware.js.map +1 -0
  16. package/dist/middleware/component-renderer.d.ts +4 -2
  17. package/dist/middleware/component-renderer.js +87 -80
  18. package/dist/middleware/component-renderer.js.map +1 -0
  19. package/dist/middleware/component-router.d.ts +8 -3
  20. package/dist/middleware/component-router.js +33 -39
  21. package/dist/middleware/component-router.js.map +1 -0
  22. package/dist/middleware/cors.d.ts +6 -3
  23. package/dist/middleware/cors.js +42 -29
  24. package/dist/middleware/cors.js.map +1 -0
  25. package/dist/middleware/rateLimit.d.ts +5 -3
  26. package/dist/middleware/rateLimit.js +45 -29
  27. package/dist/middleware/rateLimit.js.map +1 -0
  28. package/dist/middleware.d.ts +6 -3
  29. package/dist/middleware.js +97 -51
  30. package/dist/middleware.js.map +1 -0
  31. package/dist/monitoring/index.d.ts +11 -4
  32. package/dist/monitoring/index.js +1299 -17
  33. package/dist/monitoring/index.js.map +1 -0
  34. package/dist/monitoring/native-monitor.d.ts +12 -6
  35. package/dist/monitoring/native-monitor.js +1258 -161
  36. package/dist/monitoring/native-monitor.js.map +1 -0
  37. package/dist/monitoring/types.d.ts +8 -6
  38. package/dist/monitoring/types.js +1 -1
  39. package/dist/monitoring/types.js.map +1 -0
  40. package/dist/node-server/index.d.ts +4 -22
  41. package/dist/node-server/index.js +254 -21
  42. package/dist/node-server/index.js.map +1 -0
  43. package/dist/node-server/request.d.ts +6 -2
  44. package/dist/node-server/request.js +102 -134
  45. package/dist/node-server/request.js.map +1 -0
  46. package/dist/node-server/response.d.ts +7 -3
  47. package/dist/node-server/response.js +67 -89
  48. package/dist/node-server/response.js.map +1 -0
  49. package/dist/node-server/serve.d.ts +11 -7
  50. package/dist/node-server/serve.js +231 -82
  51. package/dist/node-server/serve.js.map +1 -0
  52. package/dist/router/index.d.ts +3 -5
  53. package/dist/router/index.js +228 -7
  54. package/dist/router/index.js.map +1 -0
  55. package/dist/router/radix-tree.d.ts +7 -4
  56. package/dist/router/radix-tree.js +186 -218
  57. package/dist/router/radix-tree.js.map +1 -0
  58. package/dist/router.d.ts +7 -3
  59. package/dist/router.js +37 -83
  60. package/dist/router.js.map +1 -0
  61. package/dist/serve.d.ts +2 -12
  62. package/dist/serve.js +237 -11
  63. package/dist/serve.js.map +1 -0
  64. package/dist/server/base-server.d.ts +5 -2
  65. package/dist/server/base-server.js +124 -135
  66. package/dist/server/base-server.js.map +1 -0
  67. package/dist/server/component-server.d.ts +9 -4
  68. package/dist/server/component-server.js +481 -139
  69. package/dist/server/component-server.js.map +1 -0
  70. package/dist/server/index.d.ts +8 -7
  71. package/dist/server/index.js +985 -11
  72. package/dist/server/index.js.map +1 -0
  73. package/dist/server/server-factory.d.ts +11 -5
  74. package/dist/server/server-factory.js +979 -67
  75. package/dist/server/server-factory.js.map +1 -0
  76. package/dist/server/server.d.ts +7 -3
  77. package/dist/server/server.js +553 -112
  78. package/dist/server/server.js.map +1 -0
  79. package/dist/types/component-route.d.ts +8 -4
  80. package/dist/types/component-route.js +1 -1
  81. package/dist/types/component-route.js.map +1 -0
  82. package/dist/types/index.d.ts +5 -5
  83. package/dist/types/index.js +21 -4
  84. package/dist/types/index.js.map +1 -0
  85. package/dist/types/route.d.ts +13 -10
  86. package/dist/types/route.js +10 -9
  87. package/dist/types/route.js.map +1 -0
  88. package/dist/types/schema.d.ts +11 -7
  89. package/dist/types/schema.js +1 -1
  90. package/dist/types/schema.js.map +1 -0
  91. package/dist/types/types.d.ts +11 -9
  92. package/dist/types/types.js +1 -1
  93. package/dist/types/types.js.map +1 -0
  94. package/dist/utils/base64url.d.ts +4 -2
  95. package/dist/utils/base64url.js +12 -9
  96. package/dist/utils/base64url.js.map +1 -0
  97. package/dist/utils/create-handler.d.ts +11 -7
  98. package/dist/utils/create-handler.js +393 -217
  99. package/dist/utils/create-handler.js.map +1 -0
  100. package/dist/utils/dependency-manager.d.ts +3 -1
  101. package/dist/utils/dependency-manager.js +67 -69
  102. package/dist/utils/dependency-manager.js.map +1 -0
  103. package/dist/utils/go-await.d.ts +3 -1
  104. package/dist/utils/go-await.js +8 -22
  105. package/dist/utils/go-await.js.map +1 -0
  106. package/dist/utils/handle.d.ts +6 -4
  107. package/dist/utils/handle.js +44 -25
  108. package/dist/utils/handle.js.map +1 -0
  109. package/dist/utils/html-renderer.d.ts +3 -1
  110. package/dist/utils/html-renderer.js +25 -24
  111. package/dist/utils/html-renderer.js.map +1 -0
  112. package/dist/utils/index.d.ts +13 -13
  113. package/dist/utils/index.js +832 -21
  114. package/dist/utils/index.js.map +1 -0
  115. package/dist/utils/parsers.d.ts +15 -13
  116. package/dist/utils/parsers.js +138 -188
  117. package/dist/utils/parsers.js.map +1 -0
  118. package/dist/utils/path-matcher.d.ts +3 -1
  119. package/dist/utils/path-matcher.js +68 -78
  120. package/dist/utils/path-matcher.js.map +1 -0
  121. package/dist/utils/request-validator.d.ts +13 -10
  122. package/dist/utils/request-validator.js +234 -84
  123. package/dist/utils/request-validator.js.map +1 -0
  124. package/dist/utils/response.d.ts +9 -7
  125. package/dist/utils/response.js +93 -102
  126. package/dist/utils/response.js.map +1 -0
  127. package/dist/utils/validators/schema-validator.d.ts +13 -9
  128. package/dist/utils/validators/schema-validator.js +228 -209
  129. package/dist/utils/validators/schema-validator.js.map +1 -0
  130. package/dist/utils/validators/schema-validators-ultra.d.ts +15 -12
  131. package/dist/utils/validators/schema-validators-ultra.js +233 -256
  132. package/dist/utils/validators/schema-validators-ultra.js.map +1 -0
  133. package/dist/utils/validators/validators.d.ts +15 -12
  134. package/dist/utils/validators/validators.js +81 -122
  135. package/dist/utils/validators/validators.js.map +1 -0
  136. package/package.json +5 -4
@@ -1,176 +1,1273 @@
1
- /**
2
- * 原生监控装饰器
3
- *
4
- * 通过装饰器模式为 Server 添加监控能力,完全不入侵原类
5
- *
6
- * @author Framework Team
7
- * @version 2.0.0
8
- * @license MIT
9
- */
10
- // 原生监控器
11
- class NativeMonitor {
12
- config;
13
- metrics = [];
14
- isEnabled = false;
15
- constructor(config = {}) {
16
- this.config = {
17
- enabled: true,
18
- console: true,
19
- slowThreshold: 1000,
20
- errorThreshold: 0.05,
21
- tags: { framework: "vafast" },
22
- ...config,
23
- };
24
- this.isEnabled = this.config.enabled ?? true;
25
- if (this.isEnabled && this.config.console) {
26
- console.log("✅ 原生监控已启用");
27
- console.log(`📊 监控配置:`, {
28
- 慢请求阈值: `${this.config.slowThreshold}ms`,
29
- 错误率阈值: `${(this.config.errorThreshold * 100).toFixed(1)}%`,
30
- 标签: this.config.tags,
31
- });
32
- }
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __esm = (fn, res) => function __init() {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+
22
+ // src/router.ts
23
+ function flattenNestedRoutes(routes) {
24
+ const flattened = [];
25
+ function processRoute(route, parentPath = "", parentMiddleware = []) {
26
+ const currentPath = normalizePath(parentPath + route.path);
27
+ const currentMiddleware = [
28
+ ...parentMiddleware,
29
+ ...route.middleware || []
30
+ ];
31
+ if ("method" in route && "handler" in route) {
32
+ flattened.push({
33
+ ...route,
34
+ fullPath: currentPath,
35
+ middlewareChain: currentMiddleware
36
+ });
37
+ } else if ("children" in route && route.children) {
38
+ for (const child of route.children) {
39
+ processRoute(child, currentPath, currentMiddleware);
40
+ }
33
41
  }
34
- // 记录监控指标
35
- recordMetrics(metrics) {
36
- if (!this.isEnabled)
37
- return;
38
- this.metrics.push(metrics);
39
- // 保持最近1000条记录
40
- if (this.metrics.length > 1000) {
41
- this.metrics = this.metrics.slice(-1000);
42
- }
43
- // 控制台输出
44
- if (this.config.console) {
45
- const status = metrics.statusCode < 400 ? "✅" : "❌";
46
- const timeColor = metrics.totalTime > this.config.slowThreshold ? "🐌" : "⚡";
47
- console.log(`${status} ${metrics.method} ${metrics.path} - ${metrics.statusCode} (${timeColor} ${metrics.totalTime.toFixed(2)}ms)`);
48
- // 慢请求警告
49
- if (metrics.totalTime > this.config.slowThreshold) {
50
- console.warn(`🐌 慢请求警告: ${metrics.path} 耗时 ${metrics.totalTime.toFixed(2)}ms`);
42
+ }
43
+ for (const route of routes) {
44
+ processRoute(route);
45
+ }
46
+ return flattened;
47
+ }
48
+ function normalizePath(path) {
49
+ let normalized = decodeURIComponent(path);
50
+ normalized = normalized.replace(/\/+/g, "/");
51
+ if (normalized === "") return "/";
52
+ if (normalized !== "/" && normalized.endsWith("/")) {
53
+ normalized = normalized.slice(0, -1);
54
+ }
55
+ return normalized;
56
+ }
57
+ var init_router = __esm({
58
+ "src/router.ts"() {
59
+ "use strict";
60
+ }
61
+ });
62
+
63
+ // src/utils/response.ts
64
+ function json(data, status = 200, headers = {}) {
65
+ const body = JSON.stringify(data);
66
+ if (Object.keys(headers).length === 0) {
67
+ return new Response(body, {
68
+ status,
69
+ headers: { "Content-Type": "application/json" }
70
+ });
71
+ }
72
+ const h = new Headers({
73
+ "Content-Type": "application/json",
74
+ ...headers
75
+ });
76
+ return new Response(body, {
77
+ status,
78
+ headers: h
79
+ });
80
+ }
81
+ function mapResponse(response) {
82
+ if (response instanceof Response) return response;
83
+ switch (response?.constructor?.name) {
84
+ case "String":
85
+ return new Response(response, { headers: TEXT_HEADERS });
86
+ case "Object":
87
+ case "Array":
88
+ return new Response(JSON.stringify(response), { headers: JSON_HEADERS });
89
+ case "Number":
90
+ case "Boolean":
91
+ return new Response(String(response), { headers: TEXT_HEADERS });
92
+ case void 0:
93
+ return new Response(null, { status: 204 });
94
+ case "ReadableStream":
95
+ return new Response(response);
96
+ case "Blob":
97
+ return new Response(response);
98
+ case "ArrayBuffer":
99
+ return new Response(response);
100
+ case "Uint8Array":
101
+ return new Response(response);
102
+ default:
103
+ if (response instanceof Promise) {
104
+ return response.then(mapResponse);
105
+ }
106
+ return new Response(JSON.stringify(response), { headers: JSON_HEADERS });
107
+ }
108
+ }
109
+ var JSON_HEADERS, TEXT_HEADERS;
110
+ var init_response = __esm({
111
+ "src/utils/response.ts"() {
112
+ "use strict";
113
+ JSON_HEADERS = { "Content-Type": "application/json" };
114
+ TEXT_HEADERS = { "Content-Type": "text/plain" };
115
+ }
116
+ });
117
+
118
+ // src/middleware.ts
119
+ function composeMiddleware(middleware, finalHandler) {
120
+ const all = [errorHandler, ...middleware];
121
+ return function composedHandler(req) {
122
+ let i = -1;
123
+ const dispatch = (index) => {
124
+ if (index <= i)
125
+ return Promise.reject(new Error("next() called multiple times"));
126
+ i = index;
127
+ if (index < all.length) {
128
+ const mw = all[index];
129
+ return Promise.resolve(mw(req, () => dispatch(index + 1)));
130
+ }
131
+ return Promise.resolve(finalHandler(req)).then(mapResponse);
132
+ };
133
+ return dispatch(0);
134
+ };
135
+ }
136
+ var VafastError, errorHandler;
137
+ var init_middleware = __esm({
138
+ "src/middleware.ts"() {
139
+ "use strict";
140
+ init_response();
141
+ VafastError = class extends Error {
142
+ status;
143
+ type;
144
+ expose;
145
+ constructor(message, options = {}) {
146
+ super(message);
147
+ this.name = "VafastError";
148
+ this.status = options.status ?? 500;
149
+ this.type = options.type ?? "internal_error";
150
+ this.expose = options.expose ?? false;
151
+ if (options.cause) this.cause = options.cause;
152
+ }
153
+ };
154
+ errorHandler = async (req, next) => {
155
+ try {
156
+ return await next();
157
+ } catch (err) {
158
+ console.error("\u672A\u5904\u7406\u7684\u9519\u8BEF:", err);
159
+ if (err instanceof VafastError) {
160
+ return json(
161
+ {
162
+ error: err.type,
163
+ message: err.expose ? err.message : "\u53D1\u751F\u4E86\u4E00\u4E2A\u9519\u8BEF"
164
+ },
165
+ err.status
166
+ );
167
+ }
168
+ return json({ error: "internal_error", message: "\u51FA\u73B0\u4E86\u4E00\u4E9B\u95EE\u9898" }, 500);
169
+ }
170
+ };
171
+ }
172
+ });
173
+
174
+ // src/server/base-server.ts
175
+ var BaseServer;
176
+ var init_base_server = __esm({
177
+ "src/server/base-server.ts"() {
178
+ "use strict";
179
+ BaseServer = class {
180
+ globalMiddleware = [];
181
+ use(mw) {
182
+ this.globalMiddleware.push(mw);
183
+ }
184
+ /**
185
+ * 打印扁平化后的路由信息,用于调试
186
+ */
187
+ logFlattenedRoutes(routes, type = "\u8DEF\u7531") {
188
+ console.log(`\u{1F680} \u6241\u5E73\u5316\u540E\u7684${type}:`);
189
+ for (const route of routes) {
190
+ const method = route.method || "GET";
191
+ const path = route.fullPath || route.path;
192
+ console.log(` ${method} ${path}`);
193
+ if (route.middlewareChain && route.middlewareChain.length > 0) {
194
+ console.log(` \u4E2D\u95F4\u4EF6\u94FE: ${route.middlewareChain.length} \u4E2A`);
195
+ }
196
+ }
197
+ console.log("");
198
+ }
199
+ /**
200
+ * 检测路由冲突
201
+ * 检查是否有路径相同但方法不同的路由,以及潜在的路径冲突
202
+ */
203
+ detectRouteConflicts(routes) {
204
+ const pathGroups = /* @__PURE__ */ new Map();
205
+ for (const route of routes) {
206
+ const path = route.fullPath || route.path;
207
+ const method = route.method || "GET";
208
+ if (!pathGroups.has(path)) {
209
+ pathGroups.set(path, []);
210
+ }
211
+ pathGroups.get(path).push({ ...route, method });
212
+ }
213
+ for (const [path, routeList] of pathGroups) {
214
+ if (routeList.length > 1) {
215
+ const methods = routeList.map((r) => r.method);
216
+ const uniqueMethods = [...new Set(methods)];
217
+ if (uniqueMethods.length === 1) {
218
+ console.warn(
219
+ `\u26A0\uFE0F \u8DEF\u7531\u51B2\u7A81: ${uniqueMethods[0]} ${path} \u5B9A\u4E49\u4E86 ${routeList.length} \u6B21`
220
+ );
221
+ routeList.forEach((route, index) => {
222
+ console.warn(` ${index + 1}. ${route.method} ${path}`);
223
+ });
224
+ } else {
225
+ console.log(`\u2139\uFE0F \u8DEF\u5F84 ${path} \u652F\u6301\u65B9\u6CD5: ${uniqueMethods.join(", ")}`);
51
226
  }
227
+ }
52
228
  }
53
- }
54
- // 获取监控状态
55
- getStatus() {
56
- if (!this.isEnabled) {
57
- return { enabled: false, message: "监控未启用" };
58
- }
59
- const totalRequests = this.metrics.length;
60
- const successfulRequests = this.metrics.filter((m) => m.statusCode < 400).length;
61
- const failedRequests = totalRequests - successfulRequests;
62
- const avgResponseTime = totalRequests > 0
63
- ? this.metrics.reduce((sum, m) => sum + m.totalTime, 0) / totalRequests
64
- : 0;
229
+ this.detectDynamicRouteConflicts(routes);
230
+ }
231
+ /**
232
+ * 检测动态路由的潜在冲突
233
+ */
234
+ detectDynamicRouteConflicts(routes) {
235
+ const dynamicRoutes = routes.filter((r) => {
236
+ const path = r.fullPath || r.path;
237
+ return path.includes(":") || path.includes("*");
238
+ });
239
+ for (let i = 0; i < dynamicRoutes.length; i++) {
240
+ for (let j = i + 1; j < dynamicRoutes.length; j++) {
241
+ const route1 = dynamicRoutes[i];
242
+ const route2 = dynamicRoutes[j];
243
+ const method1 = route1.method || "GET";
244
+ const method2 = route2.method || "GET";
245
+ if (method1 === method2) {
246
+ const path1 = route1.fullPath || route1.path;
247
+ const path2 = route2.fullPath || route2.path;
248
+ if (this.pathsMayConflict(path1, path2)) {
249
+ console.warn(
250
+ `\u26A0\uFE0F \u6F5C\u5728\u8DEF\u7531\u51B2\u7A81: ${method1} ${path1} \u53EF\u80FD\u4E0E ${path2} \u51B2\u7A81`
251
+ );
252
+ }
253
+ }
254
+ }
255
+ }
256
+ }
257
+ /**
258
+ * 判断两个路径是否可能冲突
259
+ */
260
+ pathsMayConflict(path1, path2) {
261
+ const parts1 = path1.split("/").filter(Boolean);
262
+ const parts2 = path2.split("/").filter(Boolean);
263
+ if (parts1.length !== parts2.length) return false;
264
+ for (let i = 0; i < parts1.length; i++) {
265
+ const p1 = parts1[i];
266
+ const p2 = parts2[i];
267
+ if (!p1.startsWith(":") && !p1.startsWith("*") && !p2.startsWith(":") && !p2.startsWith("*") && p1 !== p2) {
268
+ return false;
269
+ }
270
+ if (p1 === "*" && p2.startsWith(":") || p2 === "*" && p1.startsWith(":")) {
271
+ return true;
272
+ }
273
+ }
274
+ return false;
275
+ }
276
+ /**
277
+ * 路径匹配
278
+ */
279
+ matchPath(pattern, path) {
280
+ const patternParts = pattern.split("/").filter(Boolean);
281
+ const pathParts = path.split("/").filter(Boolean);
282
+ if (patternParts.length !== pathParts.length) {
283
+ return false;
284
+ }
285
+ for (let i = 0; i < patternParts.length; i++) {
286
+ if (patternParts[i] !== pathParts[i] && !patternParts[i].startsWith(":")) {
287
+ return false;
288
+ }
289
+ }
290
+ return true;
291
+ }
292
+ /**
293
+ * 提取路径参数
294
+ */
295
+ extractParams(pattern, path) {
296
+ const params = {};
297
+ const patternParts = pattern.split("/").filter(Boolean);
298
+ const pathParts = path.split("/").filter(Boolean);
299
+ for (let i = 0; i < patternParts.length; i++) {
300
+ if (patternParts[i].startsWith(":")) {
301
+ const paramName = patternParts[i].slice(1);
302
+ params[paramName] = pathParts[i];
303
+ }
304
+ }
305
+ return params;
306
+ }
307
+ };
308
+ }
309
+ });
310
+
311
+ // src/router/radix-tree.ts
312
+ var RadixRouter;
313
+ var init_radix_tree = __esm({
314
+ "src/router/radix-tree.ts"() {
315
+ "use strict";
316
+ RadixRouter = class {
317
+ root;
318
+ constructor() {
319
+ this.root = this.createNode("");
320
+ }
321
+ createNode(path) {
65
322
  return {
66
- enabled: true,
67
- totalRequests,
68
- successfulRequests,
69
- failedRequests,
70
- errorRate: totalRequests > 0 ? failedRequests / totalRequests : 0,
71
- avgResponseTime: avgResponseTime.toFixed(2) + "ms",
72
- memoryUsage: this.getMemoryUsage(),
73
- recentRequests: this.metrics.slice(-5),
323
+ path,
324
+ children: /* @__PURE__ */ Object.create(null),
325
+ handlers: /* @__PURE__ */ Object.create(null)
74
326
  };
75
- }
76
- // 获取监控指标
77
- getMetrics() {
78
- return this.metrics;
79
- }
80
- // 重置监控数据
81
- reset() {
82
- this.metrics = [];
83
- console.log("🔄 监控数据已重置");
84
- }
85
- // 获取内存使用情况
86
- getMemoryUsage() {
87
- if (typeof process !== "undefined" && process.memoryUsage) {
88
- const mem = process.memoryUsage();
89
- return {
90
- heapUsed: (mem.heapUsed / 1024 / 1024).toFixed(2) + "MB",
91
- heapTotal: (mem.heapTotal / 1024 / 1024).toFixed(2) + "MB",
92
- external: (mem.external / 1024 / 1024).toFixed(2) + "MB",
93
- };
327
+ }
328
+ /** 分割路径 */
329
+ splitPath(path) {
330
+ return path.split("/").filter(Boolean);
331
+ }
332
+ /** 编译器函数 - 用于预编译中间件链 */
333
+ compiler;
334
+ /** 设置中间件编译器 */
335
+ setCompiler(compiler) {
336
+ this.compiler = compiler;
337
+ }
338
+ /** 注册路由 */
339
+ register(method, pattern, handler, middleware = []) {
340
+ const segments = this.splitPath(pattern);
341
+ let node = this.root;
342
+ for (const segment of segments) {
343
+ const firstChar = segment[0];
344
+ if (firstChar === ":") {
345
+ if (!node.paramChild) {
346
+ node.paramChild = this.createNode(segment);
347
+ node.paramChild.paramName = segment.substring(1);
348
+ }
349
+ node = node.paramChild;
350
+ } else if (firstChar === "*") {
351
+ if (!node.wildcardChild) {
352
+ node.wildcardChild = this.createNode(segment);
353
+ node.wildcardChild.paramName = segment.length > 1 ? segment.substring(1) : "*";
354
+ }
355
+ node = node.wildcardChild;
356
+ break;
357
+ } else {
358
+ if (!node.children[segment]) {
359
+ node.children[segment] = this.createNode(segment);
360
+ }
361
+ node = node.children[segment];
362
+ }
363
+ }
364
+ const routeHandler = { handler, middleware };
365
+ if (this.compiler && middleware.length === 0) {
366
+ routeHandler.compiled = this.compiler([], handler);
367
+ }
368
+ node.handlers[method] = routeHandler;
369
+ }
370
+ /** 预编译所有路由(在添加全局中间件后调用) */
371
+ precompileAll(globalMiddleware) {
372
+ if (!this.compiler) return;
373
+ this.precompileNode(this.root, globalMiddleware);
374
+ }
375
+ precompileNode(node, globalMiddleware) {
376
+ for (const method in node.handlers) {
377
+ const routeHandler = node.handlers[method];
378
+ if (routeHandler) {
379
+ const allMiddleware = [...globalMiddleware, ...routeHandler.middleware];
380
+ routeHandler.compiled = this.compiler(
381
+ allMiddleware,
382
+ routeHandler.handler
383
+ );
384
+ }
385
+ }
386
+ for (const key in node.children) {
387
+ this.precompileNode(node.children[key], globalMiddleware);
388
+ }
389
+ if (node.paramChild) {
390
+ this.precompileNode(node.paramChild, globalMiddleware);
391
+ }
392
+ if (node.wildcardChild) {
393
+ this.precompileNode(node.wildcardChild, globalMiddleware);
394
+ }
395
+ }
396
+ /** 匹配路由 */
397
+ match(method, path) {
398
+ const segments = this.splitPath(path);
399
+ const params = /* @__PURE__ */ Object.create(null);
400
+ const node = this.matchNode(this.root, segments, 0, params);
401
+ if (!node) return null;
402
+ const routeHandler = node.handlers[method];
403
+ if (!routeHandler) return null;
404
+ return {
405
+ handler: routeHandler.handler,
406
+ middleware: routeHandler.middleware,
407
+ params,
408
+ compiled: routeHandler.compiled
409
+ };
410
+ }
411
+ /** 递归匹配节点 (优先级: 静态 > 动态参数 > 通配符) */
412
+ matchNode(node, segments, index, params) {
413
+ if (index === segments.length) {
414
+ for (const method in node.handlers) {
415
+ if (node.handlers[method]) return node;
416
+ }
417
+ return null;
418
+ }
419
+ const segment = segments[index];
420
+ const staticChild = node.children[segment];
421
+ if (staticChild) {
422
+ const result = this.matchNode(staticChild, segments, index + 1, params);
423
+ if (result) return result;
424
+ }
425
+ if (node.paramChild) {
426
+ const paramName = node.paramChild.paramName;
427
+ const oldValue = params[paramName];
428
+ params[paramName] = segment;
429
+ const result = this.matchNode(
430
+ node.paramChild,
431
+ segments,
432
+ index + 1,
433
+ params
434
+ );
435
+ if (result) return result;
436
+ if (oldValue === void 0) {
437
+ delete params[paramName];
438
+ } else {
439
+ params[paramName] = oldValue;
440
+ }
441
+ }
442
+ if (node.wildcardChild) {
443
+ params[node.wildcardChild.paramName || "*"] = segments.slice(index).join("/");
444
+ return node.wildcardChild;
445
+ }
446
+ return null;
447
+ }
448
+ /** 获取路径允许的 HTTP 方法 */
449
+ getAllowedMethods(path) {
450
+ const segments = this.splitPath(path);
451
+ const node = this.findNode(segments);
452
+ if (!node) return [];
453
+ const methods = [];
454
+ for (const method in node.handlers) {
455
+ if (node.handlers[method]) {
456
+ methods.push(method);
457
+ }
458
+ }
459
+ return methods;
460
+ }
461
+ /** 查找节点(不提取参数) */
462
+ findNode(segments) {
463
+ let node = this.root;
464
+ for (const segment of segments) {
465
+ if (node.children[segment]) {
466
+ node = node.children[segment];
467
+ } else if (node.paramChild) {
468
+ node = node.paramChild;
469
+ } else if (node.wildcardChild) {
470
+ return node.wildcardChild;
471
+ } else {
472
+ return null;
473
+ }
474
+ }
475
+ return node;
476
+ }
477
+ /** 获取所有已注册的路由 */
478
+ getRoutes() {
479
+ const routes = [];
480
+ this.collectRoutes(this.root, "", routes);
481
+ return routes;
482
+ }
483
+ collectRoutes(node, prefix, routes) {
484
+ const currentPath = prefix + (node.path ? "/" + node.path : "");
485
+ for (const method in node.handlers) {
486
+ if (node.handlers[method]) {
487
+ routes.push({ method, path: currentPath || "/" });
488
+ }
489
+ }
490
+ for (const key in node.children) {
491
+ this.collectRoutes(node.children[key], currentPath, routes);
492
+ }
493
+ if (node.paramChild) {
494
+ this.collectRoutes(node.paramChild, currentPath, routes);
495
+ }
496
+ if (node.wildcardChild) {
497
+ this.collectRoutes(node.wildcardChild, currentPath, routes);
498
+ }
499
+ }
500
+ };
501
+ }
502
+ });
503
+
504
+ // src/server/server.ts
505
+ var Server;
506
+ var init_server = __esm({
507
+ "src/server/server.ts"() {
508
+ "use strict";
509
+ init_router();
510
+ init_middleware();
511
+ init_response();
512
+ init_base_server();
513
+ init_radix_tree();
514
+ Server = class extends BaseServer {
515
+ router;
516
+ routes;
517
+ /** 是否已预编译 */
518
+ isCompiled = false;
519
+ /** 预编译时的全局中间件数量 */
520
+ compiledWithMiddlewareCount = 0;
521
+ constructor(routes = []) {
522
+ super();
523
+ this.router = new RadixRouter();
524
+ this.routes = [];
525
+ this.router.setCompiler(
526
+ (middleware, handler) => composeMiddleware(middleware, handler)
527
+ );
528
+ if (routes.length > 0) {
529
+ this.registerRoutes(routes);
94
530
  }
95
- return { message: "内存信息不可用" };
531
+ }
532
+ /**
533
+ * 预编译所有路由处理链
534
+ * 在添加所有路由和全局中间件后调用,可提升运行时性能
535
+ */
536
+ compile() {
537
+ this.router.precompileAll(this.globalMiddleware);
538
+ this.isCompiled = true;
539
+ this.compiledWithMiddlewareCount = this.globalMiddleware.length;
540
+ return this;
541
+ }
542
+ registerRoutes(routes) {
543
+ const flattened = flattenNestedRoutes(routes);
544
+ this.routes.push(...flattened);
545
+ for (const route of flattened) {
546
+ this.router.register(
547
+ route.method,
548
+ route.fullPath,
549
+ route.handler,
550
+ route.middlewareChain || []
551
+ );
552
+ }
553
+ this.detectRouteConflicts(flattened);
554
+ this.logFlattenedRoutes(flattened);
555
+ if (this.globalMiddleware.length === 0 && !this.isCompiled) {
556
+ this.compile();
557
+ }
558
+ }
559
+ /** 快速提取 pathname */
560
+ extractPathname(url) {
561
+ let start = url.indexOf("://");
562
+ start = start === -1 ? 0 : start + 3;
563
+ const pathStart = url.indexOf("/", start);
564
+ if (pathStart === -1) return "/";
565
+ let end = url.indexOf("?", pathStart);
566
+ if (end === -1) end = url.indexOf("#", pathStart);
567
+ if (end === -1) end = url.length;
568
+ return url.substring(pathStart, end) || "/";
569
+ }
570
+ /** 处理请求 */
571
+ fetch = async (req) => {
572
+ const pathname = this.extractPathname(req.url);
573
+ const method = req.method;
574
+ const match = this.router.match(method, pathname);
575
+ if (match) {
576
+ req.params = match.params;
577
+ if (match.compiled && this.globalMiddleware.length === this.compiledWithMiddlewareCount) {
578
+ return match.compiled(req);
579
+ }
580
+ const allMiddleware = [...this.globalMiddleware, ...match.middleware];
581
+ const handler = composeMiddleware(allMiddleware, match.handler);
582
+ return handler(req);
583
+ }
584
+ const allowedMethods = this.router.getAllowedMethods(pathname);
585
+ if (allowedMethods.length > 0) {
586
+ return json(
587
+ {
588
+ success: false,
589
+ error: "Method Not Allowed",
590
+ message: `Method ${method} not allowed for this endpoint`,
591
+ allowedMethods
592
+ },
593
+ 405,
594
+ { Allow: allowedMethods.join(", ") }
595
+ );
596
+ }
597
+ return json({ success: false, error: "Not Found" }, 404);
598
+ };
599
+ addRoute(route) {
600
+ const flattenedRoute = {
601
+ ...route,
602
+ fullPath: route.path,
603
+ middlewareChain: route.middleware || []
604
+ };
605
+ this.routes.push(flattenedRoute);
606
+ this.router.register(
607
+ route.method,
608
+ route.path,
609
+ route.handler,
610
+ route.middleware || []
611
+ );
612
+ }
613
+ addRoutes(routes) {
614
+ this.registerRoutes(routes);
615
+ }
616
+ getRoutes() {
617
+ return this.router.getRoutes();
618
+ }
619
+ };
620
+ }
621
+ });
622
+
623
+ // src/middleware/component-router.ts
624
+ function flattenComponentRoutes(routes) {
625
+ const flattened = [];
626
+ function processRoute(route, parentPath = "", parentMiddleware = []) {
627
+ const currentPath = parentPath + route.path;
628
+ const currentMiddleware = [
629
+ ...parentMiddleware,
630
+ ...route.middleware || []
631
+ ];
632
+ if ("component" in route) {
633
+ flattened.push({
634
+ ...route,
635
+ fullPath: currentPath,
636
+ middlewareChain: currentMiddleware
637
+ });
638
+ } else if ("children" in route && route.children) {
639
+ for (const child of route.children) {
640
+ processRoute(child, currentPath, currentMiddleware);
641
+ }
96
642
  }
643
+ }
644
+ for (const route of routes) {
645
+ processRoute(route);
646
+ }
647
+ return flattened;
97
648
  }
98
- // 纯函数:为 Server 添加监控能力
99
- export function withMonitoring(server, config = {}) {
100
- const monitor = new NativeMonitor(config);
101
- // 保存原始的 fetch 方法
102
- const originalFetch = server.fetch.bind(server);
103
- // 创建带监控的 fetch 方法
104
- const monitoredFetch = async (req) => {
105
- const startTime = performance.now();
106
- const requestId = `req_${Date.now()}_${Math.random()
107
- .toString(36)
108
- .substr(2, 9)}`;
109
- const { pathname } = new URL(req.url);
649
+ var init_component_router = __esm({
650
+ "src/middleware/component-router.ts"() {
651
+ "use strict";
652
+ }
653
+ });
654
+
655
+ // src/utils/path-matcher.ts
656
+ var PathMatcher;
657
+ var init_path_matcher = __esm({
658
+ "src/utils/path-matcher.ts"() {
659
+ "use strict";
660
+ PathMatcher = class {
661
+ /**
662
+ * 路径匹配
663
+ */
664
+ static matchPath(pattern, path) {
665
+ const patternParts = pattern.split("/").filter(Boolean);
666
+ const pathParts = path.split("/").filter(Boolean);
667
+ if (patternParts.length !== pathParts.length) {
668
+ return false;
669
+ }
670
+ for (let i = 0; i < patternParts.length; i++) {
671
+ if (patternParts[i] !== pathParts[i] && !patternParts[i].startsWith(":")) {
672
+ return false;
673
+ }
674
+ }
675
+ return true;
676
+ }
677
+ /**
678
+ * 提取路径参数
679
+ */
680
+ static extractParams(pattern, path) {
681
+ const params = {};
682
+ const patternParts = pattern.split("/").filter(Boolean);
683
+ const pathParts = path.split("/").filter(Boolean);
684
+ for (let i = 0; i < patternParts.length; i++) {
685
+ if (patternParts[i].startsWith(":")) {
686
+ const paramName = patternParts[i].slice(1);
687
+ params[paramName] = pathParts[i];
688
+ }
689
+ }
690
+ return params;
691
+ }
692
+ /**
693
+ * 计算路径特异性分数
694
+ * 用于路由排序:静态 > 动态(:param) > 通配符(*)
695
+ */
696
+ static calculatePathScore(path) {
697
+ const parts = path.split("/").filter(Boolean);
698
+ let score = 0;
699
+ for (const p of parts) {
700
+ if (p === "*")
701
+ score += 1;
702
+ else if (p.startsWith(":"))
703
+ score += 2;
704
+ else score += 3;
705
+ }
706
+ return score * 10 + parts.length;
707
+ }
708
+ /**
709
+ * 判断两个路径是否可能冲突
710
+ */
711
+ static pathsMayConflict(path1, path2) {
712
+ const parts1 = path1.split("/").filter(Boolean);
713
+ const parts2 = path2.split("/").filter(Boolean);
714
+ if (parts1.length !== parts2.length) return false;
715
+ for (let i = 0; i < parts1.length; i++) {
716
+ const p1 = parts1[i];
717
+ const p2 = parts2[i];
718
+ if (!p1.startsWith(":") && !p1.startsWith("*") && !p2.startsWith(":") && !p2.startsWith("*") && p1 !== p2) {
719
+ return false;
720
+ }
721
+ if (p1 === "*" && p2.startsWith(":") || p2 === "*" && p1.startsWith(":")) {
722
+ return true;
723
+ }
724
+ }
725
+ return false;
726
+ }
727
+ };
728
+ }
729
+ });
730
+
731
+ // src/utils/html-renderer.ts
732
+ var HtmlRenderer;
733
+ var init_html_renderer = __esm({
734
+ "src/utils/html-renderer.ts"() {
735
+ "use strict";
736
+ HtmlRenderer = class {
737
+ /**
738
+ * 生成基础HTML模板
739
+ */
740
+ static generateBaseHtml(content, context, clientScriptPath = "/client.js") {
741
+ return `
742
+ <!doctype html>
743
+ <html>
744
+ <head>
745
+ <meta charset="utf-8">
746
+ <title>Vafast SSR App</title>
747
+ <meta name="viewport" content="width=device-width, initial-scale=1">
748
+ </head>
749
+ <body>
750
+ <div id="app">${content}</div>
751
+ <script>
752
+ window.__ROUTE_INFO__ = {
753
+ params: ${JSON.stringify(context.params || {})},
754
+ query: ${JSON.stringify(context.query || {})},
755
+ pathname: '${context.pathname}'
756
+ };
757
+ </script>
758
+ <script type="module" src="${clientScriptPath}"></script>
759
+ </body>
760
+ </html>
761
+ `;
762
+ }
763
+ /**
764
+ * 生成Vue组件HTML
765
+ */
766
+ static generateVueHtml(content, context, clientScriptPath = "/client.js") {
767
+ return this.generateBaseHtml(content, context, clientScriptPath);
768
+ }
769
+ /**
770
+ * 生成React组件HTML
771
+ */
772
+ static generateReactHtml(content, context, clientScriptPath = "/client.js") {
773
+ return `
774
+ <!doctype html>
775
+ <html>
776
+ <head>
777
+ <meta charset="utf-8">
778
+ <title>Vafast SSR App</title>
779
+ <meta name="viewport" content="width=device-width, initial-scale=1">
780
+ </head>
781
+ <body>
782
+ <div id="root">${content}</div>
783
+ <script>
784
+ window.__ROUTE_INFO__ = {
785
+ params: ${JSON.stringify(context.params || {})},
786
+ query: ${JSON.stringify(context.query || {})},
787
+ pathname: '${context.pathname}'
788
+ };
789
+ </script>
790
+ <script type="module" src="${clientScriptPath}"></script>
791
+ </body>
792
+ </html>
793
+ `;
794
+ }
795
+ };
796
+ }
797
+ });
798
+
799
+ // src/utils/dependency-manager.ts
800
+ var DependencyManager;
801
+ var init_dependency_manager = __esm({
802
+ "src/utils/dependency-manager.ts"() {
803
+ "use strict";
804
+ DependencyManager = class {
805
+ dependencyCache = /* @__PURE__ */ new Map();
806
+ /**
807
+ * 按需获取框架依赖
808
+ */
809
+ async getFrameworkDeps(framework) {
810
+ if (this.dependencyCache.has(framework)) {
811
+ return this.dependencyCache.get(framework);
812
+ }
813
+ console.log(`\u{1F4E6} \u6309\u9700\u52A0\u8F7D ${framework} \u4F9D\u8D56...`);
814
+ try {
815
+ let deps;
816
+ switch (framework) {
817
+ case "vue":
818
+ deps = await Promise.all([
819
+ import("vue"),
820
+ import("@vue/server-renderer")
821
+ ]);
822
+ break;
823
+ case "react":
824
+ deps = await Promise.all([
825
+ import("react"),
826
+ import("react-dom/server")
827
+ ]);
828
+ break;
829
+ default:
830
+ throw new Error(`\u4E0D\u652F\u6301\u7684\u6846\u67B6: ${framework}`);
831
+ }
832
+ this.dependencyCache.set(framework, deps);
833
+ console.log(`\u2705 ${framework} \u4F9D\u8D56\u52A0\u8F7D\u5B8C\u6210`);
834
+ return deps;
835
+ } catch (error) {
836
+ console.error(`\u274C ${framework} \u4F9D\u8D56\u52A0\u8F7D\u5931\u8D25:`, error);
837
+ throw error;
838
+ }
839
+ }
840
+ /**
841
+ * 检测组件类型
842
+ */
843
+ detectComponentType(component) {
844
+ if (component.render && typeof component.render === "function") {
845
+ return "vue";
846
+ }
847
+ if (component.$$typeof) {
848
+ return "react";
849
+ }
850
+ return "vue";
851
+ }
852
+ /**
853
+ * 清除缓存
854
+ */
855
+ clearCache() {
856
+ this.dependencyCache.clear();
857
+ console.log("\u{1F9F9} \u4F9D\u8D56\u7F13\u5B58\u5DF2\u6E05\u9664");
858
+ }
859
+ /**
860
+ * 获取缓存状态
861
+ */
862
+ getCacheStatus() {
863
+ const status = {};
864
+ for (const [framework] of this.dependencyCache) {
865
+ status[framework] = true;
866
+ }
867
+ return status;
868
+ }
869
+ };
870
+ }
871
+ });
872
+
873
+ // src/server/component-server.ts
874
+ var ComponentServer;
875
+ var init_component_server = __esm({
876
+ "src/server/component-server.ts"() {
877
+ "use strict";
878
+ init_component_router();
879
+ init_base_server();
880
+ init_path_matcher();
881
+ init_html_renderer();
882
+ init_dependency_manager();
883
+ ComponentServer = class extends BaseServer {
884
+ routes;
885
+ dependencyManager;
886
+ constructor(routes) {
887
+ super();
888
+ this.routes = flattenComponentRoutes(routes);
889
+ this.dependencyManager = new DependencyManager();
890
+ this.detectRouteConflicts(this.routes);
891
+ this.logFlattenedRoutes(this.routes, "\u7EC4\u4EF6\u8DEF\u7531");
892
+ console.log("\u{1F680} \u4F9D\u8D56\u6309\u9700\u52A0\u8F7D\uFF0C\u670D\u52A1\u5668\u542F\u52A8\u5B8C\u6210");
893
+ }
894
+ /**
895
+ * 处理请求
896
+ */
897
+ async fetch(req) {
898
+ const url = new URL(req.url);
899
+ const pathname = url.pathname;
110
900
  const method = req.method;
901
+ if (method !== "GET") {
902
+ return new Response("Method Not Allowed", { status: 405 });
903
+ }
904
+ let matchedRoute = null;
905
+ for (const route of this.routes) {
906
+ if (PathMatcher.matchPath(route.fullPath, pathname)) {
907
+ matchedRoute = route;
908
+ break;
909
+ }
910
+ }
911
+ if (!matchedRoute) {
912
+ return new Response("Not Found", { status: 404 });
913
+ }
914
+ try {
915
+ const context = {
916
+ req,
917
+ params: PathMatcher.extractParams(matchedRoute.fullPath, pathname),
918
+ query: Object.fromEntries(url.searchParams),
919
+ pathname
920
+ };
921
+ return await this.executeMiddlewareChain(
922
+ matchedRoute.middlewareChain,
923
+ context,
924
+ matchedRoute.component
925
+ );
926
+ } catch (error) {
927
+ console.error("\u7EC4\u4EF6\u6E32\u67D3\u5931\u8D25:", error);
928
+ return new Response("Internal Server Error", { status: 500 });
929
+ }
930
+ }
931
+ /**
932
+ * 执行中间件链
933
+ */
934
+ async executeMiddlewareChain(middlewareChain, context, componentImport) {
935
+ const renderComponent = async () => {
936
+ const componentModule = await componentImport();
937
+ const component = componentModule.default || componentModule;
938
+ const componentType = this.dependencyManager.detectComponentType(component);
939
+ const deps = await this.dependencyManager.getFrameworkDeps(componentType);
940
+ if (componentType === "vue") {
941
+ return await this.renderVueComponent(component, context, deps);
942
+ } else if (componentType === "react") {
943
+ return await this.renderReactComponent(component, context, deps);
944
+ } else {
945
+ throw new Error(`\u4E0D\u652F\u6301\u7684\u7EC4\u4EF6\u7C7B\u578B: ${componentType}`);
946
+ }
947
+ };
948
+ let index = 0;
949
+ const next = async () => {
950
+ if (index >= middlewareChain.length) {
951
+ return await renderComponent();
952
+ }
953
+ const middleware = middlewareChain[index++];
954
+ return await middleware(context.req, next);
955
+ };
956
+ return await next();
957
+ }
958
+ /**
959
+ * 渲染 Vue 组件
960
+ */
961
+ async renderVueComponent(component, context, deps) {
962
+ try {
963
+ const [vue, renderer] = deps;
964
+ const app = vue.createSSRApp(component);
965
+ app.provide("routeInfo", {
966
+ params: context.params || {},
967
+ query: context.query || {},
968
+ pathname: context.pathname
969
+ });
970
+ const html = await renderer.renderToString(app);
971
+ const fullHtml = HtmlRenderer.generateVueHtml(html, context);
972
+ return new Response(fullHtml, {
973
+ headers: { "Content-Type": "text/html; charset=utf-8" }
974
+ });
975
+ } catch (error) {
976
+ console.error("Vue \u7EC4\u4EF6\u6E32\u67D3\u5931\u8D25:", error);
977
+ return new Response("Vue Component Render Error", { status: 500 });
978
+ }
979
+ }
980
+ /**
981
+ * 渲染 React 组件
982
+ */
983
+ async renderReactComponent(component, context, deps) {
111
984
  try {
112
- // 调用原始 fetch
113
- const response = await originalFetch(req);
114
- // 记录监控指标
115
- const totalTime = performance.now() - startTime;
116
- monitor.recordMetrics({
117
- requestId,
118
- method,
119
- path: pathname,
120
- statusCode: response.status,
121
- totalTime,
122
- timestamp: Date.now(),
123
- memoryUsage: (() => {
124
- if (typeof process !== "undefined" && process.memoryUsage) {
125
- const mem = process.memoryUsage();
126
- return {
127
- heapUsed: mem.heapUsed,
128
- heapTotal: mem.heapTotal,
129
- };
130
- }
131
- return { heapUsed: 0, heapTotal: 0 };
132
- })(),
133
- });
134
- return response;
135
- }
136
- catch (error) {
137
- // 记录错误监控指标
138
- const totalTime = performance.now() - startTime;
139
- monitor.recordMetrics({
140
- requestId,
141
- method,
142
- path: pathname,
143
- statusCode: 500,
144
- totalTime,
145
- timestamp: Date.now(),
146
- memoryUsage: (() => {
147
- if (typeof process !== "undefined" && process.memoryUsage) {
148
- const mem = process.memoryUsage();
149
- return {
150
- heapUsed: mem.heapUsed,
151
- heapTotal: mem.heapTotal,
152
- };
153
- }
154
- return { heapUsed: 0, heapTotal: 0 };
155
- })(),
156
- });
157
- throw error;
985
+ const [react, renderer] = deps;
986
+ const content = react.createElement(component, {
987
+ req: context.req,
988
+ params: context.params || {},
989
+ query: context.query || {}
990
+ });
991
+ const html = renderer.renderToString(content);
992
+ const fullHtml = HtmlRenderer.generateReactHtml(html, context);
993
+ return new Response(fullHtml, {
994
+ headers: { "Content-Type": "text/html; charset=utf-8" }
995
+ });
996
+ } catch (error) {
997
+ console.error("React \u7EC4\u4EF6\u6E32\u67D3\u5931\u8D25:", error);
998
+ return new Response("React Component Render Error", { status: 500 });
999
+ }
1000
+ }
1001
+ /**
1002
+ * 获取依赖管理器(用于外部访问)
1003
+ */
1004
+ getDependencyManager() {
1005
+ return this.dependencyManager;
1006
+ }
1007
+ };
1008
+ }
1009
+ });
1010
+
1011
+ // src/server/server-factory.ts
1012
+ var ServerFactory;
1013
+ var init_server_factory = __esm({
1014
+ "src/server/server-factory.ts"() {
1015
+ "use strict";
1016
+ init_server2();
1017
+ init_component_server();
1018
+ ServerFactory = class {
1019
+ servers = /* @__PURE__ */ new Map();
1020
+ /**
1021
+ * 创建标准REST API服务器
1022
+ */
1023
+ createRestServer(routes) {
1024
+ const server = new Server(routes);
1025
+ this.servers.set("rest", server);
1026
+ return server;
1027
+ }
1028
+ /**
1029
+ * 创建组件服务器
1030
+ */
1031
+ createComponentServer(routes) {
1032
+ const server = new ComponentServer(routes);
1033
+ this.servers.set("component", server);
1034
+ return server;
1035
+ }
1036
+ /**
1037
+ * 获取指定类型的服务器
1038
+ */
1039
+ getServer(type) {
1040
+ return this.servers.get(type);
1041
+ }
1042
+ /**
1043
+ * 获取所有服务器
1044
+ */
1045
+ getAllServers() {
1046
+ return this.servers;
1047
+ }
1048
+ /**
1049
+ * 移除指定类型的服务器
1050
+ */
1051
+ removeServer(type) {
1052
+ return this.servers.delete(type);
1053
+ }
1054
+ /**
1055
+ * 清除所有服务器
1056
+ */
1057
+ clearServers() {
1058
+ this.servers.clear();
1059
+ }
1060
+ /**
1061
+ * 获取服务器状态信息
1062
+ */
1063
+ getServerStatus() {
1064
+ const status = {};
1065
+ for (const [name, server] of this.servers) {
1066
+ if (server instanceof Server) {
1067
+ status[name] = {
1068
+ type: "REST API",
1069
+ routes: server.routes?.length || 0
1070
+ };
1071
+ } else if (server instanceof ComponentServer) {
1072
+ status[name] = {
1073
+ type: "Component",
1074
+ routes: server.routes?.length || 0
1075
+ };
1076
+ }
158
1077
  }
1078
+ return status;
1079
+ }
159
1080
  };
160
- // 创建带监控的 Server 对象
161
- const monitoredServer = {
162
- ...server,
163
- fetch: monitoredFetch,
164
- // 监控方法
165
- getMonitoringStatus: () => monitor.getStatus(),
166
- getMonitoringMetrics: () => monitor.getMetrics(),
167
- resetMonitoring: () => monitor.reset(),
1081
+ }
1082
+ });
1083
+
1084
+ // src/server/index.ts
1085
+ var server_exports = {};
1086
+ __export(server_exports, {
1087
+ BaseServer: () => BaseServer,
1088
+ ComponentServer: () => ComponentServer,
1089
+ Server: () => Server,
1090
+ ServerFactory: () => ServerFactory
1091
+ });
1092
+ var init_server2 = __esm({
1093
+ "src/server/index.ts"() {
1094
+ "use strict";
1095
+ init_server();
1096
+ init_component_server();
1097
+ init_server_factory();
1098
+ init_base_server();
1099
+ }
1100
+ });
1101
+
1102
+ // src/monitoring/native-monitor.ts
1103
+ var NativeMonitor = class {
1104
+ config;
1105
+ metrics = [];
1106
+ isEnabled = false;
1107
+ constructor(config = {}) {
1108
+ this.config = {
1109
+ enabled: true,
1110
+ console: true,
1111
+ slowThreshold: 1e3,
1112
+ errorThreshold: 0.05,
1113
+ tags: { framework: "vafast" },
1114
+ ...config
168
1115
  };
169
- return monitoredServer;
1116
+ this.isEnabled = this.config.enabled ?? true;
1117
+ if (this.isEnabled && this.config.console) {
1118
+ console.log("\u2705 \u539F\u751F\u76D1\u63A7\u5DF2\u542F\u7528");
1119
+ console.log(`\u{1F4CA} \u76D1\u63A7\u914D\u7F6E:`, {
1120
+ \u6162\u8BF7\u6C42\u9608\u503C: `${this.config.slowThreshold}ms`,
1121
+ \u9519\u8BEF\u7387\u9608\u503C: `${(this.config.errorThreshold * 100).toFixed(1)}%`,
1122
+ \u6807\u7B7E: this.config.tags
1123
+ });
1124
+ }
1125
+ }
1126
+ // 记录监控指标
1127
+ recordMetrics(metrics) {
1128
+ if (!this.isEnabled) return;
1129
+ this.metrics.push(metrics);
1130
+ if (this.metrics.length > 1e3) {
1131
+ this.metrics = this.metrics.slice(-1e3);
1132
+ }
1133
+ if (this.config.console) {
1134
+ const status = metrics.statusCode < 400 ? "\u2705" : "\u274C";
1135
+ const timeColor = metrics.totalTime > this.config.slowThreshold ? "\u{1F40C}" : "\u26A1";
1136
+ console.log(
1137
+ `${status} ${metrics.method} ${metrics.path} - ${metrics.statusCode} (${timeColor} ${metrics.totalTime.toFixed(2)}ms)`
1138
+ );
1139
+ if (metrics.totalTime > this.config.slowThreshold) {
1140
+ console.warn(
1141
+ `\u{1F40C} \u6162\u8BF7\u6C42\u8B66\u544A: ${metrics.path} \u8017\u65F6 ${metrics.totalTime.toFixed(
1142
+ 2
1143
+ )}ms`
1144
+ );
1145
+ }
1146
+ }
1147
+ }
1148
+ // 获取监控状态
1149
+ getStatus() {
1150
+ if (!this.isEnabled) {
1151
+ return { enabled: false, message: "\u76D1\u63A7\u672A\u542F\u7528" };
1152
+ }
1153
+ const totalRequests = this.metrics.length;
1154
+ const successfulRequests = this.metrics.filter(
1155
+ (m) => m.statusCode < 400
1156
+ ).length;
1157
+ const failedRequests = totalRequests - successfulRequests;
1158
+ const avgResponseTime = totalRequests > 0 ? this.metrics.reduce((sum, m) => sum + m.totalTime, 0) / totalRequests : 0;
1159
+ return {
1160
+ enabled: true,
1161
+ totalRequests,
1162
+ successfulRequests,
1163
+ failedRequests,
1164
+ errorRate: totalRequests > 0 ? failedRequests / totalRequests : 0,
1165
+ avgResponseTime: avgResponseTime.toFixed(2) + "ms",
1166
+ memoryUsage: this.getMemoryUsage(),
1167
+ recentRequests: this.metrics.slice(-5)
1168
+ };
1169
+ }
1170
+ // 获取监控指标
1171
+ getMetrics() {
1172
+ return this.metrics;
1173
+ }
1174
+ // 重置监控数据
1175
+ reset() {
1176
+ this.metrics = [];
1177
+ console.log("\u{1F504} \u76D1\u63A7\u6570\u636E\u5DF2\u91CD\u7F6E");
1178
+ }
1179
+ // 获取内存使用情况
1180
+ getMemoryUsage() {
1181
+ if (typeof process !== "undefined" && process.memoryUsage) {
1182
+ const mem = process.memoryUsage();
1183
+ return {
1184
+ heapUsed: (mem.heapUsed / 1024 / 1024).toFixed(2) + "MB",
1185
+ heapTotal: (mem.heapTotal / 1024 / 1024).toFixed(2) + "MB",
1186
+ external: (mem.external / 1024 / 1024).toFixed(2) + "MB"
1187
+ };
1188
+ }
1189
+ return { message: "\u5185\u5B58\u4FE1\u606F\u4E0D\u53EF\u7528" };
1190
+ }
1191
+ };
1192
+ function withMonitoring(server, config = {}) {
1193
+ const monitor = new NativeMonitor(config);
1194
+ const originalFetch = server.fetch.bind(server);
1195
+ const monitoredFetch = async (req) => {
1196
+ const startTime = performance.now();
1197
+ const requestId = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1198
+ const { pathname } = new URL(req.url);
1199
+ const method = req.method;
1200
+ try {
1201
+ const response = await originalFetch(req);
1202
+ const totalTime = performance.now() - startTime;
1203
+ monitor.recordMetrics({
1204
+ requestId,
1205
+ method,
1206
+ path: pathname,
1207
+ statusCode: response.status,
1208
+ totalTime,
1209
+ timestamp: Date.now(),
1210
+ memoryUsage: (() => {
1211
+ if (typeof process !== "undefined" && process.memoryUsage) {
1212
+ const mem = process.memoryUsage();
1213
+ return {
1214
+ heapUsed: mem.heapUsed,
1215
+ heapTotal: mem.heapTotal
1216
+ };
1217
+ }
1218
+ return { heapUsed: 0, heapTotal: 0 };
1219
+ })()
1220
+ });
1221
+ return response;
1222
+ } catch (error) {
1223
+ const totalTime = performance.now() - startTime;
1224
+ monitor.recordMetrics({
1225
+ requestId,
1226
+ method,
1227
+ path: pathname,
1228
+ statusCode: 500,
1229
+ totalTime,
1230
+ timestamp: Date.now(),
1231
+ memoryUsage: (() => {
1232
+ if (typeof process !== "undefined" && process.memoryUsage) {
1233
+ const mem = process.memoryUsage();
1234
+ return {
1235
+ heapUsed: mem.heapUsed,
1236
+ heapTotal: mem.heapTotal
1237
+ };
1238
+ }
1239
+ return { heapUsed: 0, heapTotal: 0 };
1240
+ })()
1241
+ });
1242
+ throw error;
1243
+ }
1244
+ };
1245
+ const monitoredServer = {
1246
+ ...server,
1247
+ fetch: monitoredFetch,
1248
+ // 监控方法
1249
+ getMonitoringStatus: () => monitor.getStatus(),
1250
+ getMonitoringMetrics: () => monitor.getMetrics(),
1251
+ resetMonitoring: () => monitor.reset()
1252
+ };
1253
+ return monitoredServer;
170
1254
  }
171
- // 便捷函数:创建带监控的 Server
172
- export function createMonitoredServer(routes, config) {
173
- const { Server } = require("../server");
174
- const server = new Server(routes);
175
- return withMonitoring(server, config);
1255
+ function createMonitoredServer(routes, config) {
1256
+ const { Server: Server2 } = (init_server2(), __toCommonJS(server_exports));
1257
+ const server = new Server2(routes);
1258
+ return withMonitoring(server, config);
176
1259
  }
1260
+ export {
1261
+ createMonitoredServer,
1262
+ withMonitoring
1263
+ };
1264
+ /**
1265
+ * 原生监控装饰器
1266
+ *
1267
+ * 通过装饰器模式为 Server 添加监控能力,完全不入侵原类
1268
+ *
1269
+ * @author Framework Team
1270
+ * @version 2.0.0
1271
+ * @license MIT
1272
+ */
1273
+ //# sourceMappingURL=native-monitor.js.map