@faapi/faapi 0.0.0-canary.4ab8d97 → 0.0.0-canary.a3f7014
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 +7 -1
- package/dist/cli/index.js +5887 -5340
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +379 -66
- package/dist/index.js +2765 -163
- package/dist/index.js.map +1 -1
- package/package.json +6 -7
package/dist/index.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
// src/ast/createProgram.ts
|
|
2
2
|
import ts from "typescript";
|
|
3
3
|
var programCache = /* @__PURE__ */ new Map();
|
|
4
|
+
function invalidateProgramCache() {
|
|
5
|
+
programCache.clear();
|
|
6
|
+
}
|
|
4
7
|
function createProgram(filePath) {
|
|
5
8
|
const cached = programCache.get(filePath);
|
|
6
9
|
if (cached) {
|
|
@@ -143,6 +146,9 @@ function resolveTypeNode(typeNode, checker, visited = /* @__PURE__ */ new Set())
|
|
|
143
146
|
if (ts2.isTypeOperatorNode(typeNode) && typeNode.operator === ts2.SyntaxKind.KeyOfKeyword) {
|
|
144
147
|
return resolveKeyOf(typeNode, checker);
|
|
145
148
|
}
|
|
149
|
+
if (ts2.isTypeOperatorNode(typeNode) && typeNode.operator === ts2.SyntaxKind.ReadonlyKeyword) {
|
|
150
|
+
return resolveTypeNode(typeNode.type, checker, visited);
|
|
151
|
+
}
|
|
146
152
|
if (ts2.isTypeReferenceNode(typeNode)) {
|
|
147
153
|
return resolveTypeReference(typeNode, checker, visited);
|
|
148
154
|
}
|
|
@@ -155,7 +161,11 @@ function resolveTypeLiteral(typeNode, checker, visited = /* @__PURE__ */ new Set
|
|
|
155
161
|
const name = member.name.getText();
|
|
156
162
|
const optional = !!member.questionToken;
|
|
157
163
|
const type = member.type ? resolveTypeNode(member.type, checker, visited) : { kind: "any" };
|
|
158
|
-
|
|
164
|
+
const constraints = extractConstraintsFromJsDoc(member, name);
|
|
165
|
+
validateConstraints(constraints, type, name);
|
|
166
|
+
properties.push(
|
|
167
|
+
constraints.length > 0 ? { name, type, optional, constraints } : { name, type, optional }
|
|
168
|
+
);
|
|
159
169
|
}
|
|
160
170
|
if (ts2.isIndexSignatureDeclaration(member)) {
|
|
161
171
|
const keyType = member.parameters[0]?.type ? resolveTypeNode(member.parameters[0].type, checker, visited) : { kind: "any" };
|
|
@@ -237,7 +247,7 @@ function resolveTypeReference(typeNode, checker, visited = /* @__PURE__ */ new S
|
|
|
237
247
|
if (typeName === "Date") {
|
|
238
248
|
return { kind: "date" };
|
|
239
249
|
}
|
|
240
|
-
if (typeName === "Array" && typeNode.typeArguments?.length === 1) {
|
|
250
|
+
if ((typeName === "Array" || typeName === "ReadonlyArray") && typeNode.typeArguments?.length === 1) {
|
|
241
251
|
return {
|
|
242
252
|
kind: "array",
|
|
243
253
|
element: resolveTypeNode(typeNode.typeArguments[0], checker, visited)
|
|
@@ -362,7 +372,12 @@ function resolveInterfaceDeclaration(node, checker, visited = /* @__PURE__ */ ne
|
|
|
362
372
|
const name = member.name.getText();
|
|
363
373
|
const optional = !!member.questionToken;
|
|
364
374
|
const type = member.type ? resolveTypeNode(member.type, checker, visited) : { kind: "any" };
|
|
365
|
-
|
|
375
|
+
const constraints = extractConstraintsFromJsDoc(member, name);
|
|
376
|
+
validateConstraints(constraints, type, name);
|
|
377
|
+
propMap.set(
|
|
378
|
+
name,
|
|
379
|
+
constraints.length > 0 ? { name, type, optional, constraints } : { name, type, optional }
|
|
380
|
+
);
|
|
366
381
|
}
|
|
367
382
|
if (ts2.isIndexSignatureDeclaration(member)) {
|
|
368
383
|
const keyType = member.parameters[0]?.type ? resolveTypeNode(member.parameters[0].type, checker, visited) : { kind: "any" };
|
|
@@ -375,6 +390,142 @@ function resolveInterfaceDeclaration(node, checker, visited = /* @__PURE__ */ ne
|
|
|
375
390
|
}
|
|
376
391
|
return { kind: "object", properties };
|
|
377
392
|
}
|
|
393
|
+
var NUMBER_CONSTRAINT_KINDS = /* @__PURE__ */ new Set([
|
|
394
|
+
"max",
|
|
395
|
+
"min",
|
|
396
|
+
"int",
|
|
397
|
+
"positive",
|
|
398
|
+
"negative",
|
|
399
|
+
"nonnegative",
|
|
400
|
+
"nonpositive"
|
|
401
|
+
]);
|
|
402
|
+
var LENGTH_CONSTRAINT_KINDS = /* @__PURE__ */ new Set([
|
|
403
|
+
"maxLength",
|
|
404
|
+
"minLength",
|
|
405
|
+
"length"
|
|
406
|
+
]);
|
|
407
|
+
var STRING_FORMAT_CONSTRAINT_KINDS = /* @__PURE__ */ new Set([
|
|
408
|
+
"regex",
|
|
409
|
+
"email",
|
|
410
|
+
"url",
|
|
411
|
+
"uuid"
|
|
412
|
+
]);
|
|
413
|
+
function extractConstraintsFromJsDoc(node, fieldName) {
|
|
414
|
+
const jsDocs = ts2.getJSDocCommentsAndTags(node).filter((entry) => ts2.isJSDoc(entry));
|
|
415
|
+
if (jsDocs.length === 0) return [];
|
|
416
|
+
const constraints = [];
|
|
417
|
+
for (const jsDoc of jsDocs) {
|
|
418
|
+
if (!jsDoc.tags) continue;
|
|
419
|
+
for (const tag of jsDoc.tags) {
|
|
420
|
+
const constraint = parseJsDocTag(tag, fieldName);
|
|
421
|
+
if (constraint) constraints.push(constraint);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return constraints;
|
|
425
|
+
}
|
|
426
|
+
function getTagCommentText(tag) {
|
|
427
|
+
const comment = tag.comment;
|
|
428
|
+
if (typeof comment === "string") return comment;
|
|
429
|
+
return void 0;
|
|
430
|
+
}
|
|
431
|
+
function parseJsDocTag(tag, fieldName) {
|
|
432
|
+
const tagName = tag.tagName.text;
|
|
433
|
+
switch (tagName) {
|
|
434
|
+
// 数值约束(带值)
|
|
435
|
+
case "max":
|
|
436
|
+
case "min": {
|
|
437
|
+
const value = parseNumberValue(tag, fieldName, tagName);
|
|
438
|
+
return { kind: tagName, value };
|
|
439
|
+
}
|
|
440
|
+
// 长度约束(带值)
|
|
441
|
+
case "maxLength":
|
|
442
|
+
case "minLength":
|
|
443
|
+
case "length": {
|
|
444
|
+
const value = parseNumberValue(tag, fieldName, tagName);
|
|
445
|
+
return { kind: tagName, value };
|
|
446
|
+
}
|
|
447
|
+
// 正则约束(带 /pattern/flags 值)
|
|
448
|
+
case "regex":
|
|
449
|
+
case "pattern": {
|
|
450
|
+
const text = getTagCommentText(tag);
|
|
451
|
+
if (!text) {
|
|
452
|
+
throw new SchemaExtractionError(fieldName, `@${tagName} \u6807\u7B7E\u9700\u8981 /pattern/flags \u5F62\u5F0F\u7684\u503C`);
|
|
453
|
+
}
|
|
454
|
+
const regex = parseRegexLiteral(text.trim(), fieldName);
|
|
455
|
+
return { kind: "regex", pattern: regex.pattern, flags: regex.flags };
|
|
456
|
+
}
|
|
457
|
+
// 数值约束(无值)
|
|
458
|
+
case "int":
|
|
459
|
+
case "positive":
|
|
460
|
+
case "negative":
|
|
461
|
+
case "nonnegative":
|
|
462
|
+
case "nonpositive":
|
|
463
|
+
return { kind: tagName };
|
|
464
|
+
// 字符串格式约束(无值)
|
|
465
|
+
case "email":
|
|
466
|
+
case "url":
|
|
467
|
+
case "uuid":
|
|
468
|
+
return { kind: tagName };
|
|
469
|
+
default:
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
function parseNumberValue(tag, fieldName, tagName) {
|
|
474
|
+
const text = getTagCommentText(tag);
|
|
475
|
+
if (!text) {
|
|
476
|
+
throw new SchemaExtractionError(fieldName, `@${tagName} \u6807\u7B7E\u9700\u8981\u4E00\u4E2A\u6570\u5B57\u503C`);
|
|
477
|
+
}
|
|
478
|
+
const trimmed = text.trim();
|
|
479
|
+
const num = Number(trimmed);
|
|
480
|
+
if (!Number.isFinite(num)) {
|
|
481
|
+
throw new SchemaExtractionError(fieldName, `@${tagName} \u6807\u7B7E\u7684\u503C "${trimmed}" \u4E0D\u662F\u6709\u6548\u6570\u5B57`);
|
|
482
|
+
}
|
|
483
|
+
return num;
|
|
484
|
+
}
|
|
485
|
+
function parseRegexLiteral(text, fieldName) {
|
|
486
|
+
const match = /^\/(.+)\/([gimsuy]*)$/.exec(text);
|
|
487
|
+
if (!match) {
|
|
488
|
+
throw new SchemaExtractionError(fieldName, `\u6B63\u5219\u503C "${text}" \u4E0D\u662F /pattern/flags \u5F62\u5F0F`);
|
|
489
|
+
}
|
|
490
|
+
const [, pattern, flags] = match;
|
|
491
|
+
if (!pattern) {
|
|
492
|
+
throw new SchemaExtractionError(fieldName, `\u6B63\u5219\u503C "${text}" \u7684 pattern \u90E8\u5206\u4E3A\u7A7A`);
|
|
493
|
+
}
|
|
494
|
+
return flags ? { pattern, flags } : { pattern };
|
|
495
|
+
}
|
|
496
|
+
function validateConstraints(constraints, type, fieldName) {
|
|
497
|
+
if (constraints.length === 0) return;
|
|
498
|
+
for (const constraint of constraints) {
|
|
499
|
+
const kind = constraint.kind;
|
|
500
|
+
if (NUMBER_CONSTRAINT_KINDS.has(kind)) {
|
|
501
|
+
if (type.kind !== "number") {
|
|
502
|
+
throw new SchemaExtractionError(
|
|
503
|
+
fieldName,
|
|
504
|
+
`@${kind} \u7EA6\u675F\u4EC5\u9002\u7528\u4E8E number \u5B57\u6BB5\uFF0C\u5B9E\u9645\u4E3A ${type.kind}`
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
if (LENGTH_CONSTRAINT_KINDS.has(kind)) {
|
|
510
|
+
if (type.kind !== "string" && type.kind !== "array") {
|
|
511
|
+
throw new SchemaExtractionError(
|
|
512
|
+
fieldName,
|
|
513
|
+
`@${kind} \u7EA6\u675F\u4EC5\u9002\u7528\u4E8E string \u6216 array \u5B57\u6BB5\uFF0C\u5B9E\u9645\u4E3A ${type.kind}`
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (STRING_FORMAT_CONSTRAINT_KINDS.has(kind)) {
|
|
519
|
+
if (type.kind !== "string") {
|
|
520
|
+
throw new SchemaExtractionError(
|
|
521
|
+
fieldName,
|
|
522
|
+
`@${kind} \u7EA6\u675F\u4EC5\u9002\u7528\u4E8E string \u5B57\u6BB5\uFF0C\u5B9E\u9645\u4E3A ${type.kind}`
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
378
529
|
|
|
379
530
|
// src/ast/extractHandlerTypes.ts
|
|
380
531
|
function extractTypeInfo(program, filePath, typeName) {
|
|
@@ -417,6 +568,45 @@ function extractTypeInfo(program, filePath, typeName) {
|
|
|
417
568
|
});
|
|
418
569
|
return result;
|
|
419
570
|
}
|
|
571
|
+
function extractAllTypes(program, filePath) {
|
|
572
|
+
const sourceFile = program.getSourceFile(filePath);
|
|
573
|
+
if (!sourceFile) return /* @__PURE__ */ new Map();
|
|
574
|
+
const checker = program.getTypeChecker();
|
|
575
|
+
const result = /* @__PURE__ */ new Map();
|
|
576
|
+
ts3.forEachChild(sourceFile, (node) => {
|
|
577
|
+
if (ts3.isInterfaceDeclaration(node)) {
|
|
578
|
+
const visited = /* @__PURE__ */ new Set();
|
|
579
|
+
visited.add(node.name.text);
|
|
580
|
+
const runtimeType = withFileContext(
|
|
581
|
+
filePath,
|
|
582
|
+
node.name.text,
|
|
583
|
+
() => resolveInterfaceDeclaration(node, checker, visited)
|
|
584
|
+
);
|
|
585
|
+
result.set(node.name.text, {
|
|
586
|
+
name: node.name.text,
|
|
587
|
+
properties: runtimeType.kind === "object" ? runtimeType.properties : [],
|
|
588
|
+
runtimeType
|
|
589
|
+
});
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
if (ts3.isTypeAliasDeclaration(node)) {
|
|
593
|
+
const visited = /* @__PURE__ */ new Set();
|
|
594
|
+
visited.add(node.name.text);
|
|
595
|
+
const runtimeType = withFileContext(
|
|
596
|
+
filePath,
|
|
597
|
+
node.name.text,
|
|
598
|
+
() => resolveTypeNode(node.type, checker, visited)
|
|
599
|
+
);
|
|
600
|
+
result.set(node.name.text, {
|
|
601
|
+
name: node.name.text,
|
|
602
|
+
properties: runtimeType.kind === "object" ? runtimeType.properties : [],
|
|
603
|
+
runtimeType
|
|
604
|
+
});
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
return result;
|
|
609
|
+
}
|
|
420
610
|
function withFileContext(filePath, typeName, fn) {
|
|
421
611
|
try {
|
|
422
612
|
return fn();
|
|
@@ -442,122 +632,187 @@ function getInputTypeForMethod(method) {
|
|
|
442
632
|
}
|
|
443
633
|
return "body";
|
|
444
634
|
}
|
|
635
|
+
function hasBody(method) {
|
|
636
|
+
const upper = method.toUpperCase();
|
|
637
|
+
return upper === "POST" || upper === "PUT" || upper === "PATCH" || upper === "DELETE";
|
|
638
|
+
}
|
|
445
639
|
|
|
446
|
-
// src/validator/
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
640
|
+
// src/validator/schemaName.ts
|
|
641
|
+
function getSchemaName(method, inputType) {
|
|
642
|
+
return `${method.toUpperCase()}${inputType.charAt(0).toUpperCase() + inputType.slice(1)}`;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// src/injection/analyzeInjection.ts
|
|
646
|
+
import ts5 from "typescript";
|
|
647
|
+
|
|
648
|
+
// src/injection/resolveInjection.ts
|
|
649
|
+
import ts4 from "typescript";
|
|
650
|
+
var PARAM_TYPE_MAP = {
|
|
651
|
+
query: "query",
|
|
652
|
+
body: "body",
|
|
653
|
+
headers: "headers",
|
|
654
|
+
params: "params",
|
|
655
|
+
context: "context",
|
|
656
|
+
ctx: "context",
|
|
657
|
+
// 别名
|
|
658
|
+
cookies: "cookies",
|
|
659
|
+
ip: "ip",
|
|
660
|
+
files: "files",
|
|
661
|
+
fields: "fields"
|
|
662
|
+
};
|
|
663
|
+
function resolveInjection(fn) {
|
|
664
|
+
const fnStr = fn.toString();
|
|
665
|
+
const params = extractParamsWithAst(fnStr);
|
|
666
|
+
return params.map((param) => {
|
|
667
|
+
const type = PARAM_TYPE_MAP[param.name] || "unknown";
|
|
668
|
+
return {
|
|
669
|
+
name: param.name,
|
|
670
|
+
type,
|
|
671
|
+
hasType: false
|
|
672
|
+
// 运行时类型已擦除
|
|
673
|
+
};
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
function extractParamsWithAst(fnStr) {
|
|
677
|
+
const sourceFile = ts4.createSourceFile(
|
|
678
|
+
"__faapi_injection__.ts",
|
|
679
|
+
fnStr,
|
|
680
|
+
ts4.ScriptTarget.Latest,
|
|
681
|
+
true
|
|
682
|
+
);
|
|
683
|
+
const paramNames = [];
|
|
684
|
+
function visit(node) {
|
|
685
|
+
if (ts4.isFunctionDeclaration(node) && node.parameters.length > 0) {
|
|
686
|
+
for (const param of node.parameters) {
|
|
687
|
+
extractParamName(param, paramNames);
|
|
688
|
+
}
|
|
689
|
+
return;
|
|
459
690
|
}
|
|
691
|
+
if ((ts4.isArrowFunction(node) || ts4.isFunctionExpression(node)) && node.parameters.length > 0) {
|
|
692
|
+
for (const param of node.parameters) {
|
|
693
|
+
extractParamName(param, paramNames);
|
|
694
|
+
}
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
ts4.forEachChild(node, visit);
|
|
460
698
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
const fileSchemas = this.manifest.get(filePath);
|
|
470
|
-
if (!fileSchemas) return void 0;
|
|
471
|
-
return fileSchemas.get(schemaName);
|
|
472
|
-
}
|
|
473
|
-
/**
|
|
474
|
-
* 设置单个文件的所有 schema
|
|
475
|
-
* 覆盖该文件的已有数据
|
|
476
|
-
*/
|
|
477
|
-
set(filePath, schemas) {
|
|
478
|
-
const copy = /* @__PURE__ */ new Map();
|
|
479
|
-
schemas.forEach((value, key) => copy.set(key, value));
|
|
480
|
-
this.manifest.set(filePath, copy);
|
|
699
|
+
visit(sourceFile);
|
|
700
|
+
return paramNames.map((name) => ({ name }));
|
|
701
|
+
}
|
|
702
|
+
function extractParamName(param, names) {
|
|
703
|
+
const name = param.name;
|
|
704
|
+
if (ts4.isIdentifier(name)) {
|
|
705
|
+
names.push(name.text);
|
|
706
|
+
return;
|
|
481
707
|
}
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
708
|
+
if (ts4.isObjectBindingPattern(name)) {
|
|
709
|
+
for (const element of name.elements) {
|
|
710
|
+
if (ts4.isBindingElement(element)) {
|
|
711
|
+
const elemName = element.name;
|
|
712
|
+
if (ts4.isIdentifier(elemName)) {
|
|
713
|
+
names.push(elemName.text);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
return;
|
|
487
718
|
}
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
719
|
+
if (ts4.isArrayBindingPattern(name)) {
|
|
720
|
+
for (const element of name.elements) {
|
|
721
|
+
if (element && ts4.isBindingElement(element)) {
|
|
722
|
+
const elemName = element.name;
|
|
723
|
+
if (ts4.isIdentifier(elemName)) {
|
|
724
|
+
names.push(elemName.text);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return;
|
|
493
729
|
}
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// src/injection/analyzeInjection.ts
|
|
733
|
+
function analyzeInjection(code, functionName) {
|
|
734
|
+
const sourceFile = ts5.createSourceFile("temp.ts", code, ts5.ScriptTarget.Latest, true);
|
|
735
|
+
const params = [];
|
|
736
|
+
ts5.forEachChild(sourceFile, (node) => {
|
|
737
|
+
if (ts5.isFunctionDeclaration(node) && node.name?.text === functionName) {
|
|
738
|
+
for (const param of node.parameters) {
|
|
739
|
+
const paramMeta = analyzeParam(param, sourceFile);
|
|
740
|
+
params.push(paramMeta);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
});
|
|
744
|
+
return { params };
|
|
745
|
+
}
|
|
746
|
+
function analyzeParam(param, sourceFile) {
|
|
747
|
+
const name = param.name.getText(sourceFile);
|
|
748
|
+
const type = PARAM_TYPE_MAP[name] || "unknown";
|
|
749
|
+
const result = { name, type };
|
|
750
|
+
if (param.type) {
|
|
751
|
+
if (ts5.isTypeReferenceNode(param.type)) {
|
|
752
|
+
result.typeName = param.type.typeName.getText(sourceFile);
|
|
753
|
+
} else if (ts5.isTypeLiteralNode(param.type)) {
|
|
754
|
+
result.schema = extractSchema(param.type, sourceFile);
|
|
755
|
+
}
|
|
499
756
|
}
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
757
|
+
return result;
|
|
758
|
+
}
|
|
759
|
+
function extractSchema(typeNode, sourceFile) {
|
|
760
|
+
const schema = [];
|
|
761
|
+
for (const member of typeNode.members) {
|
|
762
|
+
if (ts5.isPropertySignature(member) && member.name && ts5.isIdentifier(member.name)) {
|
|
763
|
+
const propName = member.name.text;
|
|
764
|
+
const optional = !!member.questionToken;
|
|
765
|
+
const propType = member.type?.getText(sourceFile) || "unknown";
|
|
766
|
+
schema.push({
|
|
767
|
+
name: propName,
|
|
768
|
+
type: propType,
|
|
769
|
+
optional
|
|
770
|
+
});
|
|
771
|
+
}
|
|
505
772
|
}
|
|
506
|
-
|
|
507
|
-
var schemaRegistry = new SchemaRegistry();
|
|
508
|
-
|
|
509
|
-
// src/validator/schemaName.ts
|
|
510
|
-
function getSchemaName(method, inputType) {
|
|
511
|
-
return `${method.toUpperCase()}${inputType.charAt(0).toUpperCase() + inputType.slice(1)}`;
|
|
773
|
+
return schema;
|
|
512
774
|
}
|
|
513
775
|
|
|
514
|
-
// src/
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
const
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
776
|
+
// src/cli/collectRouteSchemaSources.ts
|
|
777
|
+
import path from "path";
|
|
778
|
+
function collectRouteSchemaSources(routes, rootDir) {
|
|
779
|
+
const methodsByFile = /* @__PURE__ */ new Map();
|
|
780
|
+
for (const route of routes) {
|
|
781
|
+
const filePath = rootDir ? path.resolve(rootDir, route.filePath) : route.filePath;
|
|
782
|
+
let entry = methodsByFile.get(filePath);
|
|
783
|
+
if (!entry) {
|
|
784
|
+
entry = { urlPath: route.urlPath, methods: /* @__PURE__ */ new Set() };
|
|
785
|
+
methodsByFile.set(filePath, entry);
|
|
786
|
+
}
|
|
787
|
+
entry.methods.add(route.method);
|
|
521
788
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
case "string":
|
|
534
|
-
case "number":
|
|
535
|
-
case "boolean":
|
|
536
|
-
case "bigint":
|
|
537
|
-
case "null":
|
|
538
|
-
case "undefined":
|
|
539
|
-
case "date":
|
|
540
|
-
return type.kind;
|
|
541
|
-
case "literal":
|
|
542
|
-
return JSON.stringify(type.value);
|
|
543
|
-
case "array":
|
|
544
|
-
return `${runtimeTypeToString(type.element)}[]`;
|
|
545
|
-
case "tuple":
|
|
546
|
-
return `[${type.elements.map((e) => (e.rest ? "..." : "") + runtimeTypeToString(e.type) + (e.optional ? "?" : "")).join(", ")}]`;
|
|
547
|
-
case "object":
|
|
548
|
-
return "object";
|
|
549
|
-
case "union":
|
|
550
|
-
return type.members.map(runtimeTypeToString).join(" | ");
|
|
551
|
-
case "record":
|
|
552
|
-
return `Record<${runtimeTypeToString(type.key)}, ${runtimeTypeToString(type.value)}>`;
|
|
553
|
-
case "ref":
|
|
554
|
-
return type.name;
|
|
555
|
-
case "any":
|
|
556
|
-
case "unknown":
|
|
557
|
-
return "unknown";
|
|
558
|
-
default:
|
|
559
|
-
return "unknown";
|
|
789
|
+
const programByFile = /* @__PURE__ */ new Map();
|
|
790
|
+
const allTypesByFile = /* @__PURE__ */ new Map();
|
|
791
|
+
const mergedAllTypes = /* @__PURE__ */ new Map();
|
|
792
|
+
for (const filePath of methodsByFile.keys()) {
|
|
793
|
+
const program = createProgram(filePath);
|
|
794
|
+
programByFile.set(filePath, program);
|
|
795
|
+
const allTypes = extractAllTypes(program, filePath);
|
|
796
|
+
allTypesByFile.set(filePath, allTypes);
|
|
797
|
+
for (const [name, info] of allTypes) {
|
|
798
|
+
mergedAllTypes.set(name, info);
|
|
799
|
+
}
|
|
560
800
|
}
|
|
801
|
+
const sources = [];
|
|
802
|
+
for (const [filePath, entry] of methodsByFile) {
|
|
803
|
+
const program = programByFile.get(filePath);
|
|
804
|
+
const sourceFile = program.getSourceFile(filePath);
|
|
805
|
+
const code = sourceFile?.text ?? "";
|
|
806
|
+
for (const method of entry.methods) {
|
|
807
|
+
const inputType = getInputTypeForMethod(method);
|
|
808
|
+
const schemaName = getSchemaName(method, inputType);
|
|
809
|
+
const meta = analyzeInjection(code, method);
|
|
810
|
+
const param = meta.params.find((p) => p.type === inputType);
|
|
811
|
+
const typeInfo = param?.typeName ? extractTypeInfo(program, filePath, param.typeName) : null;
|
|
812
|
+
sources.push({ urlPath: entry.urlPath, filePath, schemaName, typeInfo });
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
return { sources, allTypesByFile, mergedAllTypes };
|
|
561
816
|
}
|
|
562
817
|
|
|
563
818
|
// src/middleware/cors.ts
|
|
@@ -633,97 +888,2444 @@ function logger(options = {}) {
|
|
|
633
888
|
try {
|
|
634
889
|
const response = await next();
|
|
635
890
|
const duration = Date.now() - start;
|
|
636
|
-
|
|
891
|
+
const entry = {
|
|
892
|
+
method: ctx.method,
|
|
893
|
+
path: ctx.path,
|
|
894
|
+
status: response.status,
|
|
895
|
+
durationMs: duration
|
|
896
|
+
};
|
|
897
|
+
log(entry, `${ctx.method} ${ctx.path} ${response.status} ${duration}ms`);
|
|
637
898
|
return response;
|
|
638
899
|
} catch (err) {
|
|
639
900
|
const duration = Date.now() - start;
|
|
640
901
|
const message = err instanceof Error ? err.message : String(err);
|
|
641
902
|
const status = err?.statusCode ?? 500;
|
|
642
|
-
|
|
903
|
+
const entry = {
|
|
904
|
+
method: ctx.method,
|
|
905
|
+
path: ctx.path,
|
|
906
|
+
status,
|
|
907
|
+
durationMs: duration,
|
|
908
|
+
error: message
|
|
909
|
+
};
|
|
910
|
+
log(entry, `${ctx.method} ${ctx.path} ${status} ${duration}ms - ${message}`);
|
|
643
911
|
throw err;
|
|
644
912
|
}
|
|
645
913
|
};
|
|
646
914
|
}
|
|
647
915
|
|
|
916
|
+
// src/middleware/helmet.ts
|
|
917
|
+
var DEFAULTS = {
|
|
918
|
+
contentSecurityPolicy: "default-src 'self'",
|
|
919
|
+
xFrameOptions: "SAMEORIGIN",
|
|
920
|
+
xContentTypeOptions: true,
|
|
921
|
+
referrerPolicy: "no-referrer",
|
|
922
|
+
strictTransportSecurity: "max-age=31536000; includeSubDomains",
|
|
923
|
+
xDnsPrefetchControl: true,
|
|
924
|
+
xDownloadOptions: true,
|
|
925
|
+
xPermittedCrossDomainPolicies: "none",
|
|
926
|
+
crossOriginOpenerPolicy: "same-origin",
|
|
927
|
+
crossOriginResourcePolicy: "same-origin",
|
|
928
|
+
crossOriginEmbedderPolicy: false,
|
|
929
|
+
originAgentCluster: true,
|
|
930
|
+
xPoweredBy: true
|
|
931
|
+
};
|
|
932
|
+
function helmet(options = {}) {
|
|
933
|
+
const opts = { ...DEFAULTS, ...options };
|
|
934
|
+
return async (ctx, next) => {
|
|
935
|
+
if (opts.contentSecurityPolicy !== false) {
|
|
936
|
+
ctx.setHeader("Content-Security-Policy", opts.contentSecurityPolicy);
|
|
937
|
+
}
|
|
938
|
+
if (opts.xFrameOptions !== false) {
|
|
939
|
+
ctx.setHeader("X-Frame-Options", opts.xFrameOptions);
|
|
940
|
+
}
|
|
941
|
+
if (opts.xContentTypeOptions) {
|
|
942
|
+
ctx.setHeader("X-Content-Type-Options", "nosniff");
|
|
943
|
+
}
|
|
944
|
+
if (opts.referrerPolicy !== false) {
|
|
945
|
+
ctx.setHeader("Referrer-Policy", opts.referrerPolicy);
|
|
946
|
+
}
|
|
947
|
+
if (opts.strictTransportSecurity !== false) {
|
|
948
|
+
ctx.setHeader("Strict-Transport-Security", opts.strictTransportSecurity);
|
|
949
|
+
}
|
|
950
|
+
if (opts.xDnsPrefetchControl) {
|
|
951
|
+
ctx.setHeader("X-DNS-Prefetch-Control", "off");
|
|
952
|
+
}
|
|
953
|
+
if (opts.xDownloadOptions) {
|
|
954
|
+
ctx.setHeader("X-Download-Options", "noopen");
|
|
955
|
+
}
|
|
956
|
+
if (opts.xPermittedCrossDomainPolicies !== false) {
|
|
957
|
+
ctx.setHeader("X-Permitted-Cross-Domain-Policies", opts.xPermittedCrossDomainPolicies);
|
|
958
|
+
}
|
|
959
|
+
if (opts.crossOriginOpenerPolicy !== false) {
|
|
960
|
+
ctx.setHeader("Cross-Origin-Opener-Policy", opts.crossOriginOpenerPolicy);
|
|
961
|
+
}
|
|
962
|
+
if (opts.crossOriginResourcePolicy !== false) {
|
|
963
|
+
ctx.setHeader("Cross-Origin-Resource-Policy", opts.crossOriginResourcePolicy);
|
|
964
|
+
}
|
|
965
|
+
if (opts.crossOriginEmbedderPolicy !== false) {
|
|
966
|
+
ctx.setHeader("Cross-Origin-Embedder-Policy", opts.crossOriginEmbedderPolicy);
|
|
967
|
+
}
|
|
968
|
+
if (opts.originAgentCluster) {
|
|
969
|
+
ctx.setHeader("Origin-Agent-Cluster", "?1");
|
|
970
|
+
}
|
|
971
|
+
if (opts.xPoweredBy) {
|
|
972
|
+
ctx.setHeader("X-Powered-By", "faapi");
|
|
973
|
+
}
|
|
974
|
+
return await next();
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
|
|
648
978
|
// src/config/loadConfig.ts
|
|
649
|
-
import
|
|
979
|
+
import path2 from "path";
|
|
650
980
|
import fs from "fs";
|
|
981
|
+
|
|
982
|
+
// src/utils/importWithCacheBust.ts
|
|
651
983
|
import { pathToFileURL } from "url";
|
|
652
|
-
var
|
|
653
|
-
function
|
|
654
|
-
|
|
655
|
-
}
|
|
656
|
-
function
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
984
|
+
var loadTs;
|
|
985
|
+
function setLoadTimestamp(ts6) {
|
|
986
|
+
loadTs = ts6;
|
|
987
|
+
}
|
|
988
|
+
async function importWithCacheBust(filePath) {
|
|
989
|
+
let url = pathToFileURL(filePath).href;
|
|
990
|
+
if (loadTs !== void 0) {
|
|
991
|
+
url += `?t=${loadTs}`;
|
|
992
|
+
}
|
|
993
|
+
return await import(url);
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// src/config/loadConfig.ts
|
|
997
|
+
var CONFIG_PRODUCT_FILE = "faapi-config.js";
|
|
998
|
+
async function loadConfig(rootDir, outDir) {
|
|
999
|
+
const configProductPath = path2.resolve(rootDir, outDir, CONFIG_PRODUCT_FILE);
|
|
1000
|
+
if (fs.existsSync(configProductPath)) {
|
|
1001
|
+
const module = await importWithCacheBust(configProductPath);
|
|
1002
|
+
return module.default ?? {};
|
|
1003
|
+
}
|
|
1004
|
+
const hasSourceConfig = fs.existsSync(path2.join(rootDir, "faapi.config.ts")) || fs.existsSync(path2.join(rootDir, "faapi.config.js"));
|
|
1005
|
+
if (hasSourceConfig) {
|
|
1006
|
+
throw new Error(
|
|
1007
|
+
`[faapi] ${outDir}/${CONFIG_PRODUCT_FILE} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6267\u884C \`faapi build\`\uFF08\u6216 \`faapi dev\`\uFF09\u751F\u6210\u4EA7\u7269\u3002`
|
|
1008
|
+
);
|
|
1009
|
+
}
|
|
1010
|
+
return null;
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
// src/errors/FaapiError.ts
|
|
1014
|
+
var FaapiError = class extends Error {
|
|
1015
|
+
constructor(code, message, statusCode) {
|
|
1016
|
+
super(message);
|
|
1017
|
+
this.code = code;
|
|
1018
|
+
this.statusCode = statusCode;
|
|
1019
|
+
this.name = "FaapiError";
|
|
1020
|
+
}
|
|
1021
|
+
code;
|
|
1022
|
+
statusCode;
|
|
1023
|
+
};
|
|
1024
|
+
|
|
1025
|
+
// src/errors/httpErrors.ts
|
|
1026
|
+
function deriveStatusCode(issues) {
|
|
1027
|
+
const has400 = issues.some((i) => i.code === "INVALID_FORMAT" || i.code === "MISSING_FIELD");
|
|
1028
|
+
return has400 ? 400 : 422;
|
|
1029
|
+
}
|
|
1030
|
+
var ValidationError = class extends FaapiError {
|
|
1031
|
+
constructor(message, issues) {
|
|
1032
|
+
super("VALIDATION_ERROR", message, deriveStatusCode(issues));
|
|
1033
|
+
this.issues = issues;
|
|
1034
|
+
this.name = "ValidationError";
|
|
1035
|
+
}
|
|
1036
|
+
issues;
|
|
1037
|
+
};
|
|
1038
|
+
var RouteNotFoundError = class extends FaapiError {
|
|
1039
|
+
constructor(path9) {
|
|
1040
|
+
super("ROUTE_NOT_FOUND", `Route not found: ${path9}`, 404);
|
|
1041
|
+
this.name = "RouteNotFoundError";
|
|
1042
|
+
}
|
|
1043
|
+
};
|
|
1044
|
+
var MethodNotAllowedError = class extends FaapiError {
|
|
1045
|
+
constructor(method, path9, allowedMethods) {
|
|
1046
|
+
super("METHOD_NOT_ALLOWED", `Method ${method} not allowed for ${path9}`, 405);
|
|
1047
|
+
this.allowedMethods = allowedMethods;
|
|
1048
|
+
this.name = "MethodNotAllowedError";
|
|
1049
|
+
}
|
|
1050
|
+
allowedMethods;
|
|
1051
|
+
};
|
|
1052
|
+
var InternalError = class extends FaapiError {
|
|
1053
|
+
constructor(message) {
|
|
1054
|
+
super("INTERNAL_ERROR", message, 500);
|
|
1055
|
+
this.name = "InternalError";
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
var ModuleLoadError = class extends FaapiError {
|
|
1059
|
+
constructor(filePath, reason) {
|
|
1060
|
+
super("MODULE_LOAD_ERROR", `Failed to load module ${filePath}: ${reason}`, 500);
|
|
1061
|
+
this.name = "ModuleLoadError";
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
// src/cli/createAppCore.ts
|
|
1066
|
+
import fs4 from "fs";
|
|
1067
|
+
import path7 from "path";
|
|
1068
|
+
import { PassThrough } from "stream";
|
|
1069
|
+
|
|
1070
|
+
// src/router/sortRoutes.ts
|
|
1071
|
+
function sortRoutes(routes) {
|
|
1072
|
+
return [...routes].sort((a, b) => {
|
|
1073
|
+
if (a.isDynamic !== b.isDynamic) {
|
|
1074
|
+
return a.isDynamic ? 1 : -1;
|
|
664
1075
|
}
|
|
665
|
-
if (
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
1076
|
+
if (a.isCatchAll !== b.isCatchAll) {
|
|
1077
|
+
return a.isCatchAll ? 1 : -1;
|
|
1078
|
+
}
|
|
1079
|
+
const aSegments = a.urlPath.split("/").filter(Boolean).length;
|
|
1080
|
+
const bSegments = b.urlPath.split("/").filter(Boolean).length;
|
|
1081
|
+
if (aSegments !== bSegments) {
|
|
1082
|
+
return aSegments - bSegments;
|
|
1083
|
+
}
|
|
1084
|
+
return a.urlPath.localeCompare(b.urlPath);
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// src/router/detectRouteConflicts.ts
|
|
1089
|
+
function detectRouteConflicts(routes) {
|
|
1090
|
+
const map = /* @__PURE__ */ new Map();
|
|
1091
|
+
for (const route of routes) {
|
|
1092
|
+
const key = `${route.method} ${route.urlPath}`;
|
|
1093
|
+
const existing = map.get(key);
|
|
1094
|
+
if (existing) {
|
|
1095
|
+
existing.files.push(route.filePath);
|
|
670
1096
|
} else {
|
|
671
|
-
|
|
1097
|
+
map.set(key, {
|
|
1098
|
+
method: route.method,
|
|
1099
|
+
urlPath: route.urlPath,
|
|
1100
|
+
files: [route.filePath]
|
|
1101
|
+
});
|
|
672
1102
|
}
|
|
673
1103
|
}
|
|
674
|
-
|
|
1104
|
+
const conflicts = [];
|
|
1105
|
+
for (const conflict of map.values()) {
|
|
1106
|
+
if (conflict.files.length > 1) {
|
|
1107
|
+
conflicts.push(conflict);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
return conflicts;
|
|
675
1111
|
}
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
1112
|
+
|
|
1113
|
+
// src/server/createServer.ts
|
|
1114
|
+
import {
|
|
1115
|
+
createServer as createHttpServer
|
|
1116
|
+
} from "http";
|
|
1117
|
+
import { createSecureServer as createHttp2SecureServer } from "http2";
|
|
1118
|
+
import { readFileSync } from "fs";
|
|
1119
|
+
import { Readable as Readable2 } from "stream";
|
|
1120
|
+
import path5 from "path";
|
|
1121
|
+
|
|
1122
|
+
// src/router/matchRoute.ts
|
|
1123
|
+
function matchRoute(routes, method, path9) {
|
|
1124
|
+
for (const route of routes) {
|
|
1125
|
+
if (route.method !== method) {
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
if (!route.isDynamic) {
|
|
1129
|
+
if (route.urlPath === path9) {
|
|
1130
|
+
return { route, params: {} };
|
|
1131
|
+
}
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
const params = matchDynamicPath(route.urlPath, path9, route.paramNames, route.isCatchAll);
|
|
1135
|
+
if (params !== null) {
|
|
1136
|
+
return { route, params };
|
|
1137
|
+
}
|
|
679
1138
|
}
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
1139
|
+
return null;
|
|
1140
|
+
}
|
|
1141
|
+
function matchWsRoute(wsRoutes, path9) {
|
|
1142
|
+
for (const route of wsRoutes) {
|
|
1143
|
+
if (!route.isDynamic) {
|
|
1144
|
+
if (route.urlPath === path9) {
|
|
1145
|
+
return { route, params: {} };
|
|
1146
|
+
}
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
const params = matchDynamicPath(route.urlPath, path9, route.paramNames, route.isCatchAll);
|
|
1150
|
+
if (params !== null) {
|
|
1151
|
+
return { route, params };
|
|
1152
|
+
}
|
|
689
1153
|
}
|
|
1154
|
+
return null;
|
|
690
1155
|
}
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
1156
|
+
function matchDynamicPath(pattern, path9, paramNames, isCatchAll) {
|
|
1157
|
+
const patternSegments = pattern.split("/").filter(Boolean);
|
|
1158
|
+
const pathSegments = path9.split("/").filter(Boolean);
|
|
1159
|
+
if (isCatchAll) {
|
|
1160
|
+
const nonCatchAllCount = patternSegments.length - 1;
|
|
1161
|
+
if (pathSegments.length <= nonCatchAllCount) {
|
|
1162
|
+
return null;
|
|
1163
|
+
}
|
|
1164
|
+
const params2 = {};
|
|
1165
|
+
for (let i = 0; i < nonCatchAllCount; i++) {
|
|
1166
|
+
const patternSeg = patternSegments[i];
|
|
1167
|
+
const pathSeg = pathSegments[i];
|
|
1168
|
+
if (patternSeg.startsWith(":")) {
|
|
1169
|
+
const paramName = patternSeg.slice(1);
|
|
1170
|
+
params2[paramName] = pathSeg;
|
|
1171
|
+
} else if (patternSeg !== pathSeg) {
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
const catchAllValue = pathSegments.slice(nonCatchAllCount).join("/");
|
|
1176
|
+
const catchAllParamName = patternSegments[nonCatchAllCount].slice(4);
|
|
1177
|
+
params2[catchAllParamName] = catchAllValue;
|
|
1178
|
+
if (Object.keys(params2).length !== paramNames.length) {
|
|
1179
|
+
return null;
|
|
696
1180
|
}
|
|
697
|
-
return
|
|
1181
|
+
return params2;
|
|
698
1182
|
}
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
1183
|
+
if (patternSegments.length !== pathSegments.length) {
|
|
1184
|
+
return null;
|
|
1185
|
+
}
|
|
1186
|
+
const params = {};
|
|
1187
|
+
for (let i = 0; i < patternSegments.length; i++) {
|
|
1188
|
+
const patternSeg = patternSegments[i];
|
|
1189
|
+
const pathSeg = pathSegments[i];
|
|
1190
|
+
if (patternSeg.startsWith(":")) {
|
|
1191
|
+
const paramName = patternSeg.slice(1);
|
|
1192
|
+
params[paramName] = pathSeg;
|
|
1193
|
+
} else if (patternSeg !== pathSeg) {
|
|
1194
|
+
return null;
|
|
1195
|
+
}
|
|
704
1196
|
}
|
|
705
|
-
if (
|
|
1197
|
+
if (Object.keys(params).length !== paramNames.length) {
|
|
706
1198
|
return null;
|
|
707
1199
|
}
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
1200
|
+
return params;
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// src/loader/resolveExports.ts
|
|
1204
|
+
function resolveExport(module, exportName) {
|
|
1205
|
+
if (exportName in module && typeof module[exportName] !== "undefined") {
|
|
1206
|
+
return module[exportName];
|
|
1207
|
+
}
|
|
1208
|
+
const defaultExport = module.default;
|
|
1209
|
+
if (defaultExport !== null && typeof defaultExport === "object") {
|
|
1210
|
+
const value = defaultExport[exportName];
|
|
1211
|
+
if (value !== void 0) {
|
|
1212
|
+
return value;
|
|
715
1213
|
}
|
|
716
1214
|
}
|
|
717
|
-
return
|
|
1215
|
+
return void 0;
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// src/loader/validateRouteModule.ts
|
|
1219
|
+
function validateRouteModule(value, method, filePath) {
|
|
1220
|
+
if (typeof value !== "function") {
|
|
1221
|
+
throw new Error(
|
|
1222
|
+
`Route module "${filePath}" does not export a valid handler for method "${method}". Expected a function, got ${typeof value}.`
|
|
1223
|
+
);
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// src/loader/loadRouteModule.ts
|
|
1228
|
+
async function loadRouteModule(filePath, method) {
|
|
1229
|
+
let module;
|
|
1230
|
+
try {
|
|
1231
|
+
module = await importWithCacheBust(filePath);
|
|
1232
|
+
} catch (err) {
|
|
1233
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
1234
|
+
throw new Error(`Failed to load route module "${filePath}": ${reason}`, { cause: err });
|
|
1235
|
+
}
|
|
1236
|
+
const handler = resolveExport(module, method);
|
|
1237
|
+
validateRouteModule(handler, method, filePath);
|
|
1238
|
+
return { handler, method };
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// src/runtime/sse.ts
|
|
1242
|
+
function encodeSseEvent(event) {
|
|
1243
|
+
let out = "";
|
|
1244
|
+
if (event.comment !== void 0) {
|
|
1245
|
+
out += `: ${event.comment}
|
|
1246
|
+
`;
|
|
1247
|
+
}
|
|
1248
|
+
if (event.event !== void 0) {
|
|
1249
|
+
out += `event: ${event.event}
|
|
1250
|
+
`;
|
|
1251
|
+
}
|
|
1252
|
+
if (event.id !== void 0) {
|
|
1253
|
+
out += `id: ${event.id}
|
|
1254
|
+
`;
|
|
1255
|
+
}
|
|
1256
|
+
if (event.retry !== void 0) {
|
|
1257
|
+
out += `retry: ${event.retry}
|
|
1258
|
+
`;
|
|
1259
|
+
}
|
|
1260
|
+
if (event.data !== void 0) {
|
|
1261
|
+
let dataStr;
|
|
1262
|
+
if (typeof event.data === "string") {
|
|
1263
|
+
dataStr = event.data;
|
|
1264
|
+
} else if (event.data === null) {
|
|
1265
|
+
dataStr = "null";
|
|
1266
|
+
} else {
|
|
1267
|
+
dataStr = JSON.stringify(event.data);
|
|
1268
|
+
}
|
|
1269
|
+
const lines = dataStr.split("\n");
|
|
1270
|
+
for (const line of lines) {
|
|
1271
|
+
out += `data: ${line}
|
|
1272
|
+
`;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
out += "\n";
|
|
1276
|
+
return out;
|
|
1277
|
+
}
|
|
1278
|
+
function createSseWriter() {
|
|
1279
|
+
const encoder = new TextEncoder();
|
|
1280
|
+
let controller = null;
|
|
1281
|
+
let closed = false;
|
|
1282
|
+
let aborted = false;
|
|
1283
|
+
const stream = new ReadableStream({
|
|
1284
|
+
start(c) {
|
|
1285
|
+
controller = c;
|
|
1286
|
+
},
|
|
1287
|
+
cancel() {
|
|
1288
|
+
aborted = true;
|
|
1289
|
+
closed = true;
|
|
1290
|
+
controller = null;
|
|
1291
|
+
}
|
|
1292
|
+
});
|
|
1293
|
+
const response = new Response(stream, {
|
|
1294
|
+
status: 200,
|
|
1295
|
+
headers: {
|
|
1296
|
+
"Content-Type": "text/event-stream",
|
|
1297
|
+
"Cache-Control": "no-cache",
|
|
1298
|
+
Connection: "keep-alive"
|
|
1299
|
+
}
|
|
1300
|
+
});
|
|
1301
|
+
const writer = {
|
|
1302
|
+
send(event) {
|
|
1303
|
+
if (closed || !controller) return;
|
|
1304
|
+
const text = encodeSseEvent(event);
|
|
1305
|
+
controller.enqueue(encoder.encode(text));
|
|
1306
|
+
},
|
|
1307
|
+
sendError(error) {
|
|
1308
|
+
if (closed || !controller) return;
|
|
1309
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1310
|
+
const text = encodeSseEvent({ event: "error", data: message });
|
|
1311
|
+
try {
|
|
1312
|
+
controller.enqueue(encoder.encode(text));
|
|
1313
|
+
} finally {
|
|
1314
|
+
writer.close();
|
|
1315
|
+
}
|
|
1316
|
+
},
|
|
1317
|
+
close() {
|
|
1318
|
+
if (closed) return;
|
|
1319
|
+
closed = true;
|
|
1320
|
+
if (controller) {
|
|
1321
|
+
try {
|
|
1322
|
+
controller.close();
|
|
1323
|
+
} catch {
|
|
1324
|
+
}
|
|
1325
|
+
controller = null;
|
|
1326
|
+
}
|
|
1327
|
+
},
|
|
1328
|
+
get closed() {
|
|
1329
|
+
return closed;
|
|
1330
|
+
},
|
|
1331
|
+
get aborted() {
|
|
1332
|
+
return aborted;
|
|
1333
|
+
},
|
|
1334
|
+
get response() {
|
|
1335
|
+
return response;
|
|
1336
|
+
}
|
|
1337
|
+
};
|
|
1338
|
+
return writer;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
// src/runtime/createContext.ts
|
|
1342
|
+
function parseCookies(cookieHeader) {
|
|
1343
|
+
const cookies = /* @__PURE__ */ new Map();
|
|
1344
|
+
if (!cookieHeader) return cookies;
|
|
1345
|
+
for (const pair of cookieHeader.split(";")) {
|
|
1346
|
+
const [name, ...rest] = pair.split("=");
|
|
1347
|
+
const trimmed = name?.trim();
|
|
1348
|
+
if (trimmed) {
|
|
1349
|
+
cookies.set(trimmed, rest.join("=").trim());
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return cookies;
|
|
1353
|
+
}
|
|
1354
|
+
function formatSetCookie(name, value, options) {
|
|
1355
|
+
let cookie = `${name}=${value}`;
|
|
1356
|
+
if (options?.domain) cookie += `; Domain=${options.domain}`;
|
|
1357
|
+
if (options?.path) cookie += `; Path=${options.path}`;
|
|
1358
|
+
if (options?.maxAge !== void 0) cookie += `; Max-Age=${options.maxAge}`;
|
|
1359
|
+
if (options?.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
|
|
1360
|
+
if (options?.httpOnly) cookie += `; HttpOnly`;
|
|
1361
|
+
if (options?.secure) cookie += `; Secure`;
|
|
1362
|
+
if (options?.sameSite) cookie += `; SameSite=${options.sameSite}`;
|
|
1363
|
+
return cookie;
|
|
1364
|
+
}
|
|
1365
|
+
function createContext(request, params, config = {}, ip = "") {
|
|
1366
|
+
const url = new URL(request.url);
|
|
1367
|
+
const meta = { headers: {}, setCookies: [] };
|
|
1368
|
+
const parsedCookies = parseCookies(request.headers.get("cookie") ?? "");
|
|
1369
|
+
const cookiesObj = {};
|
|
1370
|
+
for (const [key, val] of parsedCookies) {
|
|
1371
|
+
cookiesObj[key] = val;
|
|
1372
|
+
}
|
|
1373
|
+
const ctx = {
|
|
1374
|
+
request,
|
|
1375
|
+
params,
|
|
1376
|
+
query: url.searchParams,
|
|
1377
|
+
headers: request.headers,
|
|
1378
|
+
method: request.method,
|
|
1379
|
+
path: url.pathname,
|
|
1380
|
+
ip,
|
|
1381
|
+
cookies: cookiesObj,
|
|
1382
|
+
config,
|
|
1383
|
+
meta,
|
|
1384
|
+
setStatus(status) {
|
|
1385
|
+
meta.status = status;
|
|
1386
|
+
},
|
|
1387
|
+
setHeader(key, value) {
|
|
1388
|
+
meta.headers[key] = value;
|
|
1389
|
+
},
|
|
1390
|
+
setETag(value) {
|
|
1391
|
+
meta.headers["etag"] = value;
|
|
1392
|
+
},
|
|
1393
|
+
redirect(url2, status = 302) {
|
|
1394
|
+
return new Response(null, {
|
|
1395
|
+
status,
|
|
1396
|
+
headers: { Location: url2 }
|
|
1397
|
+
});
|
|
1398
|
+
},
|
|
1399
|
+
json(data, status) {
|
|
1400
|
+
const headers = { "Content-Type": "application/json" };
|
|
1401
|
+
return new Response(JSON.stringify(data), {
|
|
1402
|
+
status: status ?? 200,
|
|
1403
|
+
headers
|
|
1404
|
+
});
|
|
1405
|
+
},
|
|
1406
|
+
html(html, status) {
|
|
1407
|
+
const headers = { "Content-Type": "text/html; charset=utf-8" };
|
|
1408
|
+
return new Response(html, {
|
|
1409
|
+
status: status ?? 200,
|
|
1410
|
+
headers
|
|
1411
|
+
});
|
|
1412
|
+
},
|
|
1413
|
+
getCookie(name) {
|
|
1414
|
+
return parsedCookies.get(name);
|
|
1415
|
+
},
|
|
1416
|
+
setCookie(name, value, options) {
|
|
1417
|
+
meta.setCookies.push(formatSetCookie(name, value, options));
|
|
1418
|
+
},
|
|
1419
|
+
deleteCookie(name) {
|
|
1420
|
+
meta.setCookies.push(formatSetCookie(name, "", { maxAge: 0 }));
|
|
1421
|
+
},
|
|
1422
|
+
/**
|
|
1423
|
+
* 创建 SSE writer,用于流式推送事件
|
|
1424
|
+
*
|
|
1425
|
+
* handler 调用此方法后,通过返回的 writer 推送事件,框架自动把 writer.response
|
|
1426
|
+
* 作为 HTTP 响应(Content-Type: text/event-stream)。
|
|
1427
|
+
*
|
|
1428
|
+
* 与 ctx.json / ctx.html 互斥:一个 handler 只能用一种响应方式。
|
|
1429
|
+
*/
|
|
1430
|
+
sse() {
|
|
1431
|
+
const writer = createSseWriter();
|
|
1432
|
+
const ctxWithSse = ctx;
|
|
1433
|
+
ctxWithSse.__sseResponse = writer.response;
|
|
1434
|
+
ctxWithSse.__sseWriter = writer;
|
|
1435
|
+
return writer;
|
|
1436
|
+
}
|
|
1437
|
+
};
|
|
1438
|
+
const extend = config?.extendContext;
|
|
1439
|
+
if (typeof extend === "function") {
|
|
1440
|
+
extend(ctx);
|
|
1441
|
+
}
|
|
1442
|
+
return ctx;
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
// src/utils/queryToObject.ts
|
|
1446
|
+
function queryToObject(params) {
|
|
1447
|
+
const result = {};
|
|
1448
|
+
for (const [key, value] of params) {
|
|
1449
|
+
result[key] = value;
|
|
1450
|
+
}
|
|
1451
|
+
return result;
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
// src/utils/parseJsonBody.ts
|
|
1455
|
+
function parseJsonBody(text) {
|
|
1456
|
+
try {
|
|
1457
|
+
const data = JSON.parse(text);
|
|
1458
|
+
return { success: true, data };
|
|
1459
|
+
} catch {
|
|
1460
|
+
return { success: false, error: "Invalid JSON body" };
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// src/utils/parseMultipart.ts
|
|
1465
|
+
async function parseMultipart(request) {
|
|
1466
|
+
const formData = await request.formData();
|
|
1467
|
+
const fields = {};
|
|
1468
|
+
const files = [];
|
|
1469
|
+
for (const [key, value] of formData.entries()) {
|
|
1470
|
+
if (value instanceof File) {
|
|
1471
|
+
files.push({
|
|
1472
|
+
name: key,
|
|
1473
|
+
filename: value.name,
|
|
1474
|
+
type: value.type,
|
|
1475
|
+
size: value.size,
|
|
1476
|
+
arrayBuffer: () => value.arrayBuffer()
|
|
1477
|
+
});
|
|
1478
|
+
} else {
|
|
1479
|
+
if (key in fields) {
|
|
1480
|
+
const existing = fields[key];
|
|
1481
|
+
if (Array.isArray(existing)) {
|
|
1482
|
+
existing.push(value);
|
|
1483
|
+
} else {
|
|
1484
|
+
fields[key] = [existing, value];
|
|
1485
|
+
}
|
|
1486
|
+
} else {
|
|
1487
|
+
fields[key] = value;
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
return { fields, files };
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
// src/runtime/resolveInput.ts
|
|
1495
|
+
async function resolveInput(method, request) {
|
|
1496
|
+
const inputType = getInputTypeForMethod(method);
|
|
1497
|
+
if (inputType === "body") {
|
|
1498
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
1499
|
+
if (contentType.includes("multipart/form-data")) {
|
|
1500
|
+
return parseMultipart(request);
|
|
1501
|
+
}
|
|
1502
|
+
if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
1503
|
+
const text2 = await request.text();
|
|
1504
|
+
if (text2.trim() === "") return null;
|
|
1505
|
+
const params = new URLSearchParams(text2);
|
|
1506
|
+
const obj = {};
|
|
1507
|
+
for (const [key, value] of params) {
|
|
1508
|
+
obj[key] = value;
|
|
1509
|
+
}
|
|
1510
|
+
return obj;
|
|
1511
|
+
}
|
|
1512
|
+
const text = await request.text();
|
|
1513
|
+
if (text.trim() === "") {
|
|
1514
|
+
return null;
|
|
1515
|
+
}
|
|
1516
|
+
const result = parseJsonBody(text);
|
|
1517
|
+
if (!result.success) {
|
|
1518
|
+
throw new ValidationError("\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5\u7684 JSON", [
|
|
1519
|
+
{
|
|
1520
|
+
path: "body",
|
|
1521
|
+
code: "INVALID_FORMAT",
|
|
1522
|
+
expected: "JSON",
|
|
1523
|
+
received: "text",
|
|
1524
|
+
message: "\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5\u7684 JSON"
|
|
1525
|
+
}
|
|
1526
|
+
]);
|
|
1527
|
+
}
|
|
1528
|
+
return result.data;
|
|
1529
|
+
}
|
|
1530
|
+
const url = new URL(request.url);
|
|
1531
|
+
return queryToObject(url.searchParams);
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
// src/utils/isPlainObject.ts
|
|
1535
|
+
function isPlainObject(value) {
|
|
1536
|
+
if (value === null || typeof value !== "object") {
|
|
1537
|
+
return false;
|
|
1538
|
+
}
|
|
1539
|
+
if (Array.isArray(value)) {
|
|
1540
|
+
return false;
|
|
1541
|
+
}
|
|
1542
|
+
const proto = Object.getPrototypeOf(value);
|
|
1543
|
+
return proto === null || proto === Object.prototype;
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
// src/response/toResponse.ts
|
|
1547
|
+
async function toResponse(value, meta) {
|
|
1548
|
+
if (value instanceof Promise) {
|
|
1549
|
+
return toResponse(await value, meta);
|
|
1550
|
+
}
|
|
1551
|
+
const applyMeta = (headers2) => {
|
|
1552
|
+
if (!meta) return;
|
|
1553
|
+
for (const [key, val] of Object.entries(meta.headers)) {
|
|
1554
|
+
headers2.set(key, val);
|
|
1555
|
+
}
|
|
1556
|
+
for (const cookie of meta.setCookies ?? []) {
|
|
1557
|
+
headers2.append("set-cookie", cookie);
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1560
|
+
if (value instanceof Response) {
|
|
1561
|
+
if (meta && (meta.status !== void 0 || Object.keys(meta.headers).length > 0 || meta.setCookies.length > 0)) {
|
|
1562
|
+
const headers2 = new Headers(value.headers);
|
|
1563
|
+
applyMeta(headers2);
|
|
1564
|
+
return new Response(value.body, {
|
|
1565
|
+
status: meta.status ?? value.status,
|
|
1566
|
+
headers: headers2
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
return value;
|
|
1570
|
+
}
|
|
1571
|
+
if (value === null || value === void 0) {
|
|
1572
|
+
const status = meta?.status ?? 204;
|
|
1573
|
+
const headers2 = new Headers();
|
|
1574
|
+
applyMeta(headers2);
|
|
1575
|
+
return new Response(null, { status, headers: headers2 });
|
|
1576
|
+
}
|
|
1577
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
|
|
1578
|
+
const headers2 = new Headers({ "Content-Type": "application/octet-stream" });
|
|
1579
|
+
applyMeta(headers2);
|
|
1580
|
+
return new Response(value, {
|
|
1581
|
+
status: meta?.status ?? 200,
|
|
1582
|
+
headers: headers2
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) {
|
|
1586
|
+
const headers2 = new Headers({ "Content-Type": "application/octet-stream" });
|
|
1587
|
+
applyMeta(headers2);
|
|
1588
|
+
return new Response(value, {
|
|
1589
|
+
status: meta?.status ?? 200,
|
|
1590
|
+
headers: headers2
|
|
1591
|
+
});
|
|
1592
|
+
}
|
|
1593
|
+
if (value instanceof Uint8Array) {
|
|
1594
|
+
const headers2 = new Headers({ "Content-Type": "application/octet-stream" });
|
|
1595
|
+
applyMeta(headers2);
|
|
1596
|
+
return new Response(value, {
|
|
1597
|
+
status: meta?.status ?? 200,
|
|
1598
|
+
headers: headers2
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
if (isPlainObject(value) || Array.isArray(value)) {
|
|
1602
|
+
const body2 = JSON.stringify(value);
|
|
1603
|
+
const headers2 = new Headers({ "Content-Type": "application/json" });
|
|
1604
|
+
applyMeta(headers2);
|
|
1605
|
+
return new Response(body2, {
|
|
1606
|
+
status: meta?.status ?? 200,
|
|
1607
|
+
headers: headers2
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
if (typeof value === "string") {
|
|
1611
|
+
const headers2 = new Headers({ "Content-Type": "text/plain" });
|
|
1612
|
+
applyMeta(headers2);
|
|
1613
|
+
return new Response(value, {
|
|
1614
|
+
status: meta?.status ?? 200,
|
|
1615
|
+
headers: headers2
|
|
1616
|
+
});
|
|
1617
|
+
}
|
|
1618
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
1619
|
+
const headers2 = new Headers({ "Content-Type": "text/plain" });
|
|
1620
|
+
applyMeta(headers2);
|
|
1621
|
+
return new Response(String(value), {
|
|
1622
|
+
status: meta?.status ?? 200,
|
|
1623
|
+
headers: headers2
|
|
1624
|
+
});
|
|
1625
|
+
}
|
|
1626
|
+
const body = JSON.stringify(value);
|
|
1627
|
+
const headers = new Headers({ "Content-Type": "application/json" });
|
|
1628
|
+
applyMeta(headers);
|
|
1629
|
+
return new Response(body, {
|
|
1630
|
+
status: meta?.status ?? 200,
|
|
1631
|
+
headers
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// src/injection/injectParams.ts
|
|
1636
|
+
function getBuiltinInjectionValue(type, ctx, body) {
|
|
1637
|
+
switch (type) {
|
|
1638
|
+
case "query":
|
|
1639
|
+
return queryToObject(ctx.query);
|
|
1640
|
+
case "params":
|
|
1641
|
+
return ctx.params;
|
|
1642
|
+
case "headers":
|
|
1643
|
+
return ctx.headers;
|
|
1644
|
+
case "context":
|
|
1645
|
+
return ctx;
|
|
1646
|
+
case "cookies":
|
|
1647
|
+
return ctx.cookies;
|
|
1648
|
+
case "ip":
|
|
1649
|
+
return ctx.ip;
|
|
1650
|
+
case "body":
|
|
1651
|
+
return body;
|
|
1652
|
+
case "files":
|
|
1653
|
+
if (body && typeof body === "object" && "files" in body) {
|
|
1654
|
+
return body.files;
|
|
1655
|
+
}
|
|
1656
|
+
return [];
|
|
1657
|
+
case "fields":
|
|
1658
|
+
if (body && typeof body === "object" && "fields" in body) {
|
|
1659
|
+
return body.fields;
|
|
1660
|
+
}
|
|
1661
|
+
return {};
|
|
1662
|
+
default:
|
|
1663
|
+
return void 0;
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
async function injectParamsAsync(handler, ctx, body, injectors) {
|
|
1667
|
+
const injections = resolveInjection(handler);
|
|
1668
|
+
if (injections.length === 0) {
|
|
1669
|
+
return await handler();
|
|
1670
|
+
}
|
|
1671
|
+
const args = await Promise.all(
|
|
1672
|
+
injections.map(async (injection) => {
|
|
1673
|
+
if (injection.type !== "unknown") {
|
|
1674
|
+
return getBuiltinInjectionValue(injection.type, ctx, body);
|
|
1675
|
+
}
|
|
1676
|
+
if (injectors && injection.name in injectors) {
|
|
1677
|
+
return await injectors[injection.name](ctx);
|
|
1678
|
+
}
|
|
1679
|
+
return void 0;
|
|
1680
|
+
})
|
|
1681
|
+
);
|
|
1682
|
+
return await handler(...args);
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
// src/runtime/invokeHandler.ts
|
|
1686
|
+
function mergeMeta(response, meta) {
|
|
1687
|
+
const hasMeta = meta.status !== void 0 || Object.keys(meta.headers).length > 0 || meta.setCookies.length > 0;
|
|
1688
|
+
if (!hasMeta) return response;
|
|
1689
|
+
const headers = new Headers(response.headers);
|
|
1690
|
+
for (const [key, value] of Object.entries(meta.headers)) {
|
|
1691
|
+
headers.set(key, value);
|
|
1692
|
+
}
|
|
1693
|
+
for (const cookie of meta.setCookies) {
|
|
1694
|
+
headers.append("set-cookie", cookie);
|
|
1695
|
+
}
|
|
1696
|
+
return new Response(response.body, {
|
|
1697
|
+
status: meta.status ?? response.status,
|
|
1698
|
+
headers
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
async function compose(middlewares, ctx, finalHandler) {
|
|
1702
|
+
const meta = ctx.meta;
|
|
1703
|
+
let index = -1;
|
|
1704
|
+
async function dispatch(i) {
|
|
1705
|
+
if (i <= index) {
|
|
1706
|
+
throw new Error("next() called multiple times");
|
|
1707
|
+
}
|
|
1708
|
+
index = i;
|
|
1709
|
+
if (i >= middlewares.length) {
|
|
1710
|
+
return await finalHandler();
|
|
1711
|
+
}
|
|
1712
|
+
const mw = middlewares[i];
|
|
1713
|
+
let innerResponse;
|
|
1714
|
+
const next = async () => {
|
|
1715
|
+
innerResponse = await dispatch(i + 1);
|
|
1716
|
+
return innerResponse;
|
|
1717
|
+
};
|
|
1718
|
+
const result = await mw(ctx, next);
|
|
1719
|
+
if (result instanceof Response) {
|
|
1720
|
+
return mergeMeta(result, meta);
|
|
1721
|
+
}
|
|
1722
|
+
if (innerResponse !== void 0) {
|
|
1723
|
+
return innerResponse;
|
|
1724
|
+
}
|
|
1725
|
+
throw new Error("\u4E2D\u95F4\u4EF6\u5FC5\u987B await next() \u6216\u8FD4\u56DE Response");
|
|
1726
|
+
}
|
|
1727
|
+
return await dispatch(0);
|
|
1728
|
+
}
|
|
1729
|
+
async function invokeHandler(handler, ctx, body, middlewares, injectors) {
|
|
1730
|
+
const meta = ctx.meta;
|
|
1731
|
+
const pickSseAndAutoClose = () => {
|
|
1732
|
+
const sseWriter = ctx.__sseWriter;
|
|
1733
|
+
if (!sseWriter) return null;
|
|
1734
|
+
if (!sseWriter.closed && !sseWriter.aborted) {
|
|
1735
|
+
sseWriter.close();
|
|
1736
|
+
}
|
|
1737
|
+
return mergeMeta(sseWriter.response, meta);
|
|
1738
|
+
};
|
|
1739
|
+
const autoCloseSseOnError = () => {
|
|
1740
|
+
const sseWriter = ctx.__sseWriter;
|
|
1741
|
+
if (sseWriter && !sseWriter.closed && !sseWriter.aborted) {
|
|
1742
|
+
sseWriter.close();
|
|
1743
|
+
}
|
|
1744
|
+
};
|
|
1745
|
+
if (!middlewares || middlewares.length === 0) {
|
|
1746
|
+
try {
|
|
1747
|
+
const result = await injectParamsAsync(handler, ctx, body, injectors);
|
|
1748
|
+
const sseResponse = pickSseAndAutoClose();
|
|
1749
|
+
if (sseResponse) return sseResponse;
|
|
1750
|
+
return toResponse(result, meta);
|
|
1751
|
+
} catch (err) {
|
|
1752
|
+
autoCloseSseOnError();
|
|
1753
|
+
throw err;
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
const finalHandler = async () => {
|
|
1757
|
+
try {
|
|
1758
|
+
const result = await injectParamsAsync(handler, ctx, body, injectors);
|
|
1759
|
+
const sseResponse = pickSseAndAutoClose();
|
|
1760
|
+
if (sseResponse) return sseResponse;
|
|
1761
|
+
return toResponse(result, meta);
|
|
1762
|
+
} catch (err) {
|
|
1763
|
+
autoCloseSseOnError();
|
|
1764
|
+
throw err;
|
|
1765
|
+
}
|
|
1766
|
+
};
|
|
1767
|
+
return await compose(middlewares, ctx, finalHandler);
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
// src/response/sendNodeResponse.ts
|
|
1771
|
+
import { Readable } from "stream";
|
|
1772
|
+
async function sendNodeResponse(response, res) {
|
|
1773
|
+
res.statusCode = response.status;
|
|
1774
|
+
for (const [key, value] of response.headers) {
|
|
1775
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
1776
|
+
res.appendHeader(key, value);
|
|
1777
|
+
} else {
|
|
1778
|
+
res.setHeader(key, value);
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
if (response.body) {
|
|
1782
|
+
const nodeStream = Readable.fromWeb(response.body);
|
|
1783
|
+
await new Promise((resolve, reject) => {
|
|
1784
|
+
nodeStream.on("error", reject);
|
|
1785
|
+
res.on("error", reject);
|
|
1786
|
+
res.on("finish", resolve);
|
|
1787
|
+
nodeStream.pipe(res);
|
|
1788
|
+
});
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
res.end();
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
// src/validator/validateInput.ts
|
|
1795
|
+
var moduleCache = /* @__PURE__ */ new Map();
|
|
1796
|
+
function invalidateSchemaCache() {
|
|
1797
|
+
moduleCache.clear();
|
|
1798
|
+
}
|
|
1799
|
+
async function loadSchemaModule(schemaPath) {
|
|
1800
|
+
let mod = moduleCache.get(schemaPath);
|
|
1801
|
+
if (!mod) {
|
|
1802
|
+
mod = await importWithCacheBust(schemaPath);
|
|
1803
|
+
moduleCache.set(schemaPath, mod);
|
|
1804
|
+
}
|
|
1805
|
+
return mod;
|
|
1806
|
+
}
|
|
1807
|
+
async function validateInput(schemaPath, method, inputType, input) {
|
|
1808
|
+
const schemaName = getSchemaName(method, inputType);
|
|
1809
|
+
const schemaKey = `${schemaName}Schema`;
|
|
1810
|
+
let mod;
|
|
1811
|
+
try {
|
|
1812
|
+
mod = await loadSchemaModule(schemaPath);
|
|
1813
|
+
} catch (err) {
|
|
1814
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
1815
|
+
throw new InternalError(`Schema \u6A21\u5757\u52A0\u8F7D\u5931\u8D25: ${schemaPath}: ${reason}`);
|
|
1816
|
+
}
|
|
1817
|
+
const schema = mod[schemaKey];
|
|
1818
|
+
if (schema === void 0 || schema === null) {
|
|
1819
|
+
const data = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
|
|
1820
|
+
return { valid: true, issues: [], data };
|
|
1821
|
+
}
|
|
1822
|
+
if (typeof schema !== "object" || typeof schema.safeParse !== "function") {
|
|
1823
|
+
throw new InternalError(`Schema \u4E0D\u662F\u6709\u6548\u7684 zod schema: ${schemaPath}#${schemaName}`);
|
|
1824
|
+
}
|
|
1825
|
+
const inputObj = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
|
|
1826
|
+
const zodSchema = schema;
|
|
1827
|
+
const result = zodSchema.safeParse(inputObj);
|
|
1828
|
+
if (result.success) {
|
|
1829
|
+
const data = typeof result.data === "object" && result.data !== null && !Array.isArray(result.data) ? result.data : {};
|
|
1830
|
+
return { valid: true, issues: [], data };
|
|
1831
|
+
}
|
|
1832
|
+
const issues = mapZodIssues(result.error);
|
|
1833
|
+
return { valid: false, issues, data: inputObj };
|
|
1834
|
+
}
|
|
1835
|
+
function mapZodIssues(error) {
|
|
1836
|
+
return error.issues.map((issue) => {
|
|
1837
|
+
const code = mapZodCode(issue.code, issue.message);
|
|
1838
|
+
const path9 = issue.path.map(String).join(".") || "";
|
|
1839
|
+
return {
|
|
1840
|
+
path: path9,
|
|
1841
|
+
code,
|
|
1842
|
+
expected: issue.expected ?? mapExpectedFromMessage(issue.message),
|
|
1843
|
+
received: issue.received ?? mapReceivedFromMessage(issue.message),
|
|
1844
|
+
message: issue.message
|
|
1845
|
+
};
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
function mapZodCode(zodCode, message) {
|
|
1849
|
+
switch (zodCode) {
|
|
1850
|
+
case "invalid_type":
|
|
1851
|
+
case "invalid_union":
|
|
1852
|
+
case "invalid_union_discriminator":
|
|
1853
|
+
return "TYPE_MISMATCH";
|
|
1854
|
+
case "unrecognized_keys":
|
|
1855
|
+
return "INVALID_FORMAT";
|
|
1856
|
+
case "invalid_value":
|
|
1857
|
+
case "invalid_string":
|
|
1858
|
+
case "too_small":
|
|
1859
|
+
case "too_big":
|
|
1860
|
+
case "invalid_intersection_types":
|
|
1861
|
+
case "not_multiple_of":
|
|
1862
|
+
return "INVALID_VALUE";
|
|
1863
|
+
case "custom":
|
|
1864
|
+
return "INVALID_VALUE";
|
|
1865
|
+
default:
|
|
1866
|
+
if (message.includes("Required") || message.includes("required")) {
|
|
1867
|
+
return "MISSING_FIELD";
|
|
1868
|
+
}
|
|
1869
|
+
return "INVALID_VALUE";
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
function mapExpectedFromMessage(message) {
|
|
1873
|
+
const match = message.match(/Expected\s+(\w+)/i);
|
|
1874
|
+
return match ? match[1].toLowerCase() : "unknown";
|
|
1875
|
+
}
|
|
1876
|
+
function mapReceivedFromMessage(message) {
|
|
1877
|
+
const match = message.match(/received\s+(\w+)/i);
|
|
1878
|
+
return match ? match[1].toLowerCase() : "unknown";
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
// src/utils/getClientIp.ts
|
|
1882
|
+
function getClientIp(req) {
|
|
1883
|
+
const xff = req.headers["x-forwarded-for"];
|
|
1884
|
+
if (typeof xff === "string" && xff.length > 0) {
|
|
1885
|
+
const first = xff.split(",")[0]?.trim();
|
|
1886
|
+
if (first) return first;
|
|
1887
|
+
}
|
|
1888
|
+
const remote = req.socket?.remoteAddress;
|
|
1889
|
+
if (remote) {
|
|
1890
|
+
if (remote.startsWith("::ffff:")) {
|
|
1891
|
+
return remote.slice(7);
|
|
1892
|
+
}
|
|
1893
|
+
return remote;
|
|
1894
|
+
}
|
|
1895
|
+
return "";
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
// src/server/handleWsUpgrade.ts
|
|
1899
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
1900
|
+
import path3 from "path";
|
|
1901
|
+
|
|
1902
|
+
// src/errors/formatErrorResponse.ts
|
|
1903
|
+
function formatErrorResponse(error) {
|
|
1904
|
+
if (error instanceof ValidationError) {
|
|
1905
|
+
const body2 = {
|
|
1906
|
+
code: error.code,
|
|
1907
|
+
message: error.message,
|
|
1908
|
+
issues: error.issues
|
|
1909
|
+
};
|
|
1910
|
+
return new Response(JSON.stringify({ error: body2 }), {
|
|
1911
|
+
status: error.statusCode,
|
|
1912
|
+
headers: { "Content-Type": "application/json" }
|
|
1913
|
+
});
|
|
1914
|
+
}
|
|
1915
|
+
if (error instanceof MethodNotAllowedError) {
|
|
1916
|
+
const body2 = {
|
|
1917
|
+
code: error.code,
|
|
1918
|
+
message: error.message
|
|
1919
|
+
};
|
|
1920
|
+
return new Response(JSON.stringify({ error: body2 }), {
|
|
1921
|
+
status: error.statusCode,
|
|
1922
|
+
headers: {
|
|
1923
|
+
"Content-Type": "application/json",
|
|
1924
|
+
Allow: error.allowedMethods.join(", ")
|
|
1925
|
+
}
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
if (error instanceof FaapiError) {
|
|
1929
|
+
const body2 = {
|
|
1930
|
+
code: error.code,
|
|
1931
|
+
message: error.message
|
|
1932
|
+
};
|
|
1933
|
+
return new Response(JSON.stringify({ error: body2 }), {
|
|
1934
|
+
status: error.statusCode,
|
|
1935
|
+
headers: { "Content-Type": "application/json" }
|
|
1936
|
+
});
|
|
1937
|
+
}
|
|
1938
|
+
const body = {
|
|
1939
|
+
code: "INTERNAL_ERROR",
|
|
1940
|
+
message: error instanceof Error ? error.message : "An unknown error occurred"
|
|
1941
|
+
};
|
|
1942
|
+
return new Response(JSON.stringify({ error: body }), {
|
|
1943
|
+
status: 500,
|
|
1944
|
+
headers: { "Content-Type": "application/json" }
|
|
1945
|
+
});
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
// src/server/serverUtils.ts
|
|
1949
|
+
function nodeHttpToWebHeaders(req) {
|
|
1950
|
+
const headers = new Headers();
|
|
1951
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
1952
|
+
if (value === void 0) continue;
|
|
1953
|
+
if (Array.isArray(value)) {
|
|
1954
|
+
for (const v of value) headers.append(key, v);
|
|
1955
|
+
} else {
|
|
1956
|
+
headers.set(key, value);
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
return headers;
|
|
1960
|
+
}
|
|
1961
|
+
function buildErrorResponse(err) {
|
|
1962
|
+
try {
|
|
1963
|
+
return formatErrorResponse(err);
|
|
1964
|
+
} catch {
|
|
1965
|
+
return new Response(
|
|
1966
|
+
JSON.stringify({ error: { code: "INTERNAL_ERROR", message: "Internal Server Error" } }),
|
|
1967
|
+
{
|
|
1968
|
+
status: 500,
|
|
1969
|
+
headers: { "Content-Type": "application/json" }
|
|
1970
|
+
}
|
|
1971
|
+
);
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
// src/runtime/wsHandler.ts
|
|
1976
|
+
function wrapWsSocket(rawSocket) {
|
|
1977
|
+
return {
|
|
1978
|
+
send(data) {
|
|
1979
|
+
const payload = typeof data === "string" || Buffer.isBuffer(data) ? data : JSON.stringify(data);
|
|
1980
|
+
rawSocket.send(payload);
|
|
1981
|
+
},
|
|
1982
|
+
close(code, reason) {
|
|
1983
|
+
rawSocket.close(code, reason);
|
|
1984
|
+
},
|
|
1985
|
+
get readyState() {
|
|
1986
|
+
return rawSocket.readyState;
|
|
1987
|
+
}
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
// src/server/handleWsUpgrade.ts
|
|
1992
|
+
function getPathname(req) {
|
|
1993
|
+
const url = req.url ?? "/";
|
|
1994
|
+
const idx = url.indexOf("?");
|
|
1995
|
+
return idx >= 0 ? url.slice(0, idx) : url;
|
|
1996
|
+
}
|
|
1997
|
+
async function loadWsHandler(filePath, ctx) {
|
|
1998
|
+
const module = await importWithCacheBust(filePath);
|
|
1999
|
+
const handler = module["WS"];
|
|
2000
|
+
if (typeof handler !== "function") {
|
|
2001
|
+
throw new Error(`WS export not found in ${filePath}`);
|
|
2002
|
+
}
|
|
2003
|
+
return handler(ctx);
|
|
2004
|
+
}
|
|
2005
|
+
function bindEvents(rawSocket, handlers) {
|
|
2006
|
+
if (!handlers) return;
|
|
2007
|
+
const ws = wrapWsSocket(rawSocket);
|
|
2008
|
+
if (handlers.onOpen) {
|
|
2009
|
+
if (rawSocket.readyState === WebSocket.OPEN) {
|
|
2010
|
+
handlers.onOpen(ws);
|
|
2011
|
+
} else {
|
|
2012
|
+
rawSocket.once("open", () => handlers.onOpen(ws));
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
if (handlers.onMessage) {
|
|
2016
|
+
rawSocket.on("message", (data) => {
|
|
2017
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
2018
|
+
handlers.onMessage(ws, buf.toString("utf8"));
|
|
2019
|
+
});
|
|
2020
|
+
}
|
|
2021
|
+
if (handlers.onClose) {
|
|
2022
|
+
rawSocket.on("close", (code, reason) => {
|
|
2023
|
+
handlers.onClose(ws, code, reason.toString("utf8"));
|
|
2024
|
+
});
|
|
2025
|
+
}
|
|
2026
|
+
if (handlers.onError) {
|
|
2027
|
+
rawSocket.on("error", (err) => {
|
|
2028
|
+
handlers.onError(ws, err);
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
async function sendResponseToSocket(socket, response) {
|
|
2033
|
+
const body = await response.text().catch(() => "");
|
|
2034
|
+
const statusLine = `HTTP/1.1 ${response.status} ${response.statusText || ""}\r
|
|
2035
|
+
`;
|
|
2036
|
+
const headerLines = [];
|
|
2037
|
+
let hasContentLength = false;
|
|
2038
|
+
for (const [key, value] of response.headers) {
|
|
2039
|
+
if (key.toLowerCase() === "content-length") {
|
|
2040
|
+
hasContentLength = true;
|
|
2041
|
+
}
|
|
2042
|
+
headerLines.push(`${key}: ${value}`);
|
|
2043
|
+
}
|
|
2044
|
+
if (!hasContentLength) {
|
|
2045
|
+
headerLines.push(`Content-Length: ${Buffer.byteLength(body)}`);
|
|
2046
|
+
}
|
|
2047
|
+
socket.write(statusLine + headerLines.join("\r\n") + "\r\n\r\n" + body);
|
|
2048
|
+
socket.destroy();
|
|
2049
|
+
}
|
|
2050
|
+
function attachWebSocket(options) {
|
|
2051
|
+
const { server, routesRef, rootDir, config, globalMiddlewares } = options;
|
|
2052
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
2053
|
+
server.on("upgrade", async (req, socket, head) => {
|
|
2054
|
+
const currentWsRoutes = routesRef.wsCurrent;
|
|
2055
|
+
const pathname = getPathname(req);
|
|
2056
|
+
const match = matchWsRoute(currentWsRoutes, pathname);
|
|
2057
|
+
if (!match) {
|
|
2058
|
+
socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
|
|
2059
|
+
socket.destroy();
|
|
2060
|
+
return;
|
|
2061
|
+
}
|
|
2062
|
+
const { route, params } = match;
|
|
2063
|
+
const headers = nodeHttpToWebHeaders(req);
|
|
2064
|
+
const host = req.headers.host ?? "localhost";
|
|
2065
|
+
const url = `http://${host}${req.url ?? "/"}`;
|
|
2066
|
+
const request = new Request(url, { method: "GET", headers });
|
|
2067
|
+
const ctx = createContext(request, params, config, getClientIp(req));
|
|
2068
|
+
const meta = ctx.meta;
|
|
2069
|
+
let upgraded = false;
|
|
2070
|
+
const finalHandler = async () => {
|
|
2071
|
+
let handlers;
|
|
2072
|
+
try {
|
|
2073
|
+
const absoluteFilePath = path3.resolve(rootDir, route.filePath);
|
|
2074
|
+
handlers = await loadWsHandler(absoluteFilePath, ctx);
|
|
2075
|
+
} catch (err) {
|
|
2076
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
2077
|
+
console.error(`[faapi] WS handler \u52A0\u8F7D\u5931\u8D25 ${route.filePath}: ${reason}`);
|
|
2078
|
+
return new Response("Internal Server Error", { status: 500 });
|
|
2079
|
+
}
|
|
2080
|
+
await new Promise((resolve, reject) => {
|
|
2081
|
+
wss.handleUpgrade(req, socket, head, (rawSocket) => {
|
|
2082
|
+
try {
|
|
2083
|
+
bindEvents(rawSocket, handlers);
|
|
2084
|
+
wss.emit("connection", rawSocket, req);
|
|
2085
|
+
upgraded = true;
|
|
2086
|
+
resolve();
|
|
2087
|
+
} catch (err) {
|
|
2088
|
+
reject(err);
|
|
2089
|
+
}
|
|
2090
|
+
});
|
|
2091
|
+
});
|
|
2092
|
+
return new Response(null, { status: 200 });
|
|
2093
|
+
};
|
|
2094
|
+
let response;
|
|
2095
|
+
try {
|
|
2096
|
+
const dirMiddlewares = route.middlewares ?? [];
|
|
2097
|
+
const allMiddlewares = globalMiddlewares && globalMiddlewares.length > 0 ? [...globalMiddlewares, ...dirMiddlewares] : dirMiddlewares;
|
|
2098
|
+
if (allMiddlewares.length > 0) {
|
|
2099
|
+
response = await compose(allMiddlewares, ctx, finalHandler);
|
|
2100
|
+
} else {
|
|
2101
|
+
response = await finalHandler();
|
|
2102
|
+
}
|
|
2103
|
+
} catch (err) {
|
|
2104
|
+
if (upgraded) {
|
|
2105
|
+
console.error("[faapi] WS \u63E1\u624B\u540E\u4E2D\u95F4\u4EF6\u629B\u9519:", err);
|
|
2106
|
+
return;
|
|
2107
|
+
}
|
|
2108
|
+
response = buildErrorResponse(err);
|
|
2109
|
+
}
|
|
2110
|
+
if (upgraded) {
|
|
2111
|
+
return;
|
|
2112
|
+
}
|
|
2113
|
+
await sendResponseToSocket(socket, mergeMeta(response, meta));
|
|
2114
|
+
});
|
|
2115
|
+
return wss;
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
// src/cli/generateSchemaFiles.ts
|
|
2119
|
+
import path4 from "path";
|
|
2120
|
+
import fs2 from "fs/promises";
|
|
2121
|
+
|
|
2122
|
+
// src/ast/generateZodSchema.ts
|
|
2123
|
+
var CodeGenContext = class {
|
|
2124
|
+
/** 命名类型集合:name → RuntimeType */
|
|
2125
|
+
namedTypes = /* @__PURE__ */ new Map();
|
|
2126
|
+
/** 类型解析器(用于解析 ref 的实际类型) */
|
|
2127
|
+
resolveType;
|
|
2128
|
+
/** 入口类型原始名(typeInfo.name,用于识别入口类型的自引用) */
|
|
2129
|
+
entryTypeName = "";
|
|
2130
|
+
/** 入口类型导出名(exportName,自引用时用此名生成变量名) */
|
|
2131
|
+
entryExportName = "";
|
|
2132
|
+
/**
|
|
2133
|
+
* 是否生成 coerce 逻辑(query/params 场景,URL 来源均为 string)
|
|
2134
|
+
*
|
|
2135
|
+
* true 时为 number/boolean 字段包 z.preprocess,把合法的字符串转成对应类型。
|
|
2136
|
+
* 嵌套类型(array/object/tuple/union 等)的元素递归处理。
|
|
2137
|
+
*/
|
|
2138
|
+
coerce = false;
|
|
2139
|
+
constructor(resolveType) {
|
|
2140
|
+
this.resolveType = resolveType;
|
|
2141
|
+
}
|
|
2142
|
+
};
|
|
2143
|
+
function collectNamedTypes(type, ctx) {
|
|
2144
|
+
switch (type.kind) {
|
|
2145
|
+
case "string":
|
|
2146
|
+
case "number":
|
|
2147
|
+
case "boolean":
|
|
2148
|
+
case "bigint":
|
|
2149
|
+
case "null":
|
|
2150
|
+
case "undefined":
|
|
2151
|
+
case "any":
|
|
2152
|
+
case "unknown":
|
|
2153
|
+
case "literal":
|
|
2154
|
+
case "date":
|
|
2155
|
+
return;
|
|
2156
|
+
case "array":
|
|
2157
|
+
collectNamedTypes(type.element, ctx);
|
|
2158
|
+
return;
|
|
2159
|
+
case "tuple":
|
|
2160
|
+
for (const el of type.elements) {
|
|
2161
|
+
collectNamedTypes(el.type, ctx);
|
|
2162
|
+
}
|
|
2163
|
+
return;
|
|
2164
|
+
case "object":
|
|
2165
|
+
for (const prop of type.properties) {
|
|
2166
|
+
collectNamedTypes(prop.type, ctx);
|
|
2167
|
+
}
|
|
2168
|
+
return;
|
|
2169
|
+
case "union":
|
|
2170
|
+
for (const member of type.members) {
|
|
2171
|
+
collectNamedTypes(member, ctx);
|
|
2172
|
+
}
|
|
2173
|
+
return;
|
|
2174
|
+
case "record":
|
|
2175
|
+
collectNamedTypes(type.key, ctx);
|
|
2176
|
+
collectNamedTypes(type.value, ctx);
|
|
2177
|
+
return;
|
|
2178
|
+
case "ref": {
|
|
2179
|
+
if (ctx.namedTypes.has(type.name)) return;
|
|
2180
|
+
ctx.namedTypes.set(type.name, { kind: "any" });
|
|
2181
|
+
const resolved = ctx.resolveType(type.name);
|
|
2182
|
+
if (resolved) {
|
|
2183
|
+
ctx.namedTypes.set(type.name, resolved);
|
|
2184
|
+
collectNamedTypes(resolved, ctx);
|
|
2185
|
+
}
|
|
2186
|
+
return;
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
function runtimeTypeToZodExpression(type, ctx, constraints) {
|
|
2191
|
+
const expr = baseExpression(type, ctx);
|
|
2192
|
+
const withConstraints = constraints && constraints.length > 0 ? applyConstraints(expr, constraints, type.kind) : expr;
|
|
2193
|
+
if (ctx.coerce && (type.kind === "number" || type.kind === "boolean")) {
|
|
2194
|
+
return wrapCoercePreprocess(type.kind, withConstraints);
|
|
2195
|
+
}
|
|
2196
|
+
return withConstraints;
|
|
2197
|
+
}
|
|
2198
|
+
function applyConstraints(baseExpr, constraints, typeKind) {
|
|
2199
|
+
const suffix = constraints.map((c) => constraintToZodChain(c, typeKind)).join("");
|
|
2200
|
+
return `${baseExpr}${suffix}`;
|
|
2201
|
+
}
|
|
2202
|
+
function constraintToZodChain(constraint, _typeKind) {
|
|
2203
|
+
switch (constraint.kind) {
|
|
2204
|
+
case "max":
|
|
2205
|
+
return `.max(${constraint.value})`;
|
|
2206
|
+
case "min":
|
|
2207
|
+
return `.min(${constraint.value})`;
|
|
2208
|
+
case "int":
|
|
2209
|
+
return ".int()";
|
|
2210
|
+
case "positive":
|
|
2211
|
+
return ".positive()";
|
|
2212
|
+
case "negative":
|
|
2213
|
+
return ".negative()";
|
|
2214
|
+
case "nonnegative":
|
|
2215
|
+
return ".nonnegative()";
|
|
2216
|
+
case "nonpositive":
|
|
2217
|
+
return ".nonpositive()";
|
|
2218
|
+
case "maxLength":
|
|
2219
|
+
return `.max(${constraint.value})`;
|
|
2220
|
+
case "minLength":
|
|
2221
|
+
return `.min(${constraint.value})`;
|
|
2222
|
+
case "length":
|
|
2223
|
+
return `.length(${constraint.value})`;
|
|
2224
|
+
case "regex": {
|
|
2225
|
+
const flags = constraint.flags ?? "";
|
|
2226
|
+
return `.regex(new RegExp(${JSON.stringify(constraint.pattern)}${flags ? `, ${JSON.stringify(flags)}` : ""}))`;
|
|
2227
|
+
}
|
|
2228
|
+
case "email":
|
|
2229
|
+
return ".email()";
|
|
2230
|
+
case "url":
|
|
2231
|
+
return ".url()";
|
|
2232
|
+
case "uuid":
|
|
2233
|
+
return ".uuid()";
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
function baseExpression(type, ctx) {
|
|
2237
|
+
switch (type.kind) {
|
|
2238
|
+
case "string":
|
|
2239
|
+
return "z.string()";
|
|
2240
|
+
case "number":
|
|
2241
|
+
return "z.number()";
|
|
2242
|
+
case "boolean":
|
|
2243
|
+
return "z.boolean()";
|
|
2244
|
+
case "bigint":
|
|
2245
|
+
return "z.never()";
|
|
2246
|
+
case "null":
|
|
2247
|
+
return "z.null()";
|
|
2248
|
+
case "undefined":
|
|
2249
|
+
return "z.undefined()";
|
|
2250
|
+
case "any":
|
|
2251
|
+
case "unknown":
|
|
2252
|
+
return "z.unknown()";
|
|
2253
|
+
case "literal":
|
|
2254
|
+
return `z.literal(${JSON.stringify(type.value)})`;
|
|
2255
|
+
case "array":
|
|
2256
|
+
return `z.array(${runtimeTypeToZodExpression(type.element, ctx)})`;
|
|
2257
|
+
case "tuple":
|
|
2258
|
+
return generateTupleExpression(type.elements, ctx);
|
|
2259
|
+
case "object":
|
|
2260
|
+
return generateObjectExpression(type.properties, ctx);
|
|
2261
|
+
case "union":
|
|
2262
|
+
return generateUnionExpression(type.members, ctx);
|
|
2263
|
+
case "date":
|
|
2264
|
+
return 'z.preprocess((v) => (typeof v === "string" ? new Date(v) : v), z.date())';
|
|
2265
|
+
case "record":
|
|
2266
|
+
return `z.record(${runtimeTypeToZodExpression(type.key, ctx)}, ${runtimeTypeToZodExpression(type.value, ctx)})`;
|
|
2267
|
+
case "ref":
|
|
2268
|
+
if (type.name === ctx.entryTypeName) {
|
|
2269
|
+
return `${ctx.entryExportName}Schema`;
|
|
2270
|
+
}
|
|
2271
|
+
return `${type.name}Schema`;
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
var COERCE_NUMBER_HELPER = 'export const coerceNumber = (v) => typeof v === "string" && v.trim() !== "" && !isNaN(Number(v)) ? Number(v) : v;';
|
|
2275
|
+
var COERCE_BOOLEAN_HELPER = 'export const coerceBoolean = (v) => v === "true" || v === "1" ? true : v === "false" || v === "0" ? false : v;';
|
|
2276
|
+
var HELPERS_FILENAME = "faapi-helpers.js";
|
|
2277
|
+
function generateHelpersFileSource() {
|
|
2278
|
+
return [
|
|
2279
|
+
"// faapi-helpers.js \u2014 faapi \u81EA\u52A8\u751F\u6210\u7684\u516C\u7528\u51FD\u6570\uFF08\u8BF7\u52FF\u624B\u52A8\u7F16\u8F91\uFF09",
|
|
2280
|
+
COERCE_NUMBER_HELPER,
|
|
2281
|
+
COERCE_BOOLEAN_HELPER,
|
|
2282
|
+
""
|
|
2283
|
+
].join("\n");
|
|
2284
|
+
}
|
|
2285
|
+
function usesCoerceHelpers(code) {
|
|
2286
|
+
return code.includes("coerceNumber") || code.includes("coerceBoolean");
|
|
2287
|
+
}
|
|
2288
|
+
function wrapCoercePreprocess(kind, inner) {
|
|
2289
|
+
if (kind === "number") {
|
|
2290
|
+
return `z.preprocess(coerceNumber, ${inner})`;
|
|
2291
|
+
}
|
|
2292
|
+
return `z.preprocess(coerceBoolean, ${inner})`;
|
|
2293
|
+
}
|
|
2294
|
+
function generateTupleExpression(elements, ctx) {
|
|
2295
|
+
const fixedExprs = [];
|
|
2296
|
+
const fixedOptional = [];
|
|
2297
|
+
let restExpression = "";
|
|
2298
|
+
let restStarted = false;
|
|
2299
|
+
for (const el of elements) {
|
|
2300
|
+
if (el.rest) {
|
|
2301
|
+
restExpression = runtimeTypeToZodExpression(el.type, ctx);
|
|
2302
|
+
restStarted = true;
|
|
2303
|
+
} else if (!restStarted) {
|
|
2304
|
+
fixedExprs.push(runtimeTypeToZodExpression(el.type, ctx));
|
|
2305
|
+
fixedOptional.push(el.optional);
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
2308
|
+
if (restExpression) {
|
|
2309
|
+
return `z.tuple([${fixedExprs.join(", ")}]).rest(${restExpression})`;
|
|
2310
|
+
}
|
|
2311
|
+
const hasOptional = fixedOptional.some((o) => o);
|
|
2312
|
+
if (!hasOptional) {
|
|
2313
|
+
return `z.tuple([${fixedExprs.join(", ")}])`;
|
|
2314
|
+
}
|
|
2315
|
+
const variants = [];
|
|
2316
|
+
for (let len = fixedExprs.length; len >= 0; len--) {
|
|
2317
|
+
const removed = fixedOptional.slice(len);
|
|
2318
|
+
if (removed.length > 0 && removed.some((o) => !o)) {
|
|
2319
|
+
break;
|
|
2320
|
+
}
|
|
2321
|
+
const subset = fixedExprs.slice(0, len);
|
|
2322
|
+
variants.push(`z.tuple([${subset.join(", ")}])`);
|
|
2323
|
+
}
|
|
2324
|
+
variants.reverse();
|
|
2325
|
+
if (variants.length === 1) {
|
|
2326
|
+
return variants[0];
|
|
2327
|
+
}
|
|
2328
|
+
return `z.union([${variants.join(", ")}])`;
|
|
2329
|
+
}
|
|
2330
|
+
function generateObjectExpression(properties, ctx) {
|
|
2331
|
+
const fields = properties.map((prop) => {
|
|
2332
|
+
const expr = runtimeTypeToZodExpression(prop.type, ctx, prop.constraints);
|
|
2333
|
+
const finalExpr = prop.optional ? `${expr}.optional()` : expr;
|
|
2334
|
+
return `${JSON.stringify(prop.name)}: ${finalExpr}`;
|
|
2335
|
+
});
|
|
2336
|
+
return `z.object({ ${fields.join(", ")} })`;
|
|
2337
|
+
}
|
|
2338
|
+
function generateUnionExpression(members, ctx) {
|
|
2339
|
+
const hasNull = members.some((m) => m.kind === "null");
|
|
2340
|
+
const nonNull = members.filter((m) => m.kind !== "null");
|
|
2341
|
+
if (hasNull && nonNull.length === 1) {
|
|
2342
|
+
return `${runtimeTypeToZodExpression(nonNull[0], ctx)}.nullable()`;
|
|
2343
|
+
}
|
|
2344
|
+
if (hasNull) {
|
|
2345
|
+
const unionInner2 = nonNull.map((m) => runtimeTypeToZodExpression(m, ctx)).join(", ");
|
|
2346
|
+
return `z.union([${unionInner2}]).nullable()`;
|
|
2347
|
+
}
|
|
2348
|
+
const unionInner = members.map((m) => runtimeTypeToZodExpression(m, ctx)).join(", ");
|
|
2349
|
+
return `z.union([${unionInner}])`;
|
|
2350
|
+
}
|
|
2351
|
+
function generateNamedTypeDeclaration(name, type, ctx) {
|
|
2352
|
+
const expr = runtimeTypeToZodExpression(type, ctx);
|
|
2353
|
+
const hasRef = containsRef(type, /* @__PURE__ */ new Set([name]));
|
|
2354
|
+
if (hasRef) {
|
|
2355
|
+
return `const ${name}Schema = z.lazy(() => ${expr});`;
|
|
2356
|
+
}
|
|
2357
|
+
return `const ${name}Schema = ${expr};`;
|
|
2358
|
+
}
|
|
2359
|
+
function containsRef(type, visited) {
|
|
2360
|
+
switch (type.kind) {
|
|
2361
|
+
case "ref":
|
|
2362
|
+
return visited.has(type.name);
|
|
2363
|
+
case "array":
|
|
2364
|
+
return containsRef(type.element, visited);
|
|
2365
|
+
case "tuple":
|
|
2366
|
+
return type.elements.some((el) => containsRef(el.type, visited));
|
|
2367
|
+
case "object":
|
|
2368
|
+
return type.properties.some((prop) => containsRef(prop.type, visited));
|
|
2369
|
+
case "union":
|
|
2370
|
+
return type.members.some((m) => containsRef(m, visited));
|
|
2371
|
+
case "record":
|
|
2372
|
+
return containsRef(type.key, visited) || containsRef(type.value, visited);
|
|
2373
|
+
default:
|
|
2374
|
+
return false;
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
function generateZodSchemaSource(typeInfo, resolveType, exportName, coerce = false) {
|
|
2378
|
+
const ctx = new CodeGenContext(resolveType);
|
|
2379
|
+
const name = exportName ?? typeInfo.name;
|
|
2380
|
+
ctx.entryTypeName = typeInfo.name;
|
|
2381
|
+
ctx.entryExportName = name;
|
|
2382
|
+
ctx.coerce = coerce;
|
|
2383
|
+
collectNamedTypes(typeInfo.runtimeType, ctx);
|
|
2384
|
+
ctx.namedTypes.delete(typeInfo.name);
|
|
2385
|
+
const lines = [];
|
|
2386
|
+
lines.push("import { z } from 'zod';");
|
|
2387
|
+
lines.push("");
|
|
2388
|
+
for (const [n, type] of ctx.namedTypes) {
|
|
2389
|
+
lines.push(generateNamedTypeDeclaration(n, type, ctx));
|
|
2390
|
+
}
|
|
2391
|
+
if (ctx.namedTypes.size > 0) lines.push("");
|
|
2392
|
+
const entryExpr = runtimeTypeToZodExpression(typeInfo.runtimeType, ctx);
|
|
2393
|
+
const hasSelfRef = containsRef(typeInfo.runtimeType, /* @__PURE__ */ new Set([typeInfo.name]));
|
|
2394
|
+
if (hasSelfRef) {
|
|
2395
|
+
lines.push(`export const ${name}Schema = z.lazy(() => ${entryExpr});`);
|
|
2396
|
+
} else {
|
|
2397
|
+
lines.push(`export const ${name}Schema = ${entryExpr};`);
|
|
2398
|
+
}
|
|
2399
|
+
return lines.join("\n");
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
// src/cli/generateSchemaFiles.ts
|
|
2403
|
+
function getSchemaOutputPath(sourceFile, appDir, outDir, rootDir) {
|
|
2404
|
+
let rel = sourceFile.replace(/\\/g, "/");
|
|
2405
|
+
if (appDir !== "." && rel.startsWith(`${appDir}/`)) {
|
|
2406
|
+
rel = rel.slice(appDir.length + 1);
|
|
2407
|
+
}
|
|
2408
|
+
const idx = rel.lastIndexOf("/");
|
|
2409
|
+
const relDir = idx >= 0 ? rel.slice(0, idx) : "";
|
|
2410
|
+
return path4.resolve(rootDir, outDir, relDir, "zod.js");
|
|
2411
|
+
}
|
|
2412
|
+
function getRuntimeSchemaPath(filePath, appDir, outDir, rootDir) {
|
|
2413
|
+
let rel = filePath.replace(/\\/g, "/");
|
|
2414
|
+
if (appDir !== "." && rel.startsWith(`${appDir}/`)) {
|
|
2415
|
+
rel = rel.slice(appDir.length + 1);
|
|
2416
|
+
} else if (rel.startsWith(`${outDir}/`)) {
|
|
2417
|
+
rel = rel.slice(outDir.length + 1);
|
|
2418
|
+
}
|
|
2419
|
+
const idx = rel.lastIndexOf("/");
|
|
2420
|
+
const relDir = idx >= 0 ? rel.slice(0, idx) : "";
|
|
2421
|
+
return path4.resolve(rootDir, outDir, relDir, "zod.js");
|
|
2422
|
+
}
|
|
2423
|
+
function getHelpersImportPath(relDir) {
|
|
2424
|
+
if (!relDir) return `./${HELPERS_FILENAME}`;
|
|
2425
|
+
const depth = relDir.split("/").filter(Boolean).length;
|
|
2426
|
+
return `${"../".repeat(depth)}${HELPERS_FILENAME}`;
|
|
2427
|
+
}
|
|
2428
|
+
function generateSchemaFileSource(sources, allTypes, helpersImportPath) {
|
|
2429
|
+
const resolveType = (name) => allTypes.get(name)?.runtimeType;
|
|
2430
|
+
const lines = ["import { z } from 'zod';"];
|
|
2431
|
+
const schemaBlocks = [];
|
|
2432
|
+
for (const source of sources) {
|
|
2433
|
+
const { schemaName, typeInfo } = source;
|
|
2434
|
+
if (!typeInfo) {
|
|
2435
|
+
continue;
|
|
2436
|
+
}
|
|
2437
|
+
const coerce = /(?:Query|Params)$/.test(schemaName);
|
|
2438
|
+
const block = [`// ${schemaName}`];
|
|
2439
|
+
const schemaCode = generateZodSchemaSource(typeInfo, resolveType, schemaName, coerce).replace(
|
|
2440
|
+
/^import \{ z \} from 'zod';\s*\n\s*\n/,
|
|
2441
|
+
""
|
|
2442
|
+
);
|
|
2443
|
+
block.push(schemaCode);
|
|
2444
|
+
block.push("");
|
|
2445
|
+
schemaBlocks.push(block.join("\n"));
|
|
2446
|
+
}
|
|
2447
|
+
const allSchemaCode = schemaBlocks.join("\n");
|
|
2448
|
+
if (helpersImportPath && usesCoerceHelpers(allSchemaCode)) {
|
|
2449
|
+
lines.push(`import { coerceNumber, coerceBoolean } from '${helpersImportPath}';`);
|
|
2450
|
+
}
|
|
2451
|
+
lines.push("");
|
|
2452
|
+
lines.push(...schemaBlocks);
|
|
2453
|
+
return lines.join("\n").replace(/\n+$/, "\n");
|
|
2454
|
+
}
|
|
2455
|
+
async function generateSchemaFiles(routes, rootDir, appDir, outDir) {
|
|
2456
|
+
if (routes.length === 0) return;
|
|
2457
|
+
const { sources, allTypesByFile } = collectRouteSchemaSources(routes, rootDir);
|
|
2458
|
+
const sourcesByFile = /* @__PURE__ */ new Map();
|
|
2459
|
+
for (const source of sources) {
|
|
2460
|
+
let list = sourcesByFile.get(source.filePath);
|
|
2461
|
+
if (!list) {
|
|
2462
|
+
list = [];
|
|
2463
|
+
sourcesByFile.set(source.filePath, list);
|
|
2464
|
+
}
|
|
2465
|
+
list.push(source);
|
|
2466
|
+
}
|
|
2467
|
+
const fileEntries = [];
|
|
2468
|
+
for (const [filePath, fileSources] of sourcesByFile) {
|
|
2469
|
+
const relFile = path4.relative(rootDir, filePath).replace(/\\/g, "/");
|
|
2470
|
+
const outputPath = getSchemaOutputPath(relFile, appDir, outDir, rootDir);
|
|
2471
|
+
const allTypes = allTypesByFile.get(filePath) ?? /* @__PURE__ */ new Map();
|
|
2472
|
+
let relForDir = relFile;
|
|
2473
|
+
if (appDir !== "." && relForDir.startsWith(`${appDir}/`)) {
|
|
2474
|
+
relForDir = relForDir.slice(appDir.length + 1);
|
|
2475
|
+
}
|
|
2476
|
+
const dirIdx = relForDir.lastIndexOf("/");
|
|
2477
|
+
const zodRelDir = dirIdx >= 0 ? relForDir.slice(0, dirIdx) : "";
|
|
2478
|
+
const helpersImportPath = getHelpersImportPath(zodRelDir);
|
|
2479
|
+
const source = generateSchemaFileSource(fileSources, allTypes, helpersImportPath);
|
|
2480
|
+
fileEntries.push({ outputPath, source });
|
|
2481
|
+
}
|
|
2482
|
+
const allSourceCode = fileEntries.map((e) => e.source).join("\n");
|
|
2483
|
+
if (usesCoerceHelpers(allSourceCode)) {
|
|
2484
|
+
const helpersPath = path4.resolve(rootDir, outDir, HELPERS_FILENAME);
|
|
2485
|
+
await writeSchemaFile(helpersPath, generateHelpersFileSource());
|
|
2486
|
+
}
|
|
2487
|
+
await Promise.all(
|
|
2488
|
+
fileEntries.map(({ outputPath, source }) => writeSchemaFile(outputPath, source))
|
|
2489
|
+
);
|
|
2490
|
+
}
|
|
2491
|
+
async function writeSchemaFile(outputPath, source) {
|
|
2492
|
+
await fs2.mkdir(path4.dirname(outputPath), { recursive: true });
|
|
2493
|
+
await fs2.writeFile(outputPath, source, "utf-8");
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
// src/server/createServer.ts
|
|
2497
|
+
var DEFAULT_BODY_LIMIT = 10 * 1024 * 1024;
|
|
2498
|
+
function toWebRequest(req, bodyLimit = DEFAULT_BODY_LIMIT) {
|
|
2499
|
+
const forwardedProto = req.headers["x-forwarded-proto"];
|
|
2500
|
+
const protocol = Array.isArray(forwardedProto) ? forwardedProto[0]?.split(",")[0]?.trim() ?? "http" : forwardedProto?.split(",")[0]?.trim() ?? "http";
|
|
2501
|
+
const host = req.headers.host ?? "localhost";
|
|
2502
|
+
const url = new URL(req.url ?? "/", `${protocol}://${host}`);
|
|
2503
|
+
const headers = nodeHttpToWebHeaders(req);
|
|
2504
|
+
const method = req.method ?? "GET";
|
|
2505
|
+
if (method === "GET" || method === "HEAD") {
|
|
2506
|
+
return new Request(url.toString(), { method, headers });
|
|
2507
|
+
}
|
|
2508
|
+
const stream = Readable2.toWeb(req);
|
|
2509
|
+
const limitedStream = limitStreamSize(stream, bodyLimit);
|
|
2510
|
+
return new Request(url.toString(), {
|
|
2511
|
+
method,
|
|
2512
|
+
headers,
|
|
2513
|
+
body: limitedStream,
|
|
2514
|
+
duplex: "half"
|
|
2515
|
+
});
|
|
2516
|
+
}
|
|
2517
|
+
function limitStreamSize(stream, maxSize) {
|
|
2518
|
+
let totalSize = 0;
|
|
2519
|
+
const reader = stream.getReader();
|
|
2520
|
+
return new ReadableStream({
|
|
2521
|
+
async pull(controller) {
|
|
2522
|
+
const { done, value } = await reader.read();
|
|
2523
|
+
if (done) {
|
|
2524
|
+
controller.close();
|
|
2525
|
+
reader.releaseLock();
|
|
2526
|
+
return;
|
|
2527
|
+
}
|
|
2528
|
+
totalSize += value.byteLength;
|
|
2529
|
+
if (totalSize > maxSize) {
|
|
2530
|
+
controller.error(new Error(`\u8BF7\u6C42\u4F53\u8D85\u8FC7\u5927\u5C0F\u9650\u5236 ${maxSize} \u5B57\u8282`));
|
|
2531
|
+
reader.releaseLock();
|
|
2532
|
+
return;
|
|
2533
|
+
}
|
|
2534
|
+
controller.enqueue(value);
|
|
2535
|
+
},
|
|
2536
|
+
cancel(reason) {
|
|
2537
|
+
reader.cancel(reason);
|
|
2538
|
+
}
|
|
2539
|
+
});
|
|
2540
|
+
}
|
|
2541
|
+
function findAllowedMethods(routes, path9) {
|
|
2542
|
+
const methods = /* @__PURE__ */ new Set();
|
|
2543
|
+
for (const route of routes) {
|
|
2544
|
+
if (route.urlPath === path9) {
|
|
2545
|
+
methods.add(route.method);
|
|
2546
|
+
continue;
|
|
2547
|
+
}
|
|
2548
|
+
if (route.isDynamic) {
|
|
2549
|
+
const params = matchDynamicPath(route.urlPath, path9, route.paramNames, route.isCatchAll);
|
|
2550
|
+
if (params !== null) {
|
|
2551
|
+
methods.add(route.method);
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
return Array.from(methods);
|
|
2556
|
+
}
|
|
2557
|
+
function createServer(options) {
|
|
2558
|
+
const {
|
|
2559
|
+
routes,
|
|
2560
|
+
rootDir,
|
|
2561
|
+
appDir,
|
|
2562
|
+
outDir,
|
|
2563
|
+
cors: corsOption,
|
|
2564
|
+
onError,
|
|
2565
|
+
config,
|
|
2566
|
+
wsRoutes,
|
|
2567
|
+
middlewares: globalMiddlewares,
|
|
2568
|
+
injectors: globalInjectors,
|
|
2569
|
+
helmet: helmetOption,
|
|
2570
|
+
bodyLimit = DEFAULT_BODY_LIMIT,
|
|
2571
|
+
http2: http2Option
|
|
2572
|
+
} = options;
|
|
2573
|
+
const routesRef = { current: routes, wsCurrent: wsRoutes ?? [] };
|
|
2574
|
+
const configMiddlewares = [];
|
|
2575
|
+
const corsMiddleware = corsOption === false ? null : corsOption === true || corsOption === void 0 ? cors() : cors(corsOption);
|
|
2576
|
+
if (corsMiddleware) configMiddlewares.push(corsMiddleware);
|
|
2577
|
+
if (helmetOption) {
|
|
2578
|
+
const helmOpts = typeof helmetOption === "object" ? helmetOption : {};
|
|
2579
|
+
configMiddlewares.push(helmet(helmOpts));
|
|
2580
|
+
}
|
|
2581
|
+
const server = (() => {
|
|
2582
|
+
if (http2Option) {
|
|
2583
|
+
const h2Opts = typeof http2Option === "object" ? http2Option : {};
|
|
2584
|
+
return createHttp2SecureServer({
|
|
2585
|
+
key: h2Opts.key ? readFileSync(h2Opts.key) : void 0,
|
|
2586
|
+
cert: h2Opts.cert ? readFileSync(h2Opts.cert) : void 0,
|
|
2587
|
+
allowHTTP1: true
|
|
2588
|
+
});
|
|
2589
|
+
}
|
|
2590
|
+
return createHttpServer();
|
|
2591
|
+
})();
|
|
2592
|
+
server.on("request", (req, res) => {
|
|
2593
|
+
const currentRoutes = routesRef.current;
|
|
2594
|
+
handleRequest(
|
|
2595
|
+
currentRoutes,
|
|
2596
|
+
rootDir,
|
|
2597
|
+
appDir,
|
|
2598
|
+
outDir,
|
|
2599
|
+
req,
|
|
2600
|
+
res,
|
|
2601
|
+
configMiddlewares,
|
|
2602
|
+
onError,
|
|
2603
|
+
config,
|
|
2604
|
+
globalMiddlewares,
|
|
2605
|
+
globalInjectors,
|
|
2606
|
+
bodyLimit
|
|
2607
|
+
).catch(() => {
|
|
2608
|
+
res.statusCode = 500;
|
|
2609
|
+
res.end();
|
|
2610
|
+
});
|
|
2611
|
+
});
|
|
2612
|
+
if (routesRef.wsCurrent.length > 0) {
|
|
2613
|
+
attachWebSocket({ server, routesRef, rootDir, config, globalMiddlewares });
|
|
2614
|
+
}
|
|
2615
|
+
return { server, routesRef };
|
|
2616
|
+
}
|
|
2617
|
+
async function handleRequest(routes, rootDir, appDir, outDir, req, res, configMiddlewares, onError, config, globalMiddlewares, globalInjectors, bodyLimit) {
|
|
2618
|
+
const request = toWebRequest(req, bodyLimit);
|
|
2619
|
+
const method = request.method.toUpperCase();
|
|
2620
|
+
const urlPath = new URL(request.url).pathname;
|
|
2621
|
+
const ctx = createContext(request, {}, config, getClientIp(req));
|
|
2622
|
+
const meta = ctx.meta;
|
|
2623
|
+
const routePipeline = async () => {
|
|
2624
|
+
const match = matchRoute(routes, method, urlPath);
|
|
2625
|
+
if (!match) {
|
|
2626
|
+
const allowedMethods = findAllowedMethods(routes, urlPath);
|
|
2627
|
+
if (allowedMethods.length > 0) {
|
|
2628
|
+
throw new MethodNotAllowedError(method, urlPath, allowedMethods);
|
|
2629
|
+
}
|
|
2630
|
+
throw new RouteNotFoundError(urlPath);
|
|
2631
|
+
}
|
|
2632
|
+
ctx.params = match.params;
|
|
2633
|
+
const { route } = match;
|
|
2634
|
+
const absoluteFilePath = path5.resolve(rootDir, route.filePath);
|
|
2635
|
+
const routeModule = await loadRouteModule(absoluteFilePath, route.method);
|
|
2636
|
+
const input = await resolveInput(route.method, request);
|
|
2637
|
+
const inputType = getInputTypeForMethod(route.method);
|
|
2638
|
+
const schemaPath = getRuntimeSchemaPath(route.filePath, appDir, outDir, rootDir);
|
|
2639
|
+
const result = await validateInput(schemaPath, route.method, inputType, input);
|
|
2640
|
+
if (!result.valid) {
|
|
2641
|
+
throw new ValidationError("\u53C2\u6570\u6821\u9A8C\u5931\u8D25", result.issues);
|
|
2642
|
+
}
|
|
2643
|
+
const body = hasBody(route.method) ? result.data : void 0;
|
|
2644
|
+
const mergedInjectors = globalInjectors ? { ...globalInjectors, ...route.injectors } : route.injectors;
|
|
2645
|
+
const response = await invokeHandler(
|
|
2646
|
+
routeModule.handler,
|
|
2647
|
+
ctx,
|
|
2648
|
+
body,
|
|
2649
|
+
route.middlewares,
|
|
2650
|
+
mergedInjectors
|
|
2651
|
+
);
|
|
2652
|
+
return response;
|
|
2653
|
+
};
|
|
2654
|
+
try {
|
|
2655
|
+
let response;
|
|
2656
|
+
const outerMiddlewares = [];
|
|
2657
|
+
if (configMiddlewares.length > 0) outerMiddlewares.push(...configMiddlewares);
|
|
2658
|
+
if (globalMiddlewares && globalMiddlewares.length > 0) {
|
|
2659
|
+
outerMiddlewares.push(...globalMiddlewares);
|
|
2660
|
+
}
|
|
2661
|
+
if (outerMiddlewares.length > 0) {
|
|
2662
|
+
response = await compose(outerMiddlewares, ctx, routePipeline);
|
|
2663
|
+
} else {
|
|
2664
|
+
response = await routePipeline();
|
|
2665
|
+
}
|
|
2666
|
+
await sendNodeResponse(response, res);
|
|
2667
|
+
} catch (err) {
|
|
2668
|
+
const errorResponse = buildErrorResponse(err);
|
|
2669
|
+
await sendNodeResponse(mergeMeta(errorResponse, meta), res);
|
|
2670
|
+
if (onError) {
|
|
2671
|
+
try {
|
|
2672
|
+
await onError(err, ctx);
|
|
2673
|
+
} catch {
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
// src/server/startServer.ts
|
|
2680
|
+
function applyPluginWrappers(server, handlerWrappers, upgradeWrappers) {
|
|
2681
|
+
if (handlerWrappers.length > 0) {
|
|
2682
|
+
const listeners = server.listeners("request");
|
|
2683
|
+
const original = listeners[0];
|
|
2684
|
+
if (original) {
|
|
2685
|
+
server.removeAllListeners("request");
|
|
2686
|
+
let handler = original;
|
|
2687
|
+
for (const wrap of handlerWrappers) {
|
|
2688
|
+
handler = wrap(handler);
|
|
2689
|
+
}
|
|
2690
|
+
server.on("request", handler);
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
if (upgradeWrappers.length > 0) {
|
|
2694
|
+
const listeners = server.listeners("upgrade");
|
|
2695
|
+
const original = listeners[0];
|
|
2696
|
+
server.removeAllListeners("upgrade");
|
|
2697
|
+
let upgrade = original;
|
|
2698
|
+
for (const wrap of upgradeWrappers) {
|
|
2699
|
+
upgrade = wrap(upgrade);
|
|
2700
|
+
}
|
|
2701
|
+
if (upgrade) {
|
|
2702
|
+
server.on("upgrade", upgrade);
|
|
2703
|
+
}
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
|
|
2707
|
+
// src/cli/generateRoutes.ts
|
|
2708
|
+
import fs3 from "fs";
|
|
2709
|
+
import path6 from "path";
|
|
2710
|
+
|
|
2711
|
+
// src/middleware/loadMiddlewares.ts
|
|
2712
|
+
var middlewareCache = /* @__PURE__ */ new Map();
|
|
2713
|
+
function invalidateMiddlewareCache() {
|
|
2714
|
+
middlewareCache.clear();
|
|
2715
|
+
}
|
|
2716
|
+
function getCachedMiddlewares(absPath) {
|
|
2717
|
+
return middlewareCache.get(absPath);
|
|
2718
|
+
}
|
|
2719
|
+
function setCachedMiddlewares(absPath, bundle) {
|
|
2720
|
+
middlewareCache.set(absPath, bundle);
|
|
2721
|
+
}
|
|
2722
|
+
async function loadMiddlewaresFile(filePath) {
|
|
2723
|
+
try {
|
|
2724
|
+
const module = await importWithCacheBust(filePath);
|
|
2725
|
+
const middlewares = module.default ?? module.middlewares ?? [];
|
|
2726
|
+
if (!Array.isArray(middlewares)) {
|
|
2727
|
+
console.warn(`[faapi] middlewares.ts \u5E94\u5BFC\u51FA\u6570\u7EC4\uFF0C\u5DF2\u5FFD\u7565: ${filePath}`);
|
|
2728
|
+
return { middlewares: [], injectors: {} };
|
|
2729
|
+
}
|
|
2730
|
+
const validMiddlewares = middlewares.filter((m) => {
|
|
2731
|
+
if (typeof m !== "function") {
|
|
2732
|
+
console.warn(`[faapi] \u65E0\u6548\u7684\u4E2D\u95F4\u4EF6\u9879\uFF08\u5E94\u4E3A\u51FD\u6570\uFF09\uFF0C\u5DF2\u5FFD\u7565: ${typeof m}`);
|
|
2733
|
+
return false;
|
|
2734
|
+
}
|
|
2735
|
+
return true;
|
|
2736
|
+
});
|
|
2737
|
+
const injectors = module.injectors ?? {};
|
|
2738
|
+
if (typeof injectors !== "object" || injectors === null) {
|
|
2739
|
+
console.warn(`[faapi] injectors \u5E94\u5BFC\u51FA\u5BF9\u8C61\uFF0C\u5DF2\u5FFD\u7565: ${filePath}`);
|
|
2740
|
+
return { middlewares: validMiddlewares, injectors: {} };
|
|
2741
|
+
}
|
|
2742
|
+
const validInjectors = {};
|
|
2743
|
+
for (const [name, injector] of Object.entries(injectors)) {
|
|
2744
|
+
if (typeof injector !== "function") {
|
|
2745
|
+
console.warn(`[faapi] \u6CE8\u5165\u5668 ${name} \u5E94\u4E3A\u51FD\u6570\uFF0C\u5DF2\u5FFD\u7565`);
|
|
2746
|
+
continue;
|
|
2747
|
+
}
|
|
2748
|
+
validInjectors[name] = injector;
|
|
2749
|
+
}
|
|
2750
|
+
return { middlewares: validMiddlewares, injectors: validInjectors };
|
|
2751
|
+
} catch {
|
|
2752
|
+
return { middlewares: [], injectors: {} };
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2756
|
+
// src/cli/generateRoutes.ts
|
|
2757
|
+
async function hydrateRoutes(manifest) {
|
|
2758
|
+
const hydrateRoute = async (serialized) => {
|
|
2759
|
+
const bundle = await loadMiddlewarePaths(serialized.middlewarePaths);
|
|
2760
|
+
return {
|
|
2761
|
+
method: serialized.method,
|
|
2762
|
+
urlPath: serialized.urlPath,
|
|
2763
|
+
filePath: serialized.filePath,
|
|
2764
|
+
paramNames: serialized.paramNames,
|
|
2765
|
+
isDynamic: serialized.isDynamic,
|
|
2766
|
+
isCatchAll: serialized.isCatchAll,
|
|
2767
|
+
middlewares: bundle?.middlewares,
|
|
2768
|
+
injectors: bundle?.injectors
|
|
2769
|
+
};
|
|
2770
|
+
};
|
|
2771
|
+
const hydrateWsRoute = async (serialized) => {
|
|
2772
|
+
const bundle = await loadMiddlewarePaths(serialized.middlewarePaths);
|
|
2773
|
+
return {
|
|
2774
|
+
urlPath: serialized.urlPath,
|
|
2775
|
+
filePath: serialized.filePath,
|
|
2776
|
+
paramNames: serialized.paramNames,
|
|
2777
|
+
isDynamic: serialized.isDynamic,
|
|
2778
|
+
isCatchAll: serialized.isCatchAll,
|
|
2779
|
+
middlewares: bundle?.middlewares,
|
|
2780
|
+
injectors: bundle?.injectors
|
|
2781
|
+
};
|
|
2782
|
+
};
|
|
2783
|
+
const routes = await Promise.all(manifest.routes.map(hydrateRoute));
|
|
2784
|
+
const wsRoutes = await Promise.all(manifest.wsRoutes.map(hydrateWsRoute));
|
|
2785
|
+
return { routes, wsRoutes };
|
|
2786
|
+
}
|
|
2787
|
+
async function loadMiddlewarePaths(middlewarePaths) {
|
|
2788
|
+
if (middlewarePaths.length === 0) return void 0;
|
|
2789
|
+
const mergedMiddlewares = [];
|
|
2790
|
+
const mergedInjectors = {};
|
|
2791
|
+
for (const absMwPath of middlewarePaths) {
|
|
2792
|
+
let bundle = getCachedMiddlewares(absMwPath);
|
|
2793
|
+
if (bundle === void 0) {
|
|
2794
|
+
bundle = await loadMiddlewaresFile(absMwPath);
|
|
2795
|
+
setCachedMiddlewares(absMwPath, bundle);
|
|
2796
|
+
}
|
|
2797
|
+
mergedMiddlewares.push(...bundle.middlewares);
|
|
2798
|
+
for (const [name, injector] of Object.entries(bundle.injectors)) {
|
|
2799
|
+
mergedInjectors[name] = injector;
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
return { middlewares: mergedMiddlewares, injectors: mergedInjectors };
|
|
2803
|
+
}
|
|
2804
|
+
|
|
2805
|
+
// src/cli/loadPlugins.ts
|
|
2806
|
+
async function loadPlugins(declarations, ctx) {
|
|
2807
|
+
const handlerWrappers = [];
|
|
2808
|
+
const upgradeWrappers = [];
|
|
2809
|
+
if (!declarations || declarations.length === 0) {
|
|
2810
|
+
return { handlerWrappers, upgradeWrappers };
|
|
2811
|
+
}
|
|
2812
|
+
const fullCtx = {
|
|
2813
|
+
...ctx,
|
|
2814
|
+
wrapHandler: (fn) => {
|
|
2815
|
+
handlerWrappers.push(fn);
|
|
2816
|
+
},
|
|
2817
|
+
wrapUpgradeHandler: (fn) => {
|
|
2818
|
+
upgradeWrappers.push(fn);
|
|
2819
|
+
}
|
|
2820
|
+
};
|
|
2821
|
+
const loaded = /* @__PURE__ */ new Set();
|
|
2822
|
+
for (const decl of declarations) {
|
|
2823
|
+
const { specifier, options, enable } = resolveDeclaration(decl);
|
|
2824
|
+
if (enable === false) continue;
|
|
2825
|
+
if (loaded.has(specifier)) {
|
|
2826
|
+
console.warn(`! Plugin already loaded: ${specifier}, skipping`);
|
|
2827
|
+
continue;
|
|
2828
|
+
}
|
|
2829
|
+
loaded.add(specifier);
|
|
2830
|
+
try {
|
|
2831
|
+
const mod = await import(specifier);
|
|
2832
|
+
const plugin = mod.default ?? mod;
|
|
2833
|
+
if (typeof plugin.setup !== "function") {
|
|
2834
|
+
console.warn(`! Plugin ${specifier} has no setup function, skipping`);
|
|
2835
|
+
continue;
|
|
2836
|
+
}
|
|
2837
|
+
await plugin.setup({ ...fullCtx, options });
|
|
2838
|
+
console.log(`- Plugin loaded: ${plugin.name ?? specifier}`);
|
|
2839
|
+
} catch (err) {
|
|
2840
|
+
console.warn(
|
|
2841
|
+
`! Failed to load plugin ${specifier}: ${err instanceof Error ? err.message : String(err)}`
|
|
2842
|
+
);
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
return { handlerWrappers, upgradeWrappers };
|
|
2846
|
+
}
|
|
2847
|
+
function resolveDeclaration(decl) {
|
|
2848
|
+
if (typeof decl === "string") {
|
|
2849
|
+
return { specifier: decl };
|
|
2850
|
+
}
|
|
2851
|
+
if (Array.isArray(decl)) {
|
|
2852
|
+
const [specifier, options] = decl;
|
|
2853
|
+
return { specifier, options };
|
|
2854
|
+
}
|
|
2855
|
+
if ("package" in decl) {
|
|
2856
|
+
return { specifier: decl.package, options: decl.options, enable: decl.enable };
|
|
2857
|
+
}
|
|
2858
|
+
if ("path" in decl) {
|
|
2859
|
+
return { specifier: decl.path, options: decl.options, enable: decl.enable };
|
|
2860
|
+
}
|
|
2861
|
+
throw new Error(`Invalid plugin declaration: ${JSON.stringify(decl)}`);
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
// src/cli/createAppCore.ts
|
|
2865
|
+
var DEFAULT_OUT_DIR = "dist";
|
|
2866
|
+
var DEFAULT_APP_DIR = "src";
|
|
2867
|
+
var DEFAULT_PORT = 3e3;
|
|
2868
|
+
var ROUTES_FILE = "faapi-routes.js";
|
|
2869
|
+
var FAAPI_CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
2870
|
+
"cors",
|
|
2871
|
+
"lifecycle",
|
|
2872
|
+
"middlewares",
|
|
2873
|
+
"injectors",
|
|
2874
|
+
"extendContext",
|
|
2875
|
+
"plugins",
|
|
2876
|
+
"helmet",
|
|
2877
|
+
"bodyLimit",
|
|
2878
|
+
"logger",
|
|
2879
|
+
"http2"
|
|
2880
|
+
]);
|
|
2881
|
+
function isFaapiConfigKey(key) {
|
|
2882
|
+
return FAAPI_CONFIG_KEYS.has(key);
|
|
2883
|
+
}
|
|
2884
|
+
async function createAppBase(options) {
|
|
2885
|
+
const rootDir = options?.rootDir ?? process.cwd();
|
|
2886
|
+
const outDir = process.env.FAAPI_OUT_DIR ?? DEFAULT_OUT_DIR;
|
|
2887
|
+
const routesPath = path7.resolve(rootDir, outDir, ROUTES_FILE);
|
|
2888
|
+
if (!fs4.existsSync(routesPath)) {
|
|
2889
|
+
throw new Error(
|
|
2890
|
+
`[faapi] ${outDir}/${ROUTES_FILE} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6267\u884C \`faapi build\`\uFF08\u6216 \`faapi dev\`\uFF09\u751F\u6210\u4EA7\u7269\u3002`
|
|
2891
|
+
);
|
|
2892
|
+
}
|
|
2893
|
+
const config = await loadConfig(rootDir, outDir);
|
|
2894
|
+
const appDir = options?.appDir ?? process.env.FAAPI_APP_DIR ?? DEFAULT_APP_DIR;
|
|
2895
|
+
const patterns = appDir === "." ? ["api/**/*.ts"] : [`${appDir}/api/**/*.ts`];
|
|
2896
|
+
const serialized = await importWithCacheBust(routesPath);
|
|
2897
|
+
const hydrated = await hydrateRoutes(serialized);
|
|
2898
|
+
let sorted = sortRoutes(hydrated.routes);
|
|
2899
|
+
let wsRoutes = hydrated.wsRoutes;
|
|
2900
|
+
const conflicts = detectRouteConflicts(sorted);
|
|
2901
|
+
if (conflicts.length > 0) {
|
|
2902
|
+
for (const conflict of conflicts) {
|
|
2903
|
+
console.warn(`! \u8DEF\u7531\u51B2\u7A81: ${conflict.method} ${conflict.urlPath}`);
|
|
2904
|
+
for (const file of conflict.files) {
|
|
2905
|
+
console.warn(` - ${file}`);
|
|
2906
|
+
}
|
|
2907
|
+
}
|
|
2908
|
+
}
|
|
2909
|
+
const pluginConfig = config ? Object.fromEntries(Object.entries(config).filter(([k]) => !isFaapiConfigKey(k))) : {};
|
|
2910
|
+
const { server, routesRef } = createServer({
|
|
2911
|
+
routes: sorted,
|
|
2912
|
+
rootDir,
|
|
2913
|
+
appDir,
|
|
2914
|
+
outDir,
|
|
2915
|
+
cors: config?.cors ?? true,
|
|
2916
|
+
onError: config?.lifecycle?.onError,
|
|
2917
|
+
config: config ?? void 0,
|
|
2918
|
+
wsRoutes,
|
|
2919
|
+
middlewares: config?.middlewares,
|
|
2920
|
+
injectors: config?.injectors,
|
|
2921
|
+
helmet: config?.helmet,
|
|
2922
|
+
bodyLimit: config?.bodyLimit,
|
|
2923
|
+
http2: config?.http2
|
|
2924
|
+
});
|
|
2925
|
+
const { handlerWrappers, upgradeWrappers } = await loadPlugins(config?.plugins, {
|
|
2926
|
+
rootDir,
|
|
2927
|
+
routes: sorted,
|
|
2928
|
+
getRoutes: () => sorted,
|
|
2929
|
+
server,
|
|
2930
|
+
config: pluginConfig
|
|
2931
|
+
});
|
|
2932
|
+
applyPluginWrappers(server, handlerWrappers, upgradeWrappers);
|
|
2933
|
+
let closed = false;
|
|
2934
|
+
const app = {
|
|
2935
|
+
server: null,
|
|
2936
|
+
routes: sorted,
|
|
2937
|
+
wsRoutes,
|
|
2938
|
+
rootDir,
|
|
2939
|
+
async listen(listenPort) {
|
|
2940
|
+
const envPort = process.env.PORT ? Number(process.env.PORT) : void 0;
|
|
2941
|
+
const actualPort = listenPort ?? options?.port ?? envPort ?? DEFAULT_PORT;
|
|
2942
|
+
return new Promise((resolve) => {
|
|
2943
|
+
server.listen(actualPort, async () => {
|
|
2944
|
+
const address = server.address();
|
|
2945
|
+
const p = typeof address === "object" && address !== null ? address.port : actualPort;
|
|
2946
|
+
console.log("faapi server started");
|
|
2947
|
+
console.log(`- Local: http://localhost:${p}`);
|
|
2948
|
+
console.log("- Loaded routes:");
|
|
2949
|
+
for (const route of sorted) {
|
|
2950
|
+
console.log(` ${route.method.padEnd(6)}${route.urlPath} ${route.filePath}`);
|
|
2951
|
+
}
|
|
2952
|
+
if (wsRoutes.length > 0) {
|
|
2953
|
+
console.log("- WebSocket routes:");
|
|
2954
|
+
for (const route of wsRoutes) {
|
|
2955
|
+
console.log(` WS ${route.urlPath} ${route.filePath}`);
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
if (config?.lifecycle?.onClose) {
|
|
2959
|
+
const graceful = async (signal) => {
|
|
2960
|
+
console.log(`
|
|
2961
|
+
- Received ${signal}, shutting down...`);
|
|
2962
|
+
await app.close();
|
|
2963
|
+
process.exit(0);
|
|
2964
|
+
};
|
|
2965
|
+
process.on("SIGTERM", () => void graceful("SIGTERM"));
|
|
2966
|
+
process.on("SIGINT", () => void graceful("SIGINT"));
|
|
2967
|
+
}
|
|
2968
|
+
if (config?.lifecycle?.onReady) {
|
|
2969
|
+
await config.lifecycle.onReady({ rootDir, routes: sorted, server });
|
|
2970
|
+
console.log("- onReady hook executed");
|
|
2971
|
+
}
|
|
2972
|
+
app.server = server;
|
|
2973
|
+
resolve(server);
|
|
2974
|
+
});
|
|
2975
|
+
});
|
|
2976
|
+
},
|
|
2977
|
+
async inject(injectOpts) {
|
|
2978
|
+
const {
|
|
2979
|
+
method = "GET",
|
|
2980
|
+
path: reqPath = "/",
|
|
2981
|
+
headers: reqHeaders = {},
|
|
2982
|
+
query,
|
|
2983
|
+
body
|
|
2984
|
+
} = injectOpts ?? {};
|
|
2985
|
+
const queryStr = query ? "?" + new URLSearchParams(Object.entries(query).map(([k, v]) => [k, String(v)])).toString() : "";
|
|
2986
|
+
return new Promise((resolve, reject) => {
|
|
2987
|
+
const mockRes = {
|
|
2988
|
+
statusCode: 200,
|
|
2989
|
+
_headers: {},
|
|
2990
|
+
_body: Buffer.alloc(0),
|
|
2991
|
+
setHeader(name, value) {
|
|
2992
|
+
this._headers[name.toLowerCase()] = value;
|
|
2993
|
+
},
|
|
2994
|
+
appendHeader(name, value) {
|
|
2995
|
+
const key = name.toLowerCase();
|
|
2996
|
+
const existing = this._headers[key];
|
|
2997
|
+
this._headers[key] = existing ? `${existing}, ${value}` : value;
|
|
2998
|
+
},
|
|
2999
|
+
writeHead(status, headers) {
|
|
3000
|
+
this.statusCode = status;
|
|
3001
|
+
if (headers) {
|
|
3002
|
+
Object.assign(this._headers, headers);
|
|
3003
|
+
}
|
|
3004
|
+
},
|
|
3005
|
+
end(data) {
|
|
3006
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data ?? "");
|
|
3007
|
+
this._body = buf;
|
|
3008
|
+
resolve({
|
|
3009
|
+
status: this.statusCode,
|
|
3010
|
+
headers: new Headers(this._headers),
|
|
3011
|
+
body: this.parseBody()
|
|
3012
|
+
});
|
|
3013
|
+
},
|
|
3014
|
+
parseBody() {
|
|
3015
|
+
try {
|
|
3016
|
+
return JSON.parse(this._body.toString());
|
|
3017
|
+
} catch {
|
|
3018
|
+
return this._body.toString();
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
};
|
|
3022
|
+
const listeners = server.listeners("request");
|
|
3023
|
+
const handler = listeners[listeners.length - 1];
|
|
3024
|
+
if (typeof handler !== "function") {
|
|
3025
|
+
reject(new Error("No request handler found"));
|
|
3026
|
+
return;
|
|
3027
|
+
}
|
|
3028
|
+
const mockReq = new PassThrough({
|
|
3029
|
+
read() {
|
|
3030
|
+
this.push(null);
|
|
3031
|
+
}
|
|
3032
|
+
});
|
|
3033
|
+
mockReq.method = method;
|
|
3034
|
+
mockReq.url = `${reqPath}${queryStr}`;
|
|
3035
|
+
mockReq.headers = {
|
|
3036
|
+
...reqHeaders,
|
|
3037
|
+
host: "localhost",
|
|
3038
|
+
"content-type": body !== void 0 ? "application/json" : void 0
|
|
3039
|
+
};
|
|
3040
|
+
mockReq.socket = { remoteAddress: "127.0.0.1" };
|
|
3041
|
+
if (body !== void 0) {
|
|
3042
|
+
mockReq.push(JSON.stringify(body));
|
|
3043
|
+
}
|
|
3044
|
+
handler(
|
|
3045
|
+
mockReq,
|
|
3046
|
+
mockRes
|
|
3047
|
+
);
|
|
3048
|
+
});
|
|
3049
|
+
},
|
|
3050
|
+
async close() {
|
|
3051
|
+
if (closed) return;
|
|
3052
|
+
closed = true;
|
|
3053
|
+
const s = server;
|
|
3054
|
+
if (typeof s.closeIdleConnections === "function") {
|
|
3055
|
+
s.closeIdleConnections();
|
|
3056
|
+
}
|
|
3057
|
+
if (typeof s.closeAllConnections === "function") {
|
|
3058
|
+
s.closeAllConnections();
|
|
3059
|
+
}
|
|
3060
|
+
if (config?.lifecycle?.onClose) {
|
|
3061
|
+
await config.lifecycle.onClose({ rootDir, routes: sorted, server });
|
|
3062
|
+
}
|
|
3063
|
+
return new Promise((resolve) => {
|
|
3064
|
+
server.close((err) => {
|
|
3065
|
+
if (err) console.error("Error closing server:", err);
|
|
3066
|
+
app.server = null;
|
|
3067
|
+
resolve();
|
|
3068
|
+
});
|
|
3069
|
+
});
|
|
3070
|
+
}
|
|
3071
|
+
};
|
|
3072
|
+
const ctx = {
|
|
3073
|
+
rootDir,
|
|
3074
|
+
appDir,
|
|
3075
|
+
outDir,
|
|
3076
|
+
patterns,
|
|
3077
|
+
server,
|
|
3078
|
+
routesRef,
|
|
3079
|
+
config,
|
|
3080
|
+
updateRoutes(newRoutes, newWsRoutes) {
|
|
3081
|
+
sorted = newRoutes;
|
|
3082
|
+
wsRoutes = newWsRoutes;
|
|
3083
|
+
app.routes = newRoutes;
|
|
3084
|
+
app.wsRoutes = newWsRoutes;
|
|
3085
|
+
routesRef.current = newRoutes;
|
|
3086
|
+
routesRef.wsCurrent = newWsRoutes;
|
|
3087
|
+
}
|
|
3088
|
+
};
|
|
3089
|
+
return { app, ctx };
|
|
3090
|
+
}
|
|
3091
|
+
|
|
3092
|
+
// src/router/scanRoutes.ts
|
|
3093
|
+
import fg from "fast-glob";
|
|
3094
|
+
import path8 from "path";
|
|
3095
|
+
import fs5 from "fs";
|
|
3096
|
+
|
|
3097
|
+
// src/router/constants.ts
|
|
3098
|
+
var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
3099
|
+
var HTTP_METHOD_SET = new Set(HTTP_METHODS);
|
|
3100
|
+
function isHttpMethod(value) {
|
|
3101
|
+
return HTTP_METHOD_SET.has(value);
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
// src/utils/normalizePath.ts
|
|
3105
|
+
function normalizePath(path9) {
|
|
3106
|
+
if (!path9) return "";
|
|
3107
|
+
let result = path9.replace(/\\/g, "/");
|
|
3108
|
+
result = result.replace(/\/+/g, "/");
|
|
3109
|
+
result = result.replace(/\/+$/, "");
|
|
3110
|
+
if (result && !result.startsWith("/")) {
|
|
3111
|
+
result = "/" + result;
|
|
3112
|
+
}
|
|
3113
|
+
return result;
|
|
3114
|
+
}
|
|
3115
|
+
|
|
3116
|
+
// src/router/parseRouteFile.ts
|
|
3117
|
+
function dynamicSegmentToParam(segment) {
|
|
3118
|
+
const match = segment.match(/^\[(.+)\]$/);
|
|
3119
|
+
if (match) {
|
|
3120
|
+
return ":" + match[1];
|
|
3121
|
+
}
|
|
3122
|
+
return segment;
|
|
3123
|
+
}
|
|
3124
|
+
function extractParamNames(urlPath) {
|
|
3125
|
+
const params = [];
|
|
3126
|
+
const segments = urlPath.split("/");
|
|
3127
|
+
for (const segment of segments) {
|
|
3128
|
+
if (segment.startsWith(":...")) {
|
|
3129
|
+
params.push(segment.slice(4));
|
|
3130
|
+
} else if (segment.startsWith(":")) {
|
|
3131
|
+
params.push(segment.slice(1));
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
return params;
|
|
3135
|
+
}
|
|
3136
|
+
function isCatchAllSegment(segment) {
|
|
3137
|
+
return /^\[\.\.\..+\]$/.test(segment);
|
|
3138
|
+
}
|
|
3139
|
+
function isRouteGroup(segment) {
|
|
3140
|
+
return /^\(.+\)$/.test(segment);
|
|
3141
|
+
}
|
|
3142
|
+
function filePathToUrlPath(filePath, appDir = ".") {
|
|
3143
|
+
const withoutPrefix = filePath.startsWith(appDir + "/") ? filePath.slice(appDir.length + 1) : filePath;
|
|
3144
|
+
const lastSlashIndex = withoutPrefix.lastIndexOf("/");
|
|
3145
|
+
const dirPath = lastSlashIndex === -1 ? "" : withoutPrefix.slice(0, lastSlashIndex);
|
|
3146
|
+
if (!dirPath) {
|
|
3147
|
+
return "";
|
|
3148
|
+
}
|
|
3149
|
+
const segments = dirPath.split("/").filter((s) => !isRouteGroup(s)).map(dynamicSegmentToParam);
|
|
3150
|
+
return normalizePath(segments.join("/"));
|
|
3151
|
+
}
|
|
3152
|
+
|
|
3153
|
+
// src/router/scanRoutes.ts
|
|
3154
|
+
function toProdAbsPath(sourceAbsPath, rootDir, appDir, prodDir) {
|
|
3155
|
+
let rel = path8.relative(rootDir, sourceAbsPath).replace(/\\/g, "/");
|
|
3156
|
+
if (appDir !== "." && rel.startsWith(`${appDir}/`)) {
|
|
3157
|
+
rel = rel.slice(appDir.length + 1);
|
|
3158
|
+
}
|
|
3159
|
+
const prodRel = `${prodDir}/${rel.replace(/\.ts$/, ".js")}`;
|
|
3160
|
+
return path8.resolve(rootDir, prodRel);
|
|
3161
|
+
}
|
|
3162
|
+
async function findMergedMiddlewares(routeFilePath, rootDir, appDir, prodDir) {
|
|
3163
|
+
const routeDir = path8.dirname(routeFilePath);
|
|
3164
|
+
const resolvedRoot = path8.resolve(rootDir);
|
|
3165
|
+
const mwPaths = [];
|
|
3166
|
+
let currentDir = path8.resolve(rootDir, routeDir);
|
|
3167
|
+
while (true) {
|
|
3168
|
+
if (prodDir) {
|
|
3169
|
+
const mwPath = path8.join(currentDir, "middlewares.js");
|
|
3170
|
+
const absMwPath = path8.resolve(rootDir, mwPath);
|
|
3171
|
+
const prodAbsMwPath = toProdAbsPath(absMwPath, rootDir, appDir, prodDir);
|
|
3172
|
+
if (fs5.existsSync(prodAbsMwPath)) {
|
|
3173
|
+
mwPaths.push(prodAbsMwPath);
|
|
3174
|
+
}
|
|
3175
|
+
} else {
|
|
3176
|
+
for (const ext of [".ts", ".js"]) {
|
|
3177
|
+
const mwPath = path8.join(currentDir, `middlewares${ext}`);
|
|
3178
|
+
const absMwPath = path8.resolve(rootDir, mwPath);
|
|
3179
|
+
if (fs5.existsSync(absMwPath)) {
|
|
3180
|
+
mwPaths.push(absMwPath);
|
|
3181
|
+
break;
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
if (currentDir === resolvedRoot) break;
|
|
3186
|
+
const parentDir = path8.dirname(currentDir);
|
|
3187
|
+
if (parentDir === currentDir) break;
|
|
3188
|
+
currentDir = parentDir;
|
|
3189
|
+
}
|
|
3190
|
+
if (mwPaths.length === 0) return void 0;
|
|
3191
|
+
mwPaths.reverse();
|
|
3192
|
+
const mergedMiddlewares = [];
|
|
3193
|
+
const mergedInjectors = {};
|
|
3194
|
+
for (const absMwPath of mwPaths) {
|
|
3195
|
+
let bundle = getCachedMiddlewares(absMwPath);
|
|
3196
|
+
if (bundle === void 0) {
|
|
3197
|
+
bundle = await loadMiddlewaresFile(absMwPath);
|
|
3198
|
+
setCachedMiddlewares(absMwPath, bundle);
|
|
3199
|
+
}
|
|
3200
|
+
mergedMiddlewares.push(...bundle.middlewares);
|
|
3201
|
+
for (const [name, injector] of Object.entries(bundle.injectors)) {
|
|
3202
|
+
mergedInjectors[name] = injector;
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
if (mergedMiddlewares.length === 0 && Object.keys(mergedInjectors).length === 0) {
|
|
3206
|
+
return void 0;
|
|
3207
|
+
}
|
|
3208
|
+
return { middlewares: mergedMiddlewares, injectors: mergedInjectors };
|
|
3209
|
+
}
|
|
3210
|
+
async function extractMethodsFromHandler(absPath) {
|
|
3211
|
+
try {
|
|
3212
|
+
const module = await importWithCacheBust(absPath);
|
|
3213
|
+
const methods = [];
|
|
3214
|
+
for (const key of Object.keys(module)) {
|
|
3215
|
+
if (isHttpMethod(key) && typeof module[key] === "function") {
|
|
3216
|
+
methods.push(key);
|
|
3217
|
+
}
|
|
3218
|
+
}
|
|
3219
|
+
return methods;
|
|
3220
|
+
} catch (err) {
|
|
3221
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
3222
|
+
console.warn(`[faapi] \u52A0\u8F7D\u8DEF\u7531\u6587\u4EF6\u5931\u8D25 ${absPath}: ${reason}`);
|
|
3223
|
+
return [];
|
|
3224
|
+
}
|
|
3225
|
+
}
|
|
3226
|
+
async function hasWsExport(absPath) {
|
|
3227
|
+
try {
|
|
3228
|
+
const module = await importWithCacheBust(absPath);
|
|
3229
|
+
return typeof module["WS"] === "function";
|
|
3230
|
+
} catch (err) {
|
|
3231
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
3232
|
+
console.warn(`[faapi] \u52A0\u8F7D\u8DEF\u7531\u6587\u4EF6\u5931\u8D25\uFF08WS \u68C0\u6D4B\uFF09${absPath}: ${reason}`);
|
|
3233
|
+
return false;
|
|
3234
|
+
}
|
|
3235
|
+
}
|
|
3236
|
+
async function scanRoutes(rootDir, patterns, appDir, prodDir) {
|
|
3237
|
+
const dir = appDir ?? ".";
|
|
3238
|
+
const files = await fg(patterns, {
|
|
3239
|
+
cwd: rootDir,
|
|
3240
|
+
onlyFiles: true,
|
|
3241
|
+
absolute: false
|
|
3242
|
+
});
|
|
3243
|
+
const routes = [];
|
|
3244
|
+
const wsRoutes = [];
|
|
3245
|
+
for (const file of files) {
|
|
3246
|
+
const normalizedFile = file.replace(/\\/g, "/");
|
|
3247
|
+
const fileName = normalizedFile.split("/").pop();
|
|
3248
|
+
if (fileName === "handler.ts" || fileName === "handler.js") {
|
|
3249
|
+
const absPath = path8.resolve(rootDir, normalizedFile);
|
|
3250
|
+
const importPath = prodDir ? toProdAbsPath(absPath, rootDir, dir, prodDir) : absPath;
|
|
3251
|
+
const urlPath = filePathToUrlPath(normalizedFile, dir);
|
|
3252
|
+
const paramNames = extractParamNames(urlPath);
|
|
3253
|
+
const isDynamic = paramNames.length > 0;
|
|
3254
|
+
const isCatchAll = normalizedFile.split("/").some(isCatchAllSegment);
|
|
3255
|
+
const middlewareBundle = await findMergedMiddlewares(normalizedFile, rootDir, dir, prodDir);
|
|
3256
|
+
const methods = await extractMethodsFromHandler(importPath);
|
|
3257
|
+
for (const method of methods) {
|
|
3258
|
+
routes.push({
|
|
3259
|
+
method,
|
|
3260
|
+
urlPath,
|
|
3261
|
+
filePath: normalizedFile,
|
|
3262
|
+
paramNames,
|
|
3263
|
+
isDynamic,
|
|
3264
|
+
isCatchAll: isCatchAll || void 0,
|
|
3265
|
+
middlewares: middlewareBundle?.middlewares,
|
|
3266
|
+
injectors: middlewareBundle?.injectors
|
|
3267
|
+
});
|
|
3268
|
+
}
|
|
3269
|
+
const hasWs = await hasWsExport(importPath);
|
|
3270
|
+
if (hasWs) {
|
|
3271
|
+
wsRoutes.push({
|
|
3272
|
+
urlPath,
|
|
3273
|
+
filePath: normalizedFile,
|
|
3274
|
+
paramNames,
|
|
3275
|
+
isDynamic,
|
|
3276
|
+
isCatchAll: isCatchAll || void 0,
|
|
3277
|
+
middlewares: middlewareBundle?.middlewares,
|
|
3278
|
+
injectors: middlewareBundle?.injectors
|
|
3279
|
+
});
|
|
3280
|
+
}
|
|
3281
|
+
continue;
|
|
3282
|
+
}
|
|
3283
|
+
}
|
|
3284
|
+
return { routes, wsRoutes };
|
|
3285
|
+
}
|
|
3286
|
+
|
|
3287
|
+
// src/cli/createDevApp.ts
|
|
3288
|
+
async function createDevApp(options) {
|
|
3289
|
+
const { app, ctx } = await createAppBase(options);
|
|
3290
|
+
const devApp = app;
|
|
3291
|
+
devApp.reloadRoutes = async () => {
|
|
3292
|
+
setLoadTimestamp(Date.now());
|
|
3293
|
+
invalidateMiddlewareCache();
|
|
3294
|
+
invalidateProgramCache();
|
|
3295
|
+
invalidateSchemaCache();
|
|
3296
|
+
const reScanned = await scanRoutes(ctx.rootDir, ctx.patterns, ctx.appDir, ctx.outDir);
|
|
3297
|
+
const sorted = sortRoutes(reScanned.routes);
|
|
3298
|
+
await generateSchemaFiles(sorted, ctx.rootDir, ctx.appDir, ctx.outDir);
|
|
3299
|
+
ctx.updateRoutes(sorted, reScanned.wsRoutes);
|
|
3300
|
+
};
|
|
3301
|
+
return devApp;
|
|
3302
|
+
}
|
|
3303
|
+
|
|
3304
|
+
// src/cli/createProdApp.ts
|
|
3305
|
+
async function createProdApp(options) {
|
|
3306
|
+
const { app } = await createAppBase(options);
|
|
3307
|
+
return app;
|
|
718
3308
|
}
|
|
719
3309
|
export {
|
|
3310
|
+
FaapiError,
|
|
3311
|
+
InternalError,
|
|
3312
|
+
MethodNotAllowedError,
|
|
3313
|
+
ModuleLoadError,
|
|
3314
|
+
RouteNotFoundError,
|
|
720
3315
|
SchemaExtractionError,
|
|
3316
|
+
ValidationError,
|
|
3317
|
+
collectRouteSchemaSources,
|
|
721
3318
|
cors,
|
|
3319
|
+
createProdApp as createApp,
|
|
3320
|
+
createDevApp,
|
|
3321
|
+
createProdApp,
|
|
722
3322
|
createProgram,
|
|
723
3323
|
extractTypeInfo,
|
|
724
3324
|
getInputTypeForMethod,
|
|
725
|
-
|
|
3325
|
+
helmet,
|
|
3326
|
+
invalidateProgramCache,
|
|
726
3327
|
loadConfig,
|
|
727
|
-
logger
|
|
3328
|
+
logger,
|
|
3329
|
+
resolveTypeNode
|
|
728
3330
|
};
|
|
729
3331
|
//# sourceMappingURL=index.js.map
|