@counterfact/generator 0.1.6 → 1.0.0
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/CHANGELOG.md +25 -0
- package/dist/operation-coder.d.ts +1 -1
- package/dist/operation-coder.js +8 -6
- package/dist/operation-type-coder.d.ts +2 -5
- package/dist/operation-type-coder.js +4 -26
- package/dist/operation-type-name-mapping.d.ts +3 -2
- package/dist/operation-type-name-mapping.js +22 -10
- package/dist/sanitize-identifier.d.ts +1 -0
- package/dist/sanitize-identifier.js +17 -0
- package/dist/schema-required-properties.d.ts +3 -0
- package/dist/schema-required-properties.js +47 -0
- package/dist/schema-type-coder.d.ts +1 -0
- package/dist/schema-type-coder.js +95 -6
- package/dist/templates/counterfact-types/middleware.ts +15 -2
- package/dist/templates/counterfact-types/response-builder-factory.ts +102 -6
- package/dist/templates/counterfact-types/response-builder.ts +1 -0
- package/dist/templates/counterfact-types/wide-operation-argument.ts +13 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# @counterfact/generator
|
|
2
2
|
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 442afd2: Generate operation and parameter types with stable HTTP method names such as
|
|
8
|
+
`HTTP_GET` and `HTTP_GET_Query`, independent of OpenAPI operationId. On CLI
|
|
9
|
+
startup, automatically migrate legacy operationId-based route imports and their
|
|
10
|
+
references while preserving route logic, explicit aliases, comments, and strings.
|
|
11
|
+
References outside route files must be updated manually.
|
|
12
|
+
|
|
13
|
+
### Minor Changes
|
|
14
|
+
|
|
15
|
+
- b0d11b6: Add `response.status(code)` as a typed alternative to `response[code]`. Allow headers and cookies before status selection, narrowing generated status choices by header names and values while preserving required-header and body validation.
|
|
16
|
+
|
|
17
|
+
Deprecate bracket-based `response[statusCode]` selection in favor of `response.status(statusCode)`. Update documentation and generated route stubs to use the function-based selector; existing bracket-based handlers remain supported.
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- 872e12f: Preserve nullable values, primitive constants, inferred object properties, referenced dictionary values, composition properties and required fields, explicit discriminator mappings, and tuple prefixes in generated TypeScript contracts. Keep unrestricted values typed as unknown and retain Counterfact's streaming and server-oriented binary types.
|
|
22
|
+
|
|
23
|
+
Regenerating contracts can expose existing handler type errors where required properties or literal constraints were previously lost.
|
|
24
|
+
|
|
25
|
+
- Updated dependencies [b0d11b6]
|
|
26
|
+
- @counterfact/types@0.2.0
|
|
27
|
+
|
|
3
28
|
## 0.1.6
|
|
4
29
|
|
|
5
30
|
### Patch Changes
|
|
@@ -6,7 +6,7 @@ import type { Script } from "./script.js";
|
|
|
6
6
|
/**
|
|
7
7
|
* Generates the default route handler stub for a single OpenAPI operation.
|
|
8
8
|
*
|
|
9
|
-
* The generated stub calls `$.response
|
|
9
|
+
* The generated stub calls `$.response.status(statusCode).random()` (or `.empty()`)
|
|
10
10
|
* for the first response defined in the spec. It is only written when no
|
|
11
11
|
* handler file exists yet — users are expected to replace it with real logic.
|
|
12
12
|
*
|
package/dist/operation-coder.js
CHANGED
|
@@ -8,7 +8,7 @@ import { OperationTypeCoder, VersionedArgTypeCoder, } from "./operation-type-cod
|
|
|
8
8
|
/**
|
|
9
9
|
* Generates the default route handler stub for a single OpenAPI operation.
|
|
10
10
|
*
|
|
11
|
-
* The generated stub calls `$.response
|
|
11
|
+
* The generated stub calls `$.response.status(statusCode).random()` (or `.empty()`)
|
|
12
12
|
* for the first response defined in the spec. It is only written when no
|
|
13
13
|
* handler file exists yet — users are expected to replace it with real logic.
|
|
14
14
|
*
|
|
@@ -55,11 +55,13 @@ export class OperationCoder extends Coder {
|
|
|
55
55
|
const body = ts.factory.createBlock([placeholder], true);
|
|
56
56
|
statements.push(ts.factory.createFunctionDeclaration([ts.factory.createModifier(ts.SyntaxKind.AsyncKeyword)], ts.factory.createToken(ts.SyntaxKind.AsteriskToken), "items", undefined, [], undefined, body));
|
|
57
57
|
}
|
|
58
|
-
const result = ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
58
|
+
const result = ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("$"), "response"), "status"), undefined, [
|
|
59
|
+
/^\d+$/u.test(status ?? "")
|
|
60
|
+
? ts.factory.createNumericLiteral(status)
|
|
61
|
+
: status === "default"
|
|
62
|
+
? ts.factory.createNumericLiteral(200)
|
|
63
|
+
: ts.factory.createStringLiteral(status ?? "200"),
|
|
64
|
+
]), method), undefined, streaming
|
|
63
65
|
? [
|
|
64
66
|
ts.factory.createCallExpression(ts.factory.createIdentifier("items"), undefined, []),
|
|
65
67
|
]
|
|
@@ -25,16 +25,13 @@ export declare class OperationTypeCoder extends TypeCoder {
|
|
|
25
25
|
requestMethod: string;
|
|
26
26
|
securitySchemes: SecurityScheme[];
|
|
27
27
|
constructor(requirement: Requirement, version?: string, requestMethod?: string, securitySchemes?: SecurityScheme[]);
|
|
28
|
-
/**
|
|
29
|
-
* Returns the base identifier for this operation, derived from its
|
|
30
|
-
* `operationId` (sanitised) or falling back to `HTTP_<METHOD>`.
|
|
31
|
-
*/
|
|
28
|
+
/** Returns the stable HTTP-method identifier, independent of operationId. */
|
|
32
29
|
getOperationBaseName(): string;
|
|
33
30
|
jsdoc(): string;
|
|
34
31
|
get exportId(): string;
|
|
35
32
|
names(): Generator<string>;
|
|
36
33
|
/**
|
|
37
|
-
* Generates and exports a named parameter type (e.g. `
|
|
34
|
+
* Generates and exports a named parameter type (e.g. `HTTP_GET_Query`) from
|
|
38
35
|
* `modulePath` and returns the exported type name.
|
|
39
36
|
*
|
|
40
37
|
* Returns `"never"` without creating an export when `inlineType` is
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { STREAMING_CONTENT_TYPES } from "@counterfact/types/streaming-content-types";
|
|
2
|
+
import { sanitizeIdentifier } from "./sanitize-identifier.js";
|
|
2
3
|
import { pathJoin } from "./forward-slash-path.js";
|
|
3
4
|
import ts from "typescript";
|
|
4
5
|
import { functionType, literalType, neverType, numberType, parameter, stringType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
|
|
@@ -6,28 +7,11 @@ import { buildJsDoc } from "./jsdoc.js";
|
|
|
6
7
|
import { ParameterExportTypeCoder } from "./parameter-export-type-coder.js";
|
|
7
8
|
import { ParametersTypeCoder } from "./parameters-type-coder.js";
|
|
8
9
|
import { READ_ONLY_COMMENTS } from "./read-only-comments.js";
|
|
9
|
-
import { RESERVED_WORDS } from "./reserved-words.js";
|
|
10
10
|
import { ResponsesTypeCoder } from "./responses-type-coder.js";
|
|
11
11
|
import { SchemaTypeCoder } from "./schema-type-coder.js";
|
|
12
12
|
import { TypeCoder } from "./type-coder.js";
|
|
13
13
|
import { normalizeOpenApiPath } from "./openapi-path.js";
|
|
14
14
|
import { Requirement } from "./requirement.js";
|
|
15
|
-
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words
|
|
16
|
-
function sanitizeIdentifier(value) {
|
|
17
|
-
// Treat any run of non-identifier characters as a camelCase separator
|
|
18
|
-
let result = value.replaceAll(/[^\w$]+(?<next>.)/gu, (_, char) => char.toUpperCase());
|
|
19
|
-
// Strip any trailing non-identifier characters (no following char to capitalize)
|
|
20
|
-
result = result.replaceAll(/[^\w$]/gu, "");
|
|
21
|
-
// If the identifier starts with a digit, prefix with an underscore
|
|
22
|
-
if (/^\d/u.test(result)) {
|
|
23
|
-
result = `_${result}`;
|
|
24
|
-
}
|
|
25
|
-
// If the identifier is a reserved word, append an underscore
|
|
26
|
-
if (RESERVED_WORDS.has(result)) {
|
|
27
|
-
result = `${result}_`;
|
|
28
|
-
}
|
|
29
|
-
return result || "_";
|
|
30
|
-
}
|
|
31
15
|
/**
|
|
32
16
|
* Generates the TypeScript type for a single OpenAPI operation.
|
|
33
17
|
*
|
|
@@ -52,15 +36,9 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
52
36
|
this.requestMethod = requestMethod;
|
|
53
37
|
this.securitySchemes = securitySchemes;
|
|
54
38
|
}
|
|
55
|
-
/**
|
|
56
|
-
* Returns the base identifier for this operation, derived from its
|
|
57
|
-
* `operationId` (sanitised) or falling back to `HTTP_<METHOD>`.
|
|
58
|
-
*/
|
|
39
|
+
/** Returns the stable HTTP-method identifier, independent of operationId. */
|
|
59
40
|
getOperationBaseName() {
|
|
60
|
-
|
|
61
|
-
return operationId
|
|
62
|
-
? sanitizeIdentifier(operationId)
|
|
63
|
-
: `HTTP_${this.requestMethod.toUpperCase()}`;
|
|
41
|
+
return `HTTP_${this.requestMethod.toUpperCase()}`;
|
|
64
42
|
}
|
|
65
43
|
jsdoc() {
|
|
66
44
|
return buildJsDoc(this.requirement.data);
|
|
@@ -74,7 +52,7 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
74
52
|
return super.names(this.getOperationBaseName());
|
|
75
53
|
}
|
|
76
54
|
/**
|
|
77
|
-
* Generates and exports a named parameter type (e.g. `
|
|
55
|
+
* Generates and exports a named parameter type (e.g. `HTTP_GET_Query`) from
|
|
78
56
|
* `modulePath` and returns the exported type name.
|
|
79
57
|
*
|
|
80
58
|
* Returns `"never"` without creating an export when `inlineType` is
|
|
@@ -2,6 +2,7 @@ export type OperationTypeNameMapping = Map<string, Map<string, string>>;
|
|
|
2
2
|
/**
|
|
3
3
|
* Resolves the generated operation type name for each route and HTTP method.
|
|
4
4
|
* This is the migration-facing API; concrete coder and specification classes
|
|
5
|
-
* remain internal implementation details.
|
|
5
|
+
* remain internal implementation details. Set legacyNames only when migrating
|
|
6
|
+
* operationId-based imports from older generated projects.
|
|
6
7
|
*/
|
|
7
|
-
export declare function buildOperationTypeNameMapping(source: string, overlays?: readonly string[]): Promise<OperationTypeNameMapping>;
|
|
8
|
+
export declare function buildOperationTypeNameMapping(source: string, overlays?: readonly string[], legacyNames?: boolean): Promise<OperationTypeNameMapping>;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { normalizeOpenApiPath } from "./openapi-path.js";
|
|
2
|
+
import { sanitizeIdentifier } from "./sanitize-identifier.js";
|
|
1
3
|
import createDebug from "debug";
|
|
2
4
|
import { OperationTypeCoder, } from "./operation-type-coder.js";
|
|
3
5
|
import { Specification } from "./specification.js";
|
|
@@ -10,9 +12,10 @@ const HTTP_METHODS = new Set([
|
|
|
10
12
|
"PATCH",
|
|
11
13
|
"HEAD",
|
|
12
14
|
"OPTIONS",
|
|
13
|
-
"
|
|
15
|
+
"TRACE",
|
|
14
16
|
]);
|
|
15
17
|
function openApiPathToFilePath(openApiPath) {
|
|
18
|
+
openApiPath = normalizeOpenApiPath(openApiPath);
|
|
16
19
|
if (openApiPath === "/") {
|
|
17
20
|
return "index";
|
|
18
21
|
}
|
|
@@ -21,9 +24,10 @@ function openApiPathToFilePath(openApiPath) {
|
|
|
21
24
|
/**
|
|
22
25
|
* Resolves the generated operation type name for each route and HTTP method.
|
|
23
26
|
* This is the migration-facing API; concrete coder and specification classes
|
|
24
|
-
* remain internal implementation details.
|
|
27
|
+
* remain internal implementation details. Set legacyNames only when migrating
|
|
28
|
+
* operationId-based imports from older generated projects.
|
|
25
29
|
*/
|
|
26
|
-
export async function buildOperationTypeNameMapping(source, overlays = []) {
|
|
30
|
+
export async function buildOperationTypeNameMapping(source, overlays = [], legacyNames = false) {
|
|
27
31
|
debug("building operation type name mapping from %s", source);
|
|
28
32
|
const specification = await Specification.fromFile(source, overlays);
|
|
29
33
|
const mapping = new Map();
|
|
@@ -35,16 +39,24 @@ export async function buildOperationTypeNameMapping(source, overlays = []) {
|
|
|
35
39
|
const securitySchemes = Object.values(securityRequirement?.data ?? {});
|
|
36
40
|
paths.forEach((pathDefinition, openApiPath) => {
|
|
37
41
|
const methodMap = new Map();
|
|
38
|
-
pathDefinition.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
+
const operations = pathDefinition.flatMap((operation, method) => {
|
|
43
|
+
if (method === "additionalOperations") {
|
|
44
|
+
return operation.map((additionalOperation, additionalMethod) => ({
|
|
45
|
+
operation: additionalOperation,
|
|
46
|
+
method: additionalMethod.toUpperCase(),
|
|
47
|
+
}));
|
|
42
48
|
}
|
|
43
|
-
|
|
49
|
+
return HTTP_METHODS.has(method.toUpperCase())
|
|
50
|
+
? [{ operation, method: method.toUpperCase() }]
|
|
51
|
+
: [];
|
|
52
|
+
});
|
|
53
|
+
for (const { operation, method } of operations) {
|
|
54
|
+
const typeName = new OperationTypeCoder(operation, "", method.toLowerCase(), securitySchemes)
|
|
44
55
|
.names()
|
|
45
56
|
.next().value;
|
|
46
|
-
|
|
47
|
-
|
|
57
|
+
const operationId = operation.get("operationId")?.data;
|
|
58
|
+
methodMap.set(method, legacyNames && operationId ? sanitizeIdentifier(operationId) : typeName);
|
|
59
|
+
}
|
|
48
60
|
if (methodMap.size > 0) {
|
|
49
61
|
mapping.set(openApiPathToFilePath(openApiPath), methodMap);
|
|
50
62
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function sanitizeIdentifier(value: string): string;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { RESERVED_WORDS } from "./reserved-words.js";
|
|
2
|
+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words
|
|
3
|
+
export function sanitizeIdentifier(value) {
|
|
4
|
+
// Treat any run of non-identifier characters as a camelCase separator
|
|
5
|
+
let result = value.replaceAll(/[^\w$]+(?<next>.)/gu, (_, char) => char.toUpperCase());
|
|
6
|
+
// Strip any trailing non-identifier characters (no following char to capitalize)
|
|
7
|
+
result = result.replaceAll(/[^\w$]/gu, "");
|
|
8
|
+
// If the identifier starts with a digit, prefix with an underscore
|
|
9
|
+
if (/^\d/u.test(result)) {
|
|
10
|
+
result = `_${result}`;
|
|
11
|
+
}
|
|
12
|
+
// If the identifier is a reserved word, append an underscore
|
|
13
|
+
if (RESERVED_WORDS.has(result)) {
|
|
14
|
+
result = `${result}_`;
|
|
15
|
+
}
|
|
16
|
+
return result || "_";
|
|
17
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { typeLiteral, typeProperty, typeReference, unionType, unknownType, neverType, } from "./ast.js";
|
|
3
|
+
/** Apply a containing schema's required list without changing shared referenced models. */
|
|
4
|
+
export function requireProperties(type, names) {
|
|
5
|
+
if (ts.isParenthesizedTypeNode(type)) {
|
|
6
|
+
return ts.factory.createParenthesizedType(requireProperties(type.type, names));
|
|
7
|
+
}
|
|
8
|
+
if (ts.isUnionTypeNode(type)) {
|
|
9
|
+
return unionType(type.types.map((branch) => requireProperties(branch, names)));
|
|
10
|
+
}
|
|
11
|
+
if (ts.isIntersectionTypeNode(type)) {
|
|
12
|
+
return ts.factory.createIntersectionTypeNode(type.types.map((part) => requireProperties(part, names)));
|
|
13
|
+
}
|
|
14
|
+
if (ts.isTypeLiteralNode(type)) {
|
|
15
|
+
const present = new Set();
|
|
16
|
+
const members = type.members.map((member) => {
|
|
17
|
+
if (!ts.isPropertySignature(member) ||
|
|
18
|
+
!member.name ||
|
|
19
|
+
ts.isComputedPropertyName(member.name))
|
|
20
|
+
return member;
|
|
21
|
+
const name = member.name.text;
|
|
22
|
+
present.add(name);
|
|
23
|
+
return names.includes(name)
|
|
24
|
+
? ts.factory.updatePropertySignature(member, member.modifiers, member.name, undefined, member.type)
|
|
25
|
+
: member;
|
|
26
|
+
});
|
|
27
|
+
for (const name of names) {
|
|
28
|
+
if (!present.has(name))
|
|
29
|
+
members.push(typeProperty(name, unknownType()));
|
|
30
|
+
}
|
|
31
|
+
return typeLiteral(members);
|
|
32
|
+
}
|
|
33
|
+
if (type.kind !== ts.SyntaxKind.TypeReference)
|
|
34
|
+
return type;
|
|
35
|
+
// Distribute over referenced unions. A mapped type preserves each property's
|
|
36
|
+
// original type while removing optionality only for the requested keys.
|
|
37
|
+
const schema = typeReference("RequiredSchema");
|
|
38
|
+
const key = typeReference("RequiredKey");
|
|
39
|
+
const keys = unionType(names.map((name) => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(name))));
|
|
40
|
+
const selected = ts.factory.createMappedTypeNode(undefined, ts.factory.createTypeParameterDeclaration(undefined, "RequiredKey", ts.factory.createTypeOperatorNode(ts.SyntaxKind.KeyOfKeyword, schema)), ts.factory.createConditionalTypeNode(key, keys, key, neverType()), ts.factory.createToken(ts.SyntaxKind.MinusToken), ts.factory.createIndexedAccessTypeNode(schema, key), undefined);
|
|
41
|
+
const enforced = ts.factory.createIntersectionTypeNode([
|
|
42
|
+
schema,
|
|
43
|
+
selected,
|
|
44
|
+
typeLiteral(names.map((name) => typeProperty(name, unknownType()))),
|
|
45
|
+
]);
|
|
46
|
+
return ts.factory.createConditionalTypeNode(type, ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(undefined, "RequiredSchema")), ts.factory.createConditionalTypeNode(schema, ts.factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword), enforced, schema), neverType());
|
|
47
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
|
|
2
|
+
import { typeLiteral, typeProperty, typeReference, unionType, unknownType, neverType, } from "./ast.js";
|
|
3
|
+
import { requireProperties } from "./schema-required-properties.js";
|
|
3
4
|
import { TypeCoder } from "./type-coder.js";
|
|
4
5
|
import { pathJoin } from "./forward-slash-path.js";
|
|
5
6
|
import { buildJsDoc } from "./jsdoc.js";
|
|
@@ -13,8 +14,10 @@ export class SchemaTypeCoder extends TypeCoder {
|
|
|
13
14
|
}
|
|
14
15
|
additionalPropertiesType(script) {
|
|
15
16
|
const { additionalProperties, properties } = this.requirement.data;
|
|
16
|
-
if (
|
|
17
|
-
Object.
|
|
17
|
+
if (typeof additionalProperties !== "object" ||
|
|
18
|
+
(Object.keys(properties ?? {}).length > 0 &&
|
|
19
|
+
(!additionalProperties.type ||
|
|
20
|
+
Object.values(properties ?? {}).some((property) => property.type !== additionalProperties.type)))) {
|
|
18
21
|
return unknownType();
|
|
19
22
|
}
|
|
20
23
|
return new SchemaTypeCoder(this.requirement.get("additionalProperties"), this.version).write(script);
|
|
@@ -35,8 +38,38 @@ export class SchemaTypeCoder extends TypeCoder {
|
|
|
35
38
|
return typeLiteral(members);
|
|
36
39
|
}
|
|
37
40
|
arraySchema(script) {
|
|
41
|
+
const data = this.requirement.data;
|
|
42
|
+
const tupleKey = Array.isArray(data.prefixItems)
|
|
43
|
+
? "prefixItems"
|
|
44
|
+
: Array.isArray(data.items)
|
|
45
|
+
? "items"
|
|
46
|
+
: undefined;
|
|
47
|
+
if (tupleKey) {
|
|
48
|
+
const items = this.requirement.get(tupleKey);
|
|
49
|
+
const members = items
|
|
50
|
+
.map((item, index) => {
|
|
51
|
+
const type = new SchemaTypeCoder(item, this.version).write(script);
|
|
52
|
+
return Number(index) < (data.minItems ?? 0)
|
|
53
|
+
? type
|
|
54
|
+
: ts.factory.createOptionalTypeNode(type);
|
|
55
|
+
})
|
|
56
|
+
.slice(0, data.maxItems);
|
|
57
|
+
const restKey = tupleKey === "prefixItems" ? "items" : "additionalItems";
|
|
58
|
+
const rest = this.requirement.get(restKey);
|
|
59
|
+
if (rest?.data !== false &&
|
|
60
|
+
(data.maxItems === undefined || data.maxItems > members.length)) {
|
|
61
|
+
const restType = rest
|
|
62
|
+
? new SchemaTypeCoder(rest, this.version).write(script)
|
|
63
|
+
: unknownType();
|
|
64
|
+
members.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(restType)));
|
|
65
|
+
}
|
|
66
|
+
return ts.factory.createTupleTypeNode(members);
|
|
67
|
+
}
|
|
68
|
+
const items = this.requirement.get("items");
|
|
38
69
|
return typeReference("Array", [
|
|
39
|
-
|
|
70
|
+
items
|
|
71
|
+
? new SchemaTypeCoder(items, this.version).write(script)
|
|
72
|
+
: unknownType(),
|
|
40
73
|
]);
|
|
41
74
|
}
|
|
42
75
|
writePrimitive(value) {
|
|
@@ -76,13 +109,35 @@ export class SchemaTypeCoder extends TypeCoder {
|
|
|
76
109
|
case "null":
|
|
77
110
|
return ts.factory.createLiteralTypeNode(ts.factory.createNull());
|
|
78
111
|
default:
|
|
112
|
+
if (type === undefined &&
|
|
113
|
+
(this.requirement.has("properties") ||
|
|
114
|
+
this.requirement.has("additionalProperties"))) {
|
|
115
|
+
return this.objectSchema(script);
|
|
116
|
+
}
|
|
79
117
|
return unknownType();
|
|
80
118
|
}
|
|
81
119
|
}
|
|
82
120
|
writeGroup(script, { allOf, anyOf, oneOf, }) {
|
|
83
121
|
const key = allOf ? "allOf" : anyOf ? "anyOf" : "oneOf";
|
|
84
122
|
const items = (allOf ?? anyOf ?? oneOf);
|
|
85
|
-
const
|
|
123
|
+
const { discriminator } = this.requirement.data;
|
|
124
|
+
const types = items.map((_item, index) => {
|
|
125
|
+
const branch = this.requirement.get(key).get(index);
|
|
126
|
+
const type = new SchemaTypeCoder(branch, this.version).write(script);
|
|
127
|
+
const values = !allOf && branch.refUrl && discriminator?.propertyName
|
|
128
|
+
? Object.entries(discriminator.mapping ?? {})
|
|
129
|
+
.filter(([, ref]) => ref === branch.refUrl)
|
|
130
|
+
.map(([value]) => this.writePrimitive(value))
|
|
131
|
+
: [];
|
|
132
|
+
return values.length > 0
|
|
133
|
+
? unionType(values.map((value) => ts.factory.createIntersectionTypeNode([
|
|
134
|
+
type,
|
|
135
|
+
typeLiteral([
|
|
136
|
+
typeProperty(discriminator.propertyName, value),
|
|
137
|
+
]),
|
|
138
|
+
])))
|
|
139
|
+
: type;
|
|
140
|
+
});
|
|
86
141
|
// OpenAPI 3.2 discriminator fallback participates in the union.
|
|
87
142
|
if (!allOf) {
|
|
88
143
|
const { discriminator } = this.requirement.data;
|
|
@@ -101,6 +156,21 @@ export class SchemaTypeCoder extends TypeCoder {
|
|
|
101
156
|
return pathJoin("types", this.version, this.requirement.refUrl.replace(/^#\//u, "") + ".ts");
|
|
102
157
|
}
|
|
103
158
|
writeCode(script) {
|
|
159
|
+
if (this.requirement.data === false)
|
|
160
|
+
return neverType();
|
|
161
|
+
if (this.requirement.data === true || this.requirement.data === null)
|
|
162
|
+
return unknownType();
|
|
163
|
+
const type = this.writeSchema(script);
|
|
164
|
+
const data = this.requirement.data;
|
|
165
|
+
// nullable expands the declared type; enum/const remain independent constraints.
|
|
166
|
+
return data.nullable === true &&
|
|
167
|
+
data.type !== undefined &&
|
|
168
|
+
!this.requirement.has("enum") &&
|
|
169
|
+
!this.requirement.has("const")
|
|
170
|
+
? unionType([type, this.writePrimitive(null)])
|
|
171
|
+
: type;
|
|
172
|
+
}
|
|
173
|
+
writeSchema(script) {
|
|
104
174
|
const { allOf, anyOf, oneOf, type, format, itemSchema } = this.requirement
|
|
105
175
|
.data;
|
|
106
176
|
if (itemSchema) {
|
|
@@ -109,7 +179,26 @@ export class SchemaTypeCoder extends TypeCoder {
|
|
|
109
179
|
]);
|
|
110
180
|
}
|
|
111
181
|
if (allOf ?? anyOf ?? oneOf) {
|
|
112
|
-
|
|
182
|
+
const parts = [];
|
|
183
|
+
for (const group of [{ allOf }, { anyOf }, { oneOf }]) {
|
|
184
|
+
if (Object.values(group)[0] !== undefined)
|
|
185
|
+
parts.push(this.writeGroup(script, group));
|
|
186
|
+
}
|
|
187
|
+
if (this.requirement.has("properties") ||
|
|
188
|
+
this.requirement.has("additionalProperties")) {
|
|
189
|
+
parts.push(this.objectSchema(script));
|
|
190
|
+
}
|
|
191
|
+
const result = parts.length === 1
|
|
192
|
+
? parts[0]
|
|
193
|
+
: ts.factory.createIntersectionTypeNode(parts);
|
|
194
|
+
const required = this.requirement.data
|
|
195
|
+
.required;
|
|
196
|
+
return Array.isArray(required) && required.length > 0
|
|
197
|
+
? requireProperties(result, required)
|
|
198
|
+
: result;
|
|
199
|
+
}
|
|
200
|
+
if (this.requirement.has("const")) {
|
|
201
|
+
return this.writePrimitive(this.requirement.get("const").data);
|
|
113
202
|
}
|
|
114
203
|
if (this.requirement.has("enum")) {
|
|
115
204
|
return this.writeEnum(this.requirement.get("enum"));
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CookieOptions } from "./cookie-options.js";
|
|
1
2
|
import type { COUNTERFACT_RESPONSE } from "./counterfact-response.js";
|
|
2
3
|
import type { HttpStatusCode } from "./http-status-code.js";
|
|
3
4
|
import type { MaybePromise } from "./maybe-promise.js";
|
|
@@ -26,8 +27,20 @@ export interface MiddlewareTools {
|
|
|
26
27
|
|
|
27
28
|
/** A response-builder factory with every standard status code available. */
|
|
28
29
|
export type MiddlewareResponseBuilderFactory = {
|
|
30
|
+
/** @deprecated Use response.status(statusCode) instead. */
|
|
29
31
|
[StatusCode in HttpStatusCode]: ResponseBuilder;
|
|
30
|
-
} & {
|
|
32
|
+
} & {
|
|
33
|
+
/** @deprecated Use response.status(statusCode) instead. */
|
|
34
|
+
[key: number | `${number} ${string}`]: ResponseBuilder;
|
|
35
|
+
} & {
|
|
36
|
+
status: (statusCode: number | `${number} ${string}`) => ResponseBuilder;
|
|
37
|
+
header: (name: string, value: string) => MiddlewareResponseBuilderFactory;
|
|
38
|
+
cookie: (
|
|
39
|
+
name: string,
|
|
40
|
+
value: string,
|
|
41
|
+
options?: CookieOptions,
|
|
42
|
+
) => MiddlewareResponseBuilderFactory;
|
|
43
|
+
};
|
|
31
44
|
|
|
32
45
|
/**
|
|
33
46
|
* The request argument passed to a custom middleware function.
|
|
@@ -74,7 +87,7 @@ export type RespondTo<Context = unknown> = (
|
|
|
74
87
|
*
|
|
75
88
|
* export const middleware: Middleware<Context> = async ($, respondTo) => {
|
|
76
89
|
* if (!$.context.isAuthorized($.auth?.apiKey)) {
|
|
77
|
-
* return $.response
|
|
90
|
+
* return $.response.status(401).json({ error: "Unauthorized" });
|
|
78
91
|
* }
|
|
79
92
|
*
|
|
80
93
|
* return respondTo($);
|
|
@@ -1,16 +1,112 @@
|
|
|
1
|
+
import type { CookieOptions } from "./cookie-options.js";
|
|
1
2
|
import type { GenericResponseBuilder } from "./generic-response-builder.js";
|
|
2
|
-
import type { OpenApiResponses } from "./open-api-response.js";
|
|
3
|
+
import type { OpenApiResponse, OpenApiResponses } from "./open-api-response.js";
|
|
4
|
+
|
|
5
|
+
type StatusCodes<Responses> =
|
|
6
|
+
| keyof Responses
|
|
7
|
+
| {
|
|
8
|
+
[Key in keyof Responses]: Key extends `${infer Code extends number}`
|
|
9
|
+
? Code
|
|
10
|
+
: never;
|
|
11
|
+
}[keyof Responses];
|
|
12
|
+
|
|
13
|
+
type ResponseAt<Responses, Code> = Code extends keyof Responses
|
|
14
|
+
? Responses[Code]
|
|
15
|
+
: Code extends number
|
|
16
|
+
? `${Code}` extends keyof Responses
|
|
17
|
+
? Responses[`${Code}`]
|
|
18
|
+
: Responses extends { default: infer Default }
|
|
19
|
+
? Default
|
|
20
|
+
: never
|
|
21
|
+
: Responses extends { default: infer Default }
|
|
22
|
+
? Default
|
|
23
|
+
: never;
|
|
24
|
+
|
|
25
|
+
type HeaderNames<Responses extends OpenApiResponses> = {
|
|
26
|
+
[Code in keyof Responses]: [Responses[Code]["headers"]] extends [never]
|
|
27
|
+
? never
|
|
28
|
+
: keyof Responses[Code]["headers"];
|
|
29
|
+
}[keyof Responses] &
|
|
30
|
+
string;
|
|
31
|
+
|
|
32
|
+
type HeaderValues<Responses extends OpenApiResponses, Name extends string> = {
|
|
33
|
+
[Code in keyof Responses]: Name extends keyof Responses[Code]["headers"]
|
|
34
|
+
? Responses[Code]["headers"][Name]["schema"]
|
|
35
|
+
: never;
|
|
36
|
+
}[keyof Responses];
|
|
37
|
+
|
|
38
|
+
// Filter each response independently, preserving the relationship between a
|
|
39
|
+
// status code and its remaining body/header requirements.
|
|
40
|
+
type WithHeader<
|
|
41
|
+
Responses extends OpenApiResponses,
|
|
42
|
+
Name extends string,
|
|
43
|
+
Value,
|
|
44
|
+
> = {
|
|
45
|
+
[
|
|
46
|
+
Code in keyof Responses as [Responses[Code]["headers"]] extends [never]
|
|
47
|
+
? never
|
|
48
|
+
: [Name] extends [keyof Responses[Code]["headers"]]
|
|
49
|
+
? [Value] extends [Responses[Code]["headers"][Name]["schema"]]
|
|
50
|
+
? Code
|
|
51
|
+
: never
|
|
52
|
+
: never
|
|
53
|
+
]: {
|
|
54
|
+
content: Responses[Code]["content"];
|
|
55
|
+
headers: Omit<Responses[Code]["headers"], Name>;
|
|
56
|
+
requiredHeaders: Exclude<Responses[Code]["requiredHeaders"], Name>;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
3
59
|
|
|
4
60
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* argument object, allowing handlers to call e.g. `response[200].json(body)`.
|
|
61
|
+
* Select a response with `response.status(200)`.
|
|
62
|
+
* Headers supplied before selection narrow the available status codes and
|
|
63
|
+
* satisfy the same requirements as headers supplied after selection.
|
|
9
64
|
*/
|
|
10
65
|
export type ResponseBuilderFactory<
|
|
11
66
|
Responses extends OpenApiResponses = OpenApiResponses,
|
|
67
|
+
ExcludedStatuses extends PropertyKey = never,
|
|
12
68
|
> = {
|
|
69
|
+
/** @deprecated Use response.status(statusCode) instead. */
|
|
13
70
|
[StatusCode in keyof Responses]: GenericResponseBuilder<
|
|
14
71
|
Responses[StatusCode]
|
|
15
72
|
>;
|
|
16
|
-
} & {
|
|
73
|
+
} & {
|
|
74
|
+
/** @deprecated Use response.status(statusCode) instead. */
|
|
75
|
+
[key: string]: GenericResponseBuilder<Responses["default"]>;
|
|
76
|
+
} & {
|
|
77
|
+
status: <
|
|
78
|
+
Code extends
|
|
79
|
+
| StatusCodes<Responses>
|
|
80
|
+
| ("default" extends keyof Responses
|
|
81
|
+
? number | `${number} ${string}`
|
|
82
|
+
: never),
|
|
83
|
+
>(
|
|
84
|
+
statusCode: Code extends ExcludedStatuses
|
|
85
|
+
? never
|
|
86
|
+
: Code extends number
|
|
87
|
+
? `${Code}` extends ExcludedStatuses
|
|
88
|
+
? never
|
|
89
|
+
: Code
|
|
90
|
+
: Code,
|
|
91
|
+
) => Code extends unknown
|
|
92
|
+
? ResponseAt<Responses, Code> extends infer Response extends OpenApiResponse
|
|
93
|
+
? GenericResponseBuilder<Response>
|
|
94
|
+
: never
|
|
95
|
+
: never;
|
|
96
|
+
header: <
|
|
97
|
+
Name extends HeaderNames<Responses>,
|
|
98
|
+
const Value extends HeaderValues<Responses, Name>,
|
|
99
|
+
>(
|
|
100
|
+
name: Name,
|
|
101
|
+
value: Value,
|
|
102
|
+
) => ResponseBuilderFactory<
|
|
103
|
+
WithHeader<Responses, Name, Value>,
|
|
104
|
+
| ExcludedStatuses
|
|
105
|
+
| Exclude<keyof Responses, keyof WithHeader<Responses, Name, Value>>
|
|
106
|
+
>;
|
|
107
|
+
cookie: (
|
|
108
|
+
name: string,
|
|
109
|
+
value: string,
|
|
110
|
+
options?: CookieOptions,
|
|
111
|
+
) => ResponseBuilderFactory<Responses, ExcludedStatuses>;
|
|
112
|
+
};
|
|
@@ -8,6 +8,7 @@ import type { MaybePromise } from "./maybe-promise.js";
|
|
|
8
8
|
* strongly-typed `GenericResponseBuilder`.
|
|
9
9
|
*/
|
|
10
10
|
export interface ResponseBuilder {
|
|
11
|
+
/** @deprecated Select a status with response.status(statusCode) instead. */
|
|
11
12
|
[status: number | `${number} ${string}`]: ResponseBuilder;
|
|
12
13
|
binary: (body: Uint8Array | string) => ResponseBuilder;
|
|
13
14
|
content?: { body: unknown; type: string }[];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CookieOptions } from "./cookie-options.js";
|
|
1
2
|
import type { HttpStatusCode } from "./http-status-code.js";
|
|
2
3
|
import type { WideResponseBuilder } from "./wide-response-builder.js";
|
|
3
4
|
|
|
@@ -14,7 +15,18 @@ export interface WideOperationArgument {
|
|
|
14
15
|
path: { [key: string]: string };
|
|
15
16
|
proxy: (url: string) => { proxyUrl: string };
|
|
16
17
|
query: { [key: string]: string };
|
|
17
|
-
response: {
|
|
18
|
+
response: {
|
|
19
|
+
/** @deprecated Use response.status(statusCode) instead. */
|
|
20
|
+
[StatusCode in HttpStatusCode]: WideResponseBuilder;
|
|
21
|
+
} & {
|
|
22
|
+
/** @deprecated Use response.status(statusCode) instead. */
|
|
18
23
|
[key: number]: WideResponseBuilder;
|
|
24
|
+
status: (statusCode: number | `${number} ${string}`) => WideResponseBuilder;
|
|
25
|
+
header: (name: string, value: string) => WideOperationArgument["response"];
|
|
26
|
+
cookie: (
|
|
27
|
+
name: string,
|
|
28
|
+
value: string,
|
|
29
|
+
options?: CookieOptions,
|
|
30
|
+
) => WideOperationArgument["response"];
|
|
19
31
|
};
|
|
20
32
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@counterfact/generator",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Generate Counterfact route scaffolds and OpenAPI-derived TypeScript contracts.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
55
|
"@counterfact/openapi": "0.1.6",
|
|
56
|
-
"@counterfact/types": "0.
|
|
56
|
+
"@counterfact/types": "0.2.0",
|
|
57
57
|
"chokidar": "5.0.0",
|
|
58
58
|
"debug": "4.4.3",
|
|
59
59
|
"prettier": "3.9.10",
|