@faapi/faapi 0.0.0-canary.e2ee43b → 0.0.0-canary.f5b23c6

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/index.d.ts CHANGED
@@ -119,6 +119,19 @@ interface FaapiContext {
119
119
  * 设置响应头
120
120
  */
121
121
  setHeader(key: string, value: string): void;
122
+ /**
123
+ * 设置 ETag 响应头
124
+ *
125
+ * handler 中基于业务数据(如 updatedAt / version / contentHash)设置 ETag:
126
+ * ```ts
127
+ * export function GET(ctx) {
128
+ * const data = await fetchData();
129
+ * ctx.setETag(`"${data.version}-${data.updatedAt}"`);
130
+ * return data;
131
+ * }
132
+ * ```
133
+ */
134
+ setETag(value: string): void;
122
135
  /**
123
136
  * 返回 JSON 响应(handler 直接 return)
124
137
  *
@@ -272,22 +285,50 @@ interface CorsOptions {
272
285
  */
273
286
  declare function cors(options?: CorsOptions): FaapiMiddleware;
274
287
 
288
+ type LoggerFn = (messageOrObj: string | Record<string, unknown>, message?: string) => void;
275
289
  interface LoggerOptions {
276
- /** 自定义日志输出函数,默认 console.log */
277
- log?: (message: string) => void;
290
+ /**
291
+ * 自定义日志函数
292
+ *
293
+ * - 传入 `console.log`(默认):纯文本格式 `GET /api/users 200 12ms`
294
+ * - 传入 pino logger:结构化日志 `logger.info({ method, path, status, durationMs }, 'request completed')`
295
+ * - 传入 winston logger:`logger.info('GET /api/users 200 12ms', { method, path })`
296
+ */
297
+ log?: LoggerFn;
278
298
  }
279
299
  /**
280
300
  * 创建请求日志中间件(洋葱模型)
281
301
  *
282
- * 日志格式:GET /api/users 200 12ms
283
- * 错误格式:POST /api/users 400 45ms - Error: ...
302
+ * 日志格式(文本模式):GET /api/users 200 12ms
303
+ * 错误格式(文本模式):POST /api/users 400 45ms - Error: ...
304
+ *
305
+ * 结构化模式:传入 pino/winston 等 logger 实例时,会自动传递结构化字段。
284
306
  *
285
307
  * before/after 一体,闭包变量共享开始时间,无需污染 ctx。
286
308
  * 错误用 try/catch 捕获,记录后重新抛出(让上层处理)。
287
309
  * 成功时从 next() 返回的 Response 读取状态码。
310
+ *
311
+ * log 函数每次请求时读取(options.log ?? console.log),运行时替换 console.log 会生效。
288
312
  */
289
313
  declare function logger(options?: LoggerOptions): FaapiMiddleware;
290
314
 
315
+ interface HelmetOptions {
316
+ contentSecurityPolicy?: string | false;
317
+ xFrameOptions?: 'DENY' | 'SAMEORIGIN' | false;
318
+ xContentTypeOptions?: boolean;
319
+ referrerPolicy?: string | false;
320
+ strictTransportSecurity?: string | false;
321
+ xDnsPrefetchControl?: boolean;
322
+ xDownloadOptions?: boolean;
323
+ xPermittedCrossDomainPolicies?: string | false;
324
+ crossOriginOpenerPolicy?: string | false;
325
+ crossOriginResourcePolicy?: string | false;
326
+ crossOriginEmbedderPolicy?: string | false;
327
+ originAgentCluster?: boolean;
328
+ xPoweredBy?: boolean;
329
+ }
330
+ declare function helmet(options?: HelmetOptions): FaapiMiddleware;
331
+
291
332
  declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
292
333
  type HttpMethod = (typeof HTTP_METHODS)[number];
293
334
 
@@ -304,7 +345,26 @@ interface RouteRecord {
304
345
  /** 路由对应的注入器映射表(从根到路由目录合并,构建时加载) */
305
346
  injectors?: InjectorMap;
306
347
  }
348
+ /**
349
+ * WebSocket 路由记录
350
+ *
351
+ * 与 HTTP RouteRecord 类似,但不绑定 HTTP 方法(WS 是协议升级,不区分 GET/POST)。
352
+ * 一个 handler.ts 中导出 WS 即生成一条 WS 路由记录。
353
+ */
354
+ interface WsRouteRecord {
355
+ urlPath: string;
356
+ filePath: string;
357
+ paramNames: string[];
358
+ isDynamic: boolean;
359
+ /** 是否为 catch-all 路由([...slug]) */
360
+ isCatchAll?: boolean;
361
+ /** 路由对应的中间件集合(握手阶段执行,复用鉴权/CORS/日志) */
362
+ middlewares?: FaapiMiddleware[];
363
+ /** 路由对应的注入器映射表 */
364
+ injectors?: InjectorMap;
365
+ }
307
366
  type RouteManifest = RouteRecord[];
367
+ type WsRouteManifest = WsRouteRecord[];
308
368
  /**
309
369
  * 路由单个参数的 schema 描述
310
370
  *
@@ -323,6 +383,18 @@ interface RouteInputSchema {
323
383
  schemaName: string | null;
324
384
  properties: RouteParamSchema[];
325
385
  }
386
+ /**
387
+ * 路由响应类型的 schema 描述
388
+ *
389
+ * 由 @faapi/schema 扩展包的 buildRouteSchemas 生成。
390
+ * output 为 null 表示无显式返回类型注解、void/Promise<void>、或解析失败降级。
391
+ */
392
+ interface RouteOutputSchema {
393
+ /** 命名类型名(如 'UserResponse'),内联类型为 null */
394
+ schemaName: string | null;
395
+ /** 顶层属性列表 */
396
+ properties: RouteParamSchema[];
397
+ }
326
398
  /**
327
399
  * 路由的完整 schema 描述
328
400
  *
@@ -335,6 +407,8 @@ interface RouteInfo {
335
407
  filePath: string;
336
408
  isDynamic: boolean;
337
409
  inputs: RouteInputSchema[];
410
+ /** 响应类型描述(null 表示无返回类型注解/void/解析失败) */
411
+ output: RouteOutputSchema | null;
338
412
  }
