@lark-apaas/devtool-kits 1.2.17-alpha.17 → 1.2.17-alpha.18

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/README.md CHANGED
@@ -92,6 +92,17 @@ import {
92
92
  } from '@apaas/fullstack-toolkits';
93
93
  ```
94
94
 
95
+ ### 兼容工具函数 (Compat)
96
+ ```typescript
97
+ import {
98
+ sendJson, // 发送 JSON 响应(兼容 Express/Connect)
99
+ sendError, // 发送错误响应
100
+ sendSuccess, // 发送成功响应
101
+ getQuery, // 获取所有查询参数
102
+ getQueryParam, // 获取单个查询参数
103
+ } from '@apaas/fullstack-toolkits';
104
+ ```
105
+
95
106
  ### 类型定义 (Types)
96
107
  ```typescript
97
108
  import type {
@@ -171,6 +182,38 @@ export default {
171
182
  - 全局中间件应放在路由中间件之前
172
183
  - 路由中间件仅处理匹配其挂载路径的请求
173
184
 
185
+ ### Vite/Connect 兼容性
186
+
187
+ 本工具包原生支持 Vite 开发服务器。`registerMiddlewares` 会自动检测 Vite/Connect 环境,并添加必要的 Express API 兼容层:
188
+
189
+ - `res.status()` - 设置响应状态码
190
+ - `res.json()` - 发送 JSON 响应
191
+ - `res.send()` - 发送响应
192
+ - `req.query` - 解析后的查询参数
193
+
194
+ 这意味着您可以直接在 Vite 中使用本工具包,无需额外配置。
195
+
196
+ **兼容工具函数(可选):**
197
+
198
+ 如果您正在编写自定义中间件并希望同时支持 Express 和 Vite,可以使用导出的兼容工具函数:
199
+
200
+ ```typescript
201
+ import { sendJson, sendError, sendSuccess, getQuery, getQueryParam } from '@lark-apaas/devtool-kits';
202
+
203
+ // 发送 JSON 响应(自动检测 Express/Connect)
204
+ sendJson(res, { data: 'value' }, 200);
205
+
206
+ // 发送错误响应
207
+ sendError(res, 'Not found', error, 404);
208
+
209
+ // 发送成功响应
210
+ sendSuccess(res, { id: 123 });
211
+
212
+ // 获取查询参数(自动解析 URL 或使用 req.query)
213
+ const query = getQuery(req);
214
+ const page = getQueryParam(req, 'page');
215
+ ```
216
+
174
217
  ## 中间件详细说明
175
218
  ### Dev Logs 中间件
176
219
 
package/dist/index.cjs CHANGED
@@ -31,15 +31,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  // src/index.ts
32
32
  var index_exports = {};
33
33
  __export(index_exports, {
34
- createApiRoutesMiddleware: () => createApiRoutesMiddleware,
35
34
  createCollectLogsMiddleware: () => createCollectLogsMiddleware,
36
35
  createDevLogsMiddleware: () => createDevLogsMiddleware,
37
36
  createOpenapiMiddleware: () => createOpenapiMiddleware,
37
+ getQuery: () => getQuery,
38
+ getQueryParam: () => getQueryParam,
38
39
  handleDevProxyError: () => handleDevProxyError,
39
40
  normalizeBasePath: () => normalizeBasePath,
40
41
  parseAndGenerateNestResourceTemplate: () => parseAndGenerateNestResourceTemplate,
41
42
  postprocessDrizzleSchema: () => postprocessDrizzleSchema,
42
- registerMiddlewares: () => registerMiddlewares
43
+ registerMiddlewares: () => registerMiddlewares,
44
+ sendError: () => sendError,
45
+ sendJson: () => sendJson,
46
+ sendSuccess: () => sendSuccess
43
47
  });
44
48
  module.exports = __toCommonJS(index_exports);
45
49
 
@@ -1647,7 +1651,7 @@ function createOpenapiRouter(options, context) {
1647
1651
  const { openapiFilePath, enableEnhancement, serverDir } = options;
1648
1652
  const router = import_express.default.Router();
1649
1653
  const handler = createOpenapiHandler(openapiFilePath, enableEnhancement, serverDir);
1650
- router.get("/", (req, res) => handler(req, res, context));
1654
+ router.get("/openapi.json", (req, res) => handler(req, res, context));
1651
1655
  return router;
1652
1656
  }
1653
1657
  __name(createOpenapiRouter, "createOpenapiRouter");
@@ -1656,7 +1660,7 @@ __name(createOpenapiRouter, "createOpenapiRouter");
1656
1660
  var OPENAPI_ROUTES = [
1657
1661
  {
1658
1662
  method: "GET",
1659
- path: "/",
1663
+ path: "/openapi.json",
1660
1664
  description: "Serve enhanced OpenAPI specification with source code references"
1661
1665
  }
1662
1666
  ];
@@ -1664,7 +1668,7 @@ function createOpenapiMiddleware(options) {
1664
1668
  const { openapiFilePath, enableEnhancement = true, serverDir } = options;
1665
1669
  return {
1666
1670
  name: "openapi",
1667
- mountPath: "/dev/openapi.json",
1671
+ mountPath: "/dev",
1668
1672
  routes: OPENAPI_ROUTES,
1669
1673
  enabled: /* @__PURE__ */ __name((context) => context.isDev, "enabled"),
1670
1674
  createRouter: /* @__PURE__ */ __name((context) => {
@@ -1936,10 +1940,8 @@ function parsePinoLog(line, source) {
1936
1940
  statusCode: pinoLog.status_code,
1937
1941
  durationMs: pinoLog.duration_ms,
1938
1942
  ip: pinoLog.ip,
1939
- referer: pinoLog.referer,
1940
1943
  requestBody: pinoLog.request_body,
1941
- responseBody: pinoLog.response_body,
1942
- queryParams: pinoLog.query_params
1944
+ responseBody: pinoLog.response_body
1943
1945
  },
1944
1946
  tags: [
1945
1947
  source
@@ -2844,8 +2846,7 @@ function parsePinoLog2(line, source) {
2844
2846
  durationMs: pinoLog.duration_ms,
2845
2847
  ip: pinoLog.ip,
2846
2848
  requestBody: pinoLog.request_body,
2847
- responseBody: pinoLog.response_body,
2848
- queryParams: pinoLog.query_params
2849
+ responseBody: pinoLog.response_body
2849
2850
  },
2850
2851
  tags: [
2851
2852
  source
@@ -3296,108 +3297,6 @@ function createSSEHandler(logDir, options = {}) {
3296
3297
  }
3297
3298
  __name(createSSEHandler, "createSSEHandler");
3298
3299
 
3299
- // src/middlewares/dev-logs/api-list-handler.ts
3300
- var SERVER_PORT = process.env.SERVER_PORT || "3000";
3301
- function extractModuleFromPath(path7) {
3302
- const segments = path7.split("/").filter(Boolean);
3303
- let startIndex = 0;
3304
- if (segments[0] === "api") {
3305
- startIndex = 1;
3306
- }
3307
- if (segments[startIndex]?.match(/^v\d+$/)) {
3308
- startIndex++;
3309
- }
3310
- const moduleName = segments[startIndex];
3311
- if (!moduleName || moduleName.startsWith(":")) {
3312
- return "default";
3313
- }
3314
- return moduleName;
3315
- }
3316
- __name(extractModuleFromPath, "extractModuleFromPath");
3317
- function generateRouteId(method, path7) {
3318
- const cleanPath = path7.replace(/[/:]/g, "_").replace(/^_+|_+$/g, "");
3319
- return `${method.toLowerCase()}_${cleanPath}`;
3320
- }
3321
- __name(generateRouteId, "generateRouteId");
3322
- function capitalize(str) {
3323
- return str.charAt(0).toUpperCase() + str.slice(1);
3324
- }
3325
- __name(capitalize, "capitalize");
3326
- function groupRoutesByModule(routes) {
3327
- const groupMap = /* @__PURE__ */ new Map();
3328
- routes.forEach((route) => {
3329
- const existing = groupMap.get(route.module) || [];
3330
- existing.push(route);
3331
- groupMap.set(route.module, existing);
3332
- });
3333
- const groups = [];
3334
- groupMap.forEach((apis, moduleName) => {
3335
- groups.push({
3336
- id: moduleName,
3337
- name: capitalize(moduleName),
3338
- apis: apis.sort((a, b) => a.path.localeCompare(b.path))
3339
- });
3340
- });
3341
- return groups.sort((a, b) => a.name.localeCompare(b.name));
3342
- }
3343
- __name(groupRoutesByModule, "groupRoutesByModule");
3344
- async function fetchRoutesFromBackend(basePath) {
3345
- const normalizedBasePath = basePath.replace(/\/+$/, "");
3346
- const url = `http://localhost:${SERVER_PORT}${normalizedBasePath}/api/__framework__/debug`;
3347
- const response = await fetch(url, {
3348
- method: "GET",
3349
- headers: {
3350
- "Accept": "application/json"
3351
- }
3352
- });
3353
- if (!response.ok) {
3354
- throw new Error(`Failed to fetch routes: ${response.status}`);
3355
- }
3356
- const data = await response.json();
3357
- const routeConfig = data["\u8DEF\u7531\u914D\u7F6E"];
3358
- if (!routeConfig || !routeConfig.routes) {
3359
- return [];
3360
- }
3361
- const debugRoutes = routeConfig.routes;
3362
- return debugRoutes.filter((route) => {
3363
- return route.path.includes("/api/") && !route.path.includes("__framework__") && !route.path.includes("__innerapi__") && !route.path.includes("/api/capability");
3364
- }).map((route) => {
3365
- const apiPathMatch = route.path.match(/\/api\/.*/);
3366
- const apiPath = apiPathMatch ? apiPathMatch[0] : route.path;
3367
- const method = route.method || "ALL";
3368
- return {
3369
- id: generateRouteId(method, apiPath),
3370
- path: apiPath,
3371
- method,
3372
- module: extractModuleFromPath(apiPath)
3373
- };
3374
- });
3375
- }
3376
- __name(fetchRoutesFromBackend, "fetchRoutesFromBackend");
3377
- function createApiListHandler() {
3378
- return async (req, res) => {
3379
- res.header("Access-Control-Allow-Origin", "*");
3380
- res.header("Access-Control-Allow-Methods", "GET, OPTIONS");
3381
- res.header("Access-Control-Allow-Headers", "Content-Type, Accept");
3382
- try {
3383
- const basePath = process.env.CLIENT_BASE_PATH || "";
3384
- const routes = await fetchRoutesFromBackend(basePath);
3385
- const groups = groupRoutesByModule(routes);
3386
- res.json({
3387
- groups,
3388
- total: routes.length
3389
- });
3390
- } catch (error) {
3391
- console.error("[api-list] Failed to fetch routes:", error);
3392
- res.status(500).json({
3393
- error: "Failed to fetch routes",
3394
- message: error instanceof Error ? error.message : "Unknown error"
3395
- });
3396
- }
3397
- };
3398
- }
3399
- __name(createApiListHandler, "createApiListHandler");
3400
-
3401
3300
  // src/middlewares/dev-logs/router.ts
3402
3301
  function createDevLogRouter(options = {}) {
3403
3302
  const logDir = resolveLogDir(options.logDir);
@@ -3411,7 +3310,6 @@ function createDevLogRouter(options = {}) {
3411
3310
  router.get("/trace/trigger/:instanceID", createGetTriggerDetailHandler(logDir));
3412
3311
  router.get("/trace/capability/list", createGetCapabilityTraceListHandler(logDir));
3413
3312
  router.get("/health", createHealthCheckHandler());
3414
- router.get("/api-list", createApiListHandler());
3415
3313
  return router;
3416
3314
  }
3417
3315
  __name(createDevLogRouter, "createDevLogRouter");
@@ -3447,11 +3345,6 @@ var DEV_LOGS_ROUTES = [
3447
3345
  method: "GET",
3448
3346
  path: "/trace/trigger/:instanceID",
3449
3347
  description: "Get trigger detail (automation trigger) in trace.log by instanceID"
3450
- },
3451
- {
3452
- method: "GET",
3453
- path: "/api-list",
3454
- description: "Get all API routes grouped by module"
3455
3348
  }
3456
3349
  ];
3457
3350
  function createDevLogsMiddleware(options = {}) {
@@ -3602,148 +3495,100 @@ function createCollectLogsMiddleware(options = {}) {
3602
3495
  }
3603
3496
  __name(createCollectLogsMiddleware, "createCollectLogsMiddleware");
3604
3497
 
3605
- // src/middlewares/api-routes/router.ts
3606
- var import_express4 = __toESM(require("express"), 1);
3607
- function extractModuleFromPath2(path7) {
3608
- const segments = path7.split("/").filter(Boolean);
3609
- let startIndex = 0;
3610
- if (segments[0] === "api") {
3611
- startIndex = 1;
3612
- }
3613
- if (segments[startIndex]?.match(/^v\d+$/)) {
3614
- startIndex++;
3615
- }
3616
- const moduleName = segments[startIndex];
3617
- if (!moduleName || moduleName.startsWith(":")) {
3618
- return "default";
3619
- }
3620
- return moduleName;
3621
- }
3622
- __name(extractModuleFromPath2, "extractModuleFromPath");
3623
- function generateRouteId2(method, path7) {
3624
- const cleanPath = path7.replace(/[/:]/g, "_").replace(/^_+|_+$/g, "");
3625
- return `${method.toLowerCase()}_${cleanPath}`;
3626
- }
3627
- __name(generateRouteId2, "generateRouteId");
3628
- function capitalize2(str) {
3629
- return str.charAt(0).toUpperCase() + str.slice(1);
3630
- }
3631
- __name(capitalize2, "capitalize");
3632
- function extractRoutes(app) {
3633
- const router = app._router;
3634
- if (!router?.stack) {
3635
- return [];
3498
+ // src/middlewares/compat.ts
3499
+ function sendJson(res, data, statusCode = 200) {
3500
+ const statusFn = res.status;
3501
+ const jsonFn = res.json;
3502
+ if (typeof statusFn === "function" && typeof jsonFn === "function") {
3503
+ statusFn.call(res, statusCode);
3504
+ jsonFn.call(res, data);
3505
+ } else {
3506
+ res.statusCode = statusCode;
3507
+ res.setHeader("Content-Type", "application/json");
3508
+ res.end(JSON.stringify(data));
3636
3509
  }
3637
- const routes = [];
3638
- const seenRoutes = /* @__PURE__ */ new Set();
3639
- const processLayer = /* @__PURE__ */ __name((layer, basePath = "") => {
3640
- if (layer.route) {
3641
- const path7 = basePath + layer.route.path;
3642
- if (!path7.includes("/api/") || path7.includes("__framework__") || path7.includes("__innerapi__")) {
3643
- return;
3644
- }
3645
- const methods = Object.keys(layer.route.methods).filter((m) => layer.route.methods[m]);
3646
- methods.forEach((method) => {
3647
- const upperMethod = method.toUpperCase();
3648
- const routeKey = `${upperMethod}:${path7}`;
3649
- if (seenRoutes.has(routeKey)) {
3650
- return;
3651
- }
3652
- seenRoutes.add(routeKey);
3653
- const apiPathMatch = path7.match(/\/api\/.*/);
3654
- const apiPath = apiPathMatch ? apiPathMatch[0] : path7;
3655
- routes.push({
3656
- id: generateRouteId2(upperMethod, apiPath),
3657
- path: apiPath,
3658
- method: upperMethod,
3659
- module: extractModuleFromPath2(apiPath)
3660
- });
3661
- });
3662
- }
3663
- if (layer.name === "router" && layer.handle?.stack) {
3664
- let prefix = basePath;
3665
- if (layer.regexp) {
3666
- const pattern = new RegExp("^\\^\\\\?(.*?)(?:\\\\/\\?|$)");
3667
- const match = layer.regexp.source.match(pattern);
3668
- if (match) {
3669
- prefix = basePath + match[1].replace(/\\\//g, "/");
3670
- }
3671
- }
3672
- layer.handle.stack.forEach((subLayer) => processLayer(subLayer, prefix));
3673
- }
3674
- }, "processLayer");
3675
- router.stack.forEach((layer) => processLayer(layer));
3676
- return routes;
3677
- }
3678
- __name(extractRoutes, "extractRoutes");
3679
- function groupRoutesByModule2(routes) {
3680
- const groupMap = /* @__PURE__ */ new Map();
3681
- routes.forEach((route) => {
3682
- const existing = groupMap.get(route.module) || [];
3683
- existing.push(route);
3684
- groupMap.set(route.module, existing);
3685
- });
3686
- const groups = [];
3687
- groupMap.forEach((apis, moduleName) => {
3688
- groups.push({
3689
- id: moduleName,
3690
- name: capitalize2(moduleName),
3691
- apis: apis.sort((a, b) => a.path.localeCompare(b.path))
3692
- });
3693
- });
3694
- return groups.sort((a, b) => a.name.localeCompare(b.name));
3695
- }
3696
- __name(groupRoutesByModule2, "groupRoutesByModule");
3697
- function createApiRoutesRouter() {
3698
- console.log("[api-routes] createApiRoutesRouter called");
3699
- const router = import_express4.default.Router();
3700
- console.log("[api-routes] router created, adding /api-list route");
3701
- router.get("/api-list", (req, res) => {
3702
- console.log("[api-routes] /api-list handler called");
3703
- res.header("Access-Control-Allow-Origin", "*");
3704
- res.header("Access-Control-Allow-Methods", "GET, OPTIONS");
3705
- res.header("Access-Control-Allow-Headers", "Content-Type, Accept");
3706
- try {
3707
- const routes = extractRoutes(req.app);
3708
- const groups = groupRoutesByModule2(routes);
3709
- res.json({
3710
- groups,
3711
- total: routes.length
3712
- });
3713
- } catch (error) {
3714
- console.error("[api-routes] Failed to extract routes:", error);
3715
- res.status(500).json({
3716
- error: "Failed to extract routes",
3717
- message: error instanceof Error ? error.message : "Unknown error"
3718
- });
3719
- }
3720
- });
3721
- return router;
3722
3510
  }
3723
- __name(createApiRoutesRouter, "createApiRoutesRouter");
3724
-
3725
- // src/middlewares/api-routes/index.ts
3726
- var API_ROUTES_ROUTES = [
3727
- {
3728
- method: "GET",
3729
- path: "/api-list",
3730
- description: "Get all API routes grouped by module"
3511
+ __name(sendJson, "sendJson");
3512
+ function sendError(res, message, error, statusCode = 500) {
3513
+ const errorData = {
3514
+ message,
3515
+ ...error ? {
3516
+ error: serializeError3(error)
3517
+ } : {}
3518
+ };
3519
+ sendJson(res, errorData, statusCode);
3520
+ }
3521
+ __name(sendError, "sendError");
3522
+ function sendSuccess(res, data) {
3523
+ sendJson(res, {
3524
+ success: true,
3525
+ ...data
3526
+ }, 200);
3527
+ }
3528
+ __name(sendSuccess, "sendSuccess");
3529
+ function getQuery(req) {
3530
+ if (req.query) {
3531
+ return req.query;
3532
+ }
3533
+ const url = new URL(req.url || "", `http://${req.headers.host}`);
3534
+ return Object.fromEntries(url.searchParams.entries());
3535
+ }
3536
+ __name(getQuery, "getQuery");
3537
+ function getQueryParam(req, key) {
3538
+ const query = getQuery(req);
3539
+ return query[key];
3540
+ }
3541
+ __name(getQueryParam, "getQueryParam");
3542
+ function serializeError3(error) {
3543
+ if (error instanceof Error) {
3544
+ return {
3545
+ name: error.name,
3546
+ message: error.message,
3547
+ stack: error.stack
3548
+ };
3731
3549
  }
3732
- ];
3733
- function createApiRoutesMiddleware() {
3734
3550
  return {
3735
- name: "api-routes",
3736
- mountPath: "/dev/api",
3737
- routes: API_ROUTES_ROUTES,
3738
- enabled: /* @__PURE__ */ __name((context) => context.isDev, "enabled"),
3739
- createRouter: /* @__PURE__ */ __name((_context) => {
3740
- return createApiRoutesRouter();
3741
- }, "createRouter")
3551
+ message: String(error)
3742
3552
  };
3743
3553
  }
3744
- __name(createApiRoutesMiddleware, "createApiRoutesMiddleware");
3554
+ __name(serializeError3, "serializeError");
3745
3555
 
3746
3556
  // src/middlewares/index.ts
3557
+ function enhanceForCompat(req, res) {
3558
+ if (!res.status) {
3559
+ res.status = function(code) {
3560
+ res.statusCode = code;
3561
+ return res;
3562
+ };
3563
+ }
3564
+ if (!res.json) {
3565
+ res.json = function(data) {
3566
+ res.setHeader("Content-Type", "application/json");
3567
+ res.end(JSON.stringify(data));
3568
+ return res;
3569
+ };
3570
+ }
3571
+ if (!res.send) {
3572
+ res.send = function(data) {
3573
+ if (typeof data === "object" && data !== null) {
3574
+ res.setHeader("Content-Type", "application/json");
3575
+ res.end(JSON.stringify(data));
3576
+ } else {
3577
+ res.end(String(data));
3578
+ }
3579
+ return res;
3580
+ };
3581
+ }
3582
+ if (!req.query) {
3583
+ const url = new URL(req.url || "", `http://${req.headers.host || "localhost"}`);
3584
+ req.query = Object.fromEntries(url.searchParams.entries());
3585
+ }
3586
+ }
3587
+ __name(enhanceForCompat, "enhanceForCompat");
3588
+ function isConnectServer(server) {
3589
+ return typeof server === "function" && !("set" in server) && !("engine" in server);
3590
+ }
3591
+ __name(isConnectServer, "isConnectServer");
3747
3592
  function isRouteMiddleware(middleware) {
3748
3593
  return "createRouter" in middleware && middleware.createRouter !== void 0;
3749
3594
  }
@@ -3796,6 +3641,13 @@ async function registerMiddlewares(server, middlewares, options) {
3796
3641
  rootDir: process.cwd(),
3797
3642
  ...options
3798
3643
  };
3644
+ if (isConnectServer(server)) {
3645
+ server.use((req, res, next) => {
3646
+ enhanceForCompat(req, res);
3647
+ next();
3648
+ });
3649
+ console.log("[Middleware] Registered Express compatibility layer for Connect/Vite");
3650
+ }
3799
3651
  const allMiddlewares = [
3800
3652
  ...middlewares
3801
3653
  ];
@@ -3824,14 +3676,18 @@ async function registerMiddlewares(server, middlewares, options) {
3824
3676
  __name(registerMiddlewares, "registerMiddlewares");
3825
3677
  // Annotate the CommonJS export names for ESM import in node:
3826
3678
  0 && (module.exports = {
3827
- createApiRoutesMiddleware,
3828
3679
  createCollectLogsMiddleware,
3829
3680
  createDevLogsMiddleware,
3830
3681
  createOpenapiMiddleware,
3682
+ getQuery,
3683
+ getQueryParam,
3831
3684
  handleDevProxyError,
3832
3685
  normalizeBasePath,
3833
3686
  parseAndGenerateNestResourceTemplate,
3834
3687
  postprocessDrizzleSchema,
3835
- registerMiddlewares
3688
+ registerMiddlewares,
3689
+ sendError,
3690
+ sendJson,
3691
+ sendSuccess
3836
3692
  });
3837
3693
  //# sourceMappingURL=index.cjs.map