339
413
 
340
414
  /** HTTP 请求 handler 类型 */
@@ -352,8 +426,10 @@ type UpgradeHandler = (req: IncomingMessage, socket: Socket, head: Buffer) => vo
352
426
  interface PluginContext {
353
427
  /** 项目根目录 */
354
428
  rootDir: string;
355
- /** 当前路由清单 */
429
+ /** 当前路由清单(setup 时的快照,reloadRoutes 后不会更新;需最新路由用 getRoutes()) */
356
430
  routes: RouteManifest;
431
+ /** 获取最新路由清单(reloadRoutes 后返回更新后的数组) */
432
+ getRoutes: () => RouteManifest;
357
433
  /** HTTP 服务器实例(未 listen) */
358
434
  server: Server;
359
435
  /** 自定义业务配置(faapi.config.ts 中的自定义 key) */
@@ -424,40 +500,31 @@ type PluginDeclaration = string | [string, unknown] | {
424
500
  options?: unknown;
425
501
  };
426
502
 
427
- /**
428
- * 统一响应格式化函数
429
- *
430
- * 当配置了 responseFormat 时,handler 返回的非 Response 值会经过此函数包装
431
- * 例如:{ code: 0, data, message: 'success' }
432
- */
433
- type ResponseFormatFn = (data: unknown, ctx: FaapiContext) => unknown;
434
- /**
435
- * 错误响应格式化函数
436
- *
437
- * 优先于内置 formatErrorResponse 处理错误。返回 Response 表示已处理;
438
- * 返回 null/undefined 表示不处理,由内置 formatErrorResponse 兜底。
439
- */
440
- type ErrorFormatFn = (error: unknown, ctx?: FaapiContext) => Response | null | undefined;
503
+ interface Http2Options {
504
+ key?: string;
505
+ cert?: string;
506
+ }
507
+
441
508
  /**
442
509
  * 生命周期钩子
443
510
  */
444
511
  interface LifecycleHooks {
445
- /** 路由加载完成、服务器启动前调用(适合初始化数据库连接等) */
512
+ /** 服务器启动后调用(适合初始化数据库连接等) */
446
513
  onReady?: (ctx: LifecycleContext) => Promise<void> | void;
447
514
  /** 服务器关闭时调用(适合清理资源、优雅关闭) */
448
515
  onClose?: (ctx: LifecycleContext) => Promise<void> | void;
449
516
  /**
450
- * 请求错误已被 errorFormat 处理为响应后调用(参考 Fastify onError 语义)
517
+ * 请求错误已被处理为响应后调用(参考 Fastify onError 语义)
451
518
  *
452
- * 时机:handler 抛错 → errorFormat 生成错误响应(失败则由框架内置 formatErrorResponse 兜底)
519
+ * 时机:handler 抛错 → 全局中间件 try/catch(若有) → 框架内置 formatErrorResponse 兜底
453
520
  * → 响应发出后 → onError 触发副作用
454
521
  *
455
- * 职责:日志上报、告警、链路追踪等副作用。**不修改、不替换已生成的响应**。
456
- * 自身抛错会被捕获并忽略,不影响响应已发送的事实。
522
+ * 职责:日志上报、告警、链路追踪等副作用。**不修改、不替换已生成的响应**。
523
+ * 自身抛错会被捕获并忽略,不影响响应已发送的事实。
457
524
  *
458
- * 与 errorFormat 的区别:
459
- * - errorFormat:把 error 翻译成 Response(主入口,决定响应内容)
460
- * - onError:响应发出后的副作用(不能改响应)
525
+ * 与全局错误中间件的区别:
526
+ * - 全局错误中间件:把 error 翻译成 Response(主入口,决定响应内容)
527
+ * - onError:响应发出后的副作用(不能改响应)
461
528
  */
462
529
  onError?: (error: unknown, ctx: FaapiContext) => Promise<void> | void;
463
530
  }
@@ -479,7 +546,6 @@ interface LifecycleContext {
479
546
  * ```ts
480
547
  * import type { FaapiConfig } from '@faapi/faapi';
481
548
  * export default {
482
- * port: 3000,
483
549
  * cors: { origin: '*' },
484
550
  * } satisfies FaapiConfig;
485
551
  * ```
@@ -488,7 +554,6 @@ interface LifecycleContext {
488
554
  * ```ts
489
555
  * import type { FaapiConfig } from '@faapi/faapi';
490
556
  * export default {
491
- * port: 3000,
492
557
  * cors: { origin: '*' },
493
558
  * // 自定义业务配置(任意 key)
494
559
  * db: { host: 'localhost', port: 5432 },
@@ -496,20 +561,24 @@ interface LifecycleContext {
496
561
  * ```
497
562
  *
498
563
  * 环境覆盖通过 faapi.config.{NODE_ENV}.ts 实现(如 faapi.config.production.ts)
564
+ *
565
+ * 框架元信息通过环境变量配置(不放在 config 内):
566
+ * - `PORT`:服务端口,默认 3000
567
+ * - `FAAPI_DIST`:产物输出目录(实际目录),dev 为 <dist>/dev(默认 .faapi/dev),prod 为 <dist>/build(默认 .faapi/build)
499
568
  */
500
569
  interface FaapiConfig {
501
- /** 服务端口,默认 3000(可被 --port / PORT 环境变量覆盖) */
502
- port?: number;
503
- /** 静态文件目录 */
504
- staticDir?: string;
505
570
  /** CORS 配置,false 禁用 */
506
571
  cors?: CorsOptions | boolean;
507
- /** 统一响应格式化函数 */
508
- responseFormat?: ResponseFormatFn;
509
- /** 错误响应格式化函数 */
510
- errorFormat?: ErrorFormatFn;
511
572
  /** 生命周期钩子 */
512
573
  lifecycle?: LifecycleHooks;
574
+ /** 安全头配置,false 禁用 */
575
+ helmet?: HelmetOptions | boolean;
576
+ /** 请求体大小限制(字节),默认 10MB(10 * 1024 * 1024) */
577
+ bodyLimit?: number;
578
+ /** 日志中间件配置 */
579
+ logger?: LoggerOptions | boolean;
580
+ /** HTTP/2 配置,false 禁用(默认 http/1.1) */
581
+ http2?: Http2Options | boolean;
513
582
  /**
514
583
  * 全局中间件:对所有路由(HTTP + WebSocket 握手)生效
515
584
  *
@@ -672,6 +741,15 @@ interface WsContext {
672
741
  */
673
742
  type WsHandler = (ctx: WsContext) => WsEventHandlers | void;
674
743
 
744
+ /**
745
+ * 清理所有 Program 缓存(watch 模式下文件变化时调用)
746
+ *
747
+ * 全量清理而非增量清理,理由:
748
+ * - 简单可靠,无状态一致性问题
749
+ * - 跨文件类型引用需要所有文件的 Program 同步更新
750
+ * - dev 模式文件量有限,全量重建在百毫秒级
751
+ */
752
+ declare function invalidateProgramCache(): void;
675
753
  /**
676
754
  * 为指定文件创建 TypeScript Program(带缓存)
677
755
  *
@@ -733,6 +811,13 @@ type RuntimeType = {
733
811
  kind: 'record';
734
812
  key: RuntimeType;
735
813
  value: RuntimeType;
814
+ } | {
815
+ kind: 'map';
816
+ key: RuntimeType;
817
+ value: RuntimeType;
818
+ } | {
819
+ kind: 'set';
820
+ element: RuntimeType;
736
821
  } | {
737
822
  kind: 'ref';
738
823
  name: string;
@@ -752,7 +837,79 @@ interface PropertyType {
752
837
  name: string;
753
838
  type: RuntimeType;
754
839
  optional: boolean;
840
+ /**
841
+ * 字段级 JSDoc 约束标签(@max/@min/@maxLength 等)
842
+ *
843
+ * 来自字段 JSDoc 注释,由 generateZodSchema 转为 zod 链式调用。
844
+ * 约束与字段类型不匹配时在提取阶段抛 SchemaExtractionError。
845
+ */
846
+ constraints?: TypeConstraint[];
755
847
  }
848
+ /**
849
+ * JSDoc 约束标签的运行时描述
850
+ *
851
+ * 由字段 JSDoc 注释提取,对应 zod schema 的链式约束方法。
852
+ * 仅在 PropertyType.constraints 中出现,不挂在嵌套类型(array 元素、tuple 元素等)上。
853
+ */
854
+ type TypeConstraint = {
855
+ kind: 'max';
856
+ value: number;
857
+ } | {
858
+ kind: 'min';
859
+ value: number;
860
+ } | {
861
+ kind: 'int';
862
+ } | {
863
+ kind: 'positive';
864
+ } | {
865
+ kind: 'negative';
866
+ } | {
867
+ kind: 'nonnegative';
868
+ } | {
869
+ kind: 'nonpositive';
870
+ } | {
871
+ kind: 'maxLength';
872
+ value: number;
873
+ } | {
874
+ kind: 'minLength';
875
+ value: number;
876
+ } | {
877
+ kind: 'length';
878
+ value: number;
879
+ } | {
880
+ kind: 'regex';
881
+ pattern: string;
882
+ flags?: string;
883
+ } | {
884
+ kind: 'email';
885
+ } | {
886
+ kind: 'url';
887
+ } | {
888
+ kind: 'uuid';
889
+ };
890
+ /**
891
+ * 将 TypeScript 类型节点解析为运行时类型描述
892
+ *
893
+ * 支持的类型:
894
+ * - 基础类型:string / number / boolean / null / undefined / any / unknown / void
895
+ * - bigint:不支持(HTTP/JSON 不能传输),AST 提取阶段抛 SchemaExtractionError
896
+ * - 字面量类型:'foo' / 42 / true
897
+ * - 数组类型:T[] / Array<T> / ReadonlyArray<T> / readonly T[]
898
+ * - 元组类型:[string, number] / [string, number?] / [string, ...number[]] / readonly [T, U](按位置校验)
899
+ * - 对象类型:{ name: string; age?: number }(含 readonly 字段修饰符,忽略 readonly)
900
+ * - 联合类型:string | null
901
+ * - 交叉类型:A & B(按对象合并处理)
902
+ * - 引用类型:Date / 其他 interface(递归解析)
903
+ * - 工具类型:Record<K, V> / Partial<T> / Readonly<T>(best effort)
904
+ * - Pick<T, K> / Omit<T, K>:K 支持字面量联合、类型别名、keyof T
905
+ *
906
+ * readonly 是编译期约束,运行时不产生校验语义,所有 readonly 修饰符统一忽略。
907
+ *
908
+ * @param typeNode TypeScript 类型节点
909
+ * @param checker 类型 checker(用于解析引用类型)
910
+ * @param visited 防止递归循环
911
+ */
912
+ declare function resolveTypeNode(typeNode: ts.TypeNode, checker?: ts.TypeChecker, visited?: Set<string>): RuntimeType;
756
913
 
757
914
  interface HandlerTypeInfo {
758
915
  name: string;
@@ -788,48 +945,216 @@ declare function extractTypeInfo(program: ts.Program, filePath: string, typeName
788
945
  declare function getInputTypeForMethod(method: string): 'query' | 'body';
789
946
 
790
947
  /**
791
- * 单个参数的 schema 描述(简化版,供扩展包消费)
948
+ * 单个路由的 schema 提取结果
949
+ *
950
+ * key 使用 urlPath(如 '/api/hello')而非 filePath,因为 urlPath 在 dev/prod 完全一致,
951
+ * 无需 remapManifestKeys 桥接 .ts/.js 路径差异。
792
952
  */
793
- interface SchemaPropertyDescriptor {
794
- name: string;
795
- type: string;
796
- required: boolean;
953
+ interface RouteSchemaSource {
954
+ /** 路由 URL 路径(如 '/api/hello'),作为 schema key */
955
+ urlPath: string;
956
+ /** 源文件绝对路径(用于 generateSchemaFiles 按文件分组生成 zod.js) */
957
+ filePath: string;
958
+ schemaName: string;
959
+ typeInfo: HandlerTypeInfo | null;
960
+ /**
961
+ * 是否对 number/boolean 字段生成 z.preprocess 字符串转换(coerce)。
962
+ *
963
+ * - query/params:始终 coerce=true(URL 来源均为 string)
964
+ * - body:始终 coerce=false(JSON 解析已是天然 JS 类型)
965
+ * - form:coerce=true(form-urlencoded 来源均为 string),由本函数在提取时
966
+ * 检测到 handler 声明 `form` 参数时显式设置。schema 名仍为 `POSTBody`
967
+ * (与 body 共享运行时 schema key),运行时 validateInput 无需感知 form/body 差异。
968
+ *
969
+ * 未设置时由 generateSchemaFileSource 回退到 schemaName 后缀正则推断(Query/Params → true)。
970
+ */
971
+ coerce?: boolean;
797
972
  }
798
973
  /**
799
- * 单个输入源的 schema 描述
974
+ * 从路由清单收集 schema 提取所需的原始数据
975
+ *
976
+ * dev 和 prd 共享的核心提取流程:
977
+ * 1. 按文件分组遍历路由
978
+ * 2. 对每个文件 createProgram + extractAllTypes 收集所有类型
979
+ * 3. 用 analyzeInjection + extractTypeInfo 提取每个路由的 schema 类型
980
+ * 4. 同时返回按文件分组的 allTypesMap 和合并后的全局 allTypes
981
+ *
982
+ * 调用方基于返回的 sources 和 allTypes 各自做最终转换:
983
+ * - dev:生成 JS 模块文件 → import 加载(用 allTypesByFile)
984
+ * - prd:生成 JS 模块代码 → SchemaModuleEntry[](用 allTypesByFile)
800
985
  */
801
- interface InputSchemaDescriptor {
802
- /** 输入源类型名(如 'Query'、'CreateUserBody'),无类型声明时 null */
803
- schemaName: string | null;
804
- /** 参数列表 */
805
- properties: SchemaPropertyDescriptor[];
986
+ declare function collectRouteSchemaSources(routes: RouteManifest, rootDir?: string): {
987
+ sources: RouteSchemaSource[];
988
+ /** 按文件分组的类型映射(prd writeSchemaModule 用) */
989
+ allTypesByFile: Map<string, Map<string, HandlerTypeInfo>>;
990
+ /** 合并后的全局类型映射(兼容旧调用方保留,新路径使用 allTypesByFile) */
991
+ mergedAllTypes: Map<string, HandlerTypeInfo>;
992
+ };
993
+
994
+ /**
995
+ * 加载 faapi 配置文件
996
+ *
997
+ * 统一读取 `<dist>/faapi-config.js` 产物:
998
+ * - dev 模式:`faapi dev` 启动时由 `compileConfig` 生成 `.faapi/dev/faapi-config.js`
999
+ * - prod 模式:`faapi build` 时由 `compileConfig` 生成 `.faapi/build/faapi-config.js`
1000
+ *
1001
+ * 产物由 `compileConfig` 在构建阶段合并 env 后固化,运行时不读源码、不现场编译、不按 env 合并。
1002
+ *
1003
+ * - 产物存在 → import 并返回 default
1004
+ * - 产物不存在但源码有配置文件 → 抛错(强制 rebuild)
1005
+ * - 源码也无配置文件 → 返回 `null`(配置可选)
1006
+ *
1007
+ * @param rootDir 项目根目录
1008
+ * @param dist 产物目录(如 '.faapi/build' 或 '.faapi/dev')
1009
+ * @returns 配置对象,无配置文件时返回 null
1010
+ */
1011
+ declare function loadConfig(rootDir: string, dist: string): Promise<Partial<FaapiConfig> | null>;
1012
+
1013
+ declare const VALIDATION_ERROR = "VALIDATION_ERROR";
1014
+ declare const ROUTE_NOT_FOUND = "ROUTE_NOT_FOUND";
1015
+ declare const METHOD_NOT_ALLOWED = "METHOD_NOT_ALLOWED";
1016
+ declare const INTERNAL_ERROR = "INTERNAL_ERROR";
1017
+ declare const MODULE_LOAD_ERROR = "MODULE_LOAD_ERROR";
1018
+ type ErrorCode = typeof VALIDATION_ERROR | typeof ROUTE_NOT_FOUND | typeof METHOD_NOT_ALLOWED | typeof INTERNAL_ERROR | typeof MODULE_LOAD_ERROR;
1019
+
1020
+ declare class FaapiError extends Error {
1021
+ readonly code: ErrorCode;
1022
+ readonly statusCode: number;
1023
+ constructor(code: ErrorCode, message: string, statusCode: number);
1024
+ }
1025
+
1026
+ declare class ValidationError extends FaapiError {
1027
+ readonly issues: ValidationIssue[];
1028
+ constructor(message: string, issues: ValidationIssue[]);
1029
+ }
1030
+ declare class RouteNotFoundError extends FaapiError {
1031
+ constructor(path: string);
1032
+ }
1033
+ declare class MethodNotAllowedError extends FaapiError {
1034
+ readonly allowedMethods: string[];
1035
+ constructor(method: string, path: string, allowedMethods: string[]);
1036
+ }
1037
+ declare class InternalError extends FaapiError {
1038
+ constructor(message: string);
1039
+ }
1040
+ declare class ModuleLoadError extends FaapiError {
1041
+ constructor(filePath: string, reason: string);
1042
+ }
1043
+ /**
1044
+ * 校验问题类型
1045
+ *
1046
+ * 结构化错误信息,便于上层(全局错误中间件/前端)按 code 做不同处理,
1047
+ * 不依赖字符串解析。message 仅为人类可读的兜底描述。
1048
+ *
1049
+ * code 与 HTTP 状态码的映射(由 ValidationError 推导):
1050
+ * - INVALID_FORMAT / MISSING_FIELD → 400 Bad Request
1051
+ * - TYPE_MISMATCH / INVALID_VALUE / COERCE_FAILED → 422 Unprocessable Entity
1052
+ */
1053
+ interface ValidationIssue {
1054
+ /** 字段路径,如 'user.address.city' */
1055
+ path: string;
1056
+ /** 错误码,机器可读的契约 */
1057
+ code: ValidationErrorCode;
1058
+ /** 期望类型/值,如 'number' / '"admin" | "user"' */
1059
+ expected: string;
1060
+ /** 实际类型/值,如 'string' / 'undefined' */
1061
+ received: string;
1062
+ /** 人类可读的本地化消息(兜底,不保证稳定) */
1063
+ message: string;
1064
+ }
1065
+ type ValidationErrorCode = 'TYPE_MISMATCH' | 'MISSING_FIELD' | 'INVALID_FORMAT' | 'INVALID_VALUE' | 'COERCE_FAILED';
1066
+
1067
+ interface InjectOptions {
1068
+ method?: string;
1069
+ path?: string;
1070
+ headers?: Record<string, string>;
1071
+ query?: Record<string, string>;
1072
+ body?: unknown;
1073
+ }
1074
+ interface InjectResponse {
1075
+ status: number;
1076
+ headers: Headers;
1077
+ body: unknown;
1078
+ }
1079
+ interface CreateAppOptions {
1080
+ /** 项目根目录,默认 process.cwd() */
1081
+ rootDir?: string;
1082
+ /** 产物输出目录(实际目录,如 .faapi/build 或 .faapi/dev),覆盖环境变量 FAAPI_DIST,默认 '.faapi/build' */
1083
+ dist?: string;
1084
+ /** 端口号,也可在 listen() 时传入;默认环境变量 PORT 或 3000 */
1085
+ port?: number;
1086
+ }
1087
+ /** 应用基础接口(dev/prod 共用,不含 reloadRoutes) */
1088
+ interface AppBase {
1089
+ /** Node.js Server 实例(listen 后可用,close 后置 null) */
1090
+ server: Server | null;
1091
+ /** 排序后的路由清单 */
1092
+ routes: RouteManifest;
1093
+ /** WebSocket 路由清单 */
1094
+ wsRoutes: WsRouteManifest;
1095
+ /** 项目根目录 */
1096
+ rootDir: string;
1097
+ /** 启动 HTTP server,打印路由表,执行 onReady 钩子 */
1098
+ listen(port?: number): Promise<Server>;
1099
+ /** 关闭 server,执行 onClose 钩子 */
1100
+ close(): Promise<void>;
1101
+ /**
1102
+ * 无服务器测试注入
1103
+ *
1104
+ * 构建一个模拟请求直接走完整请求链路,不绑定端口。
1105
+ * 需要在 listen() 之前调用(server 未启动时)。
1106
+ */
1107
+ inject(options?: InjectOptions): Promise<InjectResponse>;
1108
+ }
1109
+
1110
+ /** dev 应用接口(AppBase + reloadRoutes 热替换) */
1111
+ interface DevApp extends AppBase {
1112
+ /** 重新水合路由清单 + 清 schema 缓存 + 更新 server 路由引用(dev 热替换用) */
1113
+ reloadRoutes(): Promise<void>;
806
1114
  }
807
1115
  /**
808
- * 查询指定路由 handler 的输入参数 schema
1116
+ * dev 模式应用启动 API
1117
+ *
1118
+ * 在 createAppBase(共享逻辑)基础上增加 `reloadRoutes` 热替换能力,供 `faapi dev` watcher 调用。
1119
+ *
1120
+ * 与 createProdApp 的区别:
1121
+ * - dev:含 reloadRoutes(重新扫描路由 + 重新生成 schema + 清缓存 + 更新 server 路由引用)
1122
+ * - prod:精简,无 reloadRoutes(产物已固化,运行时不重建)
809
1123
  *
810
- * 复用 schemaRegistry 已有的类型提取结果,避免重复 AST 分析。
811
- * 在 schema 尚未注册时返回 undefined。
1124
+ * `devCommand` 直接调用,devCommand 持有 app 引用并传给 watcher。
812
1125
  *
813
- * @param filePath handler 文件绝对路径
814
- * @param method HTTP 方法(GET/POST 等)
815
- * @param inputType 输入源类型(query/body/params)
1126
+ * @example
1127
+ * ```ts
1128
+ * // devCommand 内部
1129
+ * const app = await createDevApp();
1130
+ * await app.listen();
1131
+ * startWatcher({ rootDir, app, devDist });
1132
+ * ```
816
1133
  */
817
- declare function getSchemaProperties(filePath: string, method: string, inputType: 'query' | 'body' | 'params'): InputSchemaDescriptor | undefined;
1134
+ declare function createDevApp(options?: CreateAppOptions): Promise<DevApp>;
1135
+
1136
+ /** prod 应用接口(AppBase,无 reloadRoutes) */
1137
+ type ProdApp = AppBase;
818
1138
 
819
1139
  /**
820
- * 加载 faapi 配置文件
1140
+ * prod 模式应用启动 API
821
1141
  *
822
- * 查找顺序:
823
- * 1. 指定的 configPath
824
- * 2. faapi.config.ts / faapi.config.js(基础配置)
825
- * 3. faapi.config.{env}.ts / faapi.config.{env}.js(环境覆盖,深度合并)
1142
+ * 直接返回 createAppBase 结果(共享逻辑),不含 dev 专用能力(reloadRoutes、缓存失效)。
1143
+ * 产物在 `faapi build` 阶段已固化,运行时不重建。
826
1144
  *
827
- * 环境由 FAAPI_ENV 或 NODE_ENV 决定,默认 'development'
1145
+ * 框架采用零入口设计——用户无需编写 main.ts:
1146
+ * - `faapi build` 自动生成 `dist/main.js` 启动入口,内部调用 `createProdApp()` + `listen()` 启动生产服务器
1147
+ * - 用户自定义启动逻辑通过 `faapi.config.ts` 的 `lifecycle.onReady` / `onClose` 钩子实现
828
1148
  *
829
- * @param rootDir 项目根目录
830
- * @param configPath 指定的配置文件路径(可选)
831
- * @returns 合并后的配置,如果无配置文件则返回 null
1149
+ * 编程式调用场景(如自定义 CLI 启动器)也可直接调用:
1150
+ *
1151
+ * @example
1152
+ * ```ts
1153
+ * import { createProdApp } from '@faapi/faapi';
1154
+ * const app = await createProdApp();
1155
+ * await app.listen();
1156
+ * ```
832
1157
  */
833
- declare function loadConfig(rootDir: string, configPath?: string): Promise<Partial<FaapiConfig> | null>;
1158
+ declare function createProdApp(options?: CreateAppOptions): Promise<ProdApp>;
834
1159
 
835
- export { type CorsOptions, type ErrorFormatFn, type FaapiConfig, type FaapiContext, type FaapiContextConfig, type FaapiMiddleware, type FaapiPlugin, type HandlerTypeInfo, type Injector, type InjectorMap, type InputSchemaDescriptor, type LifecycleContext, type LifecycleHooks, type LoggerOptions, type PluginContext, type PluginDeclaration, type PropertyType, type RequestHandler, type ResponseFormatFn, type RouteInfo, type RouteInputSchema, type RouteManifest, type RouteParamSchema, type RuntimeType, SchemaExtractionError, type SchemaPropertyDescriptor, type SseEvent, type SseWriter, type UpgradeHandler, type WsContext, type WsEventHandlers, type WsHandler, type WsSocket, cors, createProgram, extractTypeInfo, getInputTypeForMethod, getSchemaProperties, loadConfig, logger };
1160
+ export { type ProdApp as App, type CorsOptions, type CreateAppOptions, type DevApp, type FaapiConfig, type FaapiContext, type FaapiContextConfig, FaapiError, type FaapiMiddleware, type FaapiPlugin, type HandlerTypeInfo, type HelmetOptions, type InjectOptions, type InjectResponse, type Injector, type InjectorMap, InternalError, type LifecycleContext, type LifecycleHooks, type LoggerOptions, MethodNotAllowedError, ModuleLoadError, type PluginContext, type PluginDeclaration, type ProdApp, type PropertyType, type RequestHandler, type RouteInfo, type RouteInputSchema, type RouteManifest, RouteNotFoundError, type RouteOutputSchema, type RouteParamSchema, type RouteSchemaSource, type RuntimeType, SchemaExtractionError, type SseEvent, type SseWriter, type TypeConstraint, type UpgradeHandler, ValidationError, type ValidationErrorCode, type ValidationIssue, type WsContext, type WsEventHandlers, type WsHandler, type WsSocket, collectRouteSchemaSources, cors, createProdApp as createApp, createDevApp, createProdApp, createProgram, extractTypeInfo, getInputTypeForMethod, helmet, invalidateProgramCache, loadConfig, logger, resolveTypeNode };