@counterfact/generator 1.3.0 → 2.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 +39 -0
- package/dist/adopt-spellings.d.ts +15 -0
- package/dist/adopt-spellings.js +48 -0
- package/dist/case-safe-paths.d.ts +21 -0
- package/dist/case-safe-paths.js +57 -0
- package/dist/client-multipart-schema-type-coder.d.ts +16 -0
- package/dist/client-multipart-schema-type-coder.js +78 -0
- package/dist/client-response-schemas.d.ts +29 -0
- package/dist/client-response-schemas.js +120 -0
- package/dist/client-security.d.ts +10 -0
- package/dist/client-security.js +49 -0
- package/dist/code-generator.d.ts +9 -3
- package/dist/code-generator.js +28 -55
- package/dist/generate-client.d.ts +3 -0
- package/dist/generate-client.js +418 -0
- package/dist/generate-versioned-client.d.ts +12 -0
- package/dist/generate-versioned-client.js +103 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/migrate-route-layout.d.ts +8 -0
- package/dist/migrate-route-layout.js +448 -0
- package/dist/named-client-operations.d.ts +19 -0
- package/dist/named-client-operations.js +96 -0
- package/dist/operation-coder.js +1 -1
- package/dist/operation-type-coder.d.ts +6 -0
- package/dist/operation-type-coder.js +17 -5
- package/dist/path-operations.d.ts +2 -0
- package/dist/path-operations.js +31 -0
- package/dist/prune.d.ts +1 -1
- package/dist/prune.js +10 -3
- package/dist/repository.d.ts +15 -1
- package/dist/repository.js +184 -33
- package/dist/route-file-layout.d.ts +32 -0
- package/dist/route-file-layout.js +152 -0
- package/dist/scenario-file-generator.js +25 -5
- package/dist/script.d.ts +2 -0
- package/dist/script.js +16 -4
- package/dist/standalone-client-validators.d.ts +2 -0
- package/dist/standalone-client-validators.js +85 -0
- package/dist/swagger2-client.d.ts +31 -0
- package/dist/swagger2-client.js +92 -0
- package/package.json +4 -3
- package/src/README.md +2 -1
package/dist/code-generator.js
CHANGED
|
@@ -9,7 +9,8 @@ import { ensureDirectoryExists } from "./ensure-directory-exists.js";
|
|
|
9
9
|
import { centralTypes } from "./central-types.js";
|
|
10
10
|
import { OperationCoder } from "./operation-coder.js";
|
|
11
11
|
import { assertNoNormalizedPathCollisions, normalizeOpenApiPath, } from "./openapi-path.js";
|
|
12
|
-
import {
|
|
12
|
+
import { generateClient as writeClient } from "./generate-client.js";
|
|
13
|
+
import { pathOperations } from "./path-operations.js";
|
|
13
14
|
import { Requirement } from "./requirement.js";
|
|
14
15
|
import { Repository } from "./repository.js";
|
|
15
16
|
import { Specification } from "./specification.js";
|
|
@@ -56,7 +57,7 @@ export class CodeGenerator extends EventTarget {
|
|
|
56
57
|
await fs.writeFile(gitignorePath, ".cache\n", "utf8");
|
|
57
58
|
}
|
|
58
59
|
debug("creating the .cache/README.md file");
|
|
59
|
-
ensureDirectoryExists(cacheReadmePath);
|
|
60
|
+
await ensureDirectoryExists(cacheReadmePath);
|
|
60
61
|
await fs.writeFile(cacheReadmePath, "This directory contains compiled JS files from the paths directory. Do not edit these files directly.\n", "utf8");
|
|
61
62
|
}
|
|
62
63
|
/**
|
|
@@ -82,12 +83,13 @@ export class CodeGenerator extends EventTarget {
|
|
|
82
83
|
*
|
|
83
84
|
* Loads the OpenAPI spec from `openapiPath`, optionally prunes defunct route
|
|
84
85
|
* files, registers all path operations as {@link OperationCoder} exports, and
|
|
85
|
-
* writes the resulting TypeScript files to `destination`.
|
|
86
|
+
* writes the resulting TypeScript files to `destination`. Type generation
|
|
87
|
+
* also writes a Fetch client.
|
|
86
88
|
*
|
|
87
89
|
* @param repository - Injectable repository instance; defaults to a fresh one
|
|
88
90
|
* (primarily useful in tests).
|
|
89
91
|
*/
|
|
90
|
-
async generate(repository = new Repository()) {
|
|
92
|
+
async generate(repository = new Repository(), deferWrite = false) {
|
|
91
93
|
const { destination } = this;
|
|
92
94
|
debug("generating code from %s to %s", this.openapiPath, destination);
|
|
93
95
|
debug("initializing the .cache directory");
|
|
@@ -102,68 +104,34 @@ export class CodeGenerator extends EventTarget {
|
|
|
102
104
|
debug("got %i paths", paths?.map?.length ?? 0);
|
|
103
105
|
const openApiPaths = paths.map((_pathDefinition, key) => key);
|
|
104
106
|
assertNoNormalizedPathCollisions(openApiPaths);
|
|
105
|
-
if (this.generateOptions.prune && this.generateOptions.routes) {
|
|
106
|
-
debug("pruning defunct route files");
|
|
107
|
-
await pruneRoutes(destination, openApiPaths);
|
|
108
|
-
debug("done pruning");
|
|
109
|
-
}
|
|
110
107
|
const securityRequirement = specification.getRequirement("#/components/securitySchemes");
|
|
111
108
|
const securitySchemes = Object.values(securityRequirement?.data ?? {});
|
|
112
|
-
const HTTP_VERBS = new Set([
|
|
113
|
-
"get",
|
|
114
|
-
"put",
|
|
115
|
-
"post",
|
|
116
|
-
"delete",
|
|
117
|
-
"options",
|
|
118
|
-
"head",
|
|
119
|
-
"patch",
|
|
120
|
-
"trace",
|
|
121
|
-
]);
|
|
122
|
-
const operationMethodsForPath = (pathDefinition) => {
|
|
123
|
-
let resolved = pathDefinition;
|
|
124
|
-
while (resolved.isReference)
|
|
125
|
-
resolved = resolved.reference();
|
|
126
|
-
return resolved.flatMap((operation, requestMethod) => {
|
|
127
|
-
if (requestMethod === "additionalOperations") {
|
|
128
|
-
return operation.map((additionalOperation, additionalMethod) => [
|
|
129
|
-
additionalOperation,
|
|
130
|
-
additionalMethod.toLowerCase(),
|
|
131
|
-
]);
|
|
132
|
-
}
|
|
133
|
-
if (!HTTP_VERBS.has(requestMethod)) {
|
|
134
|
-
return [];
|
|
135
|
-
}
|
|
136
|
-
return [[operation, requestMethod]];
|
|
137
|
-
});
|
|
138
|
-
};
|
|
139
109
|
paths.forEach((pathDefinition, key) => {
|
|
140
110
|
debug("processing path %s", key);
|
|
141
111
|
const normalizedPath = normalizeOpenApiPath(key);
|
|
142
112
|
const path = normalizedPath === "/" ? "/index" : normalizedPath;
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
// a method is declared under OpenAPI 3.2 additionalOperations.
|
|
146
|
-
const logicalOperation = new Requirement(operation.data, `${pathDefinition.url}/${requestMethod}`, specification);
|
|
147
|
-
logicalOperation.parent = pathDefinition;
|
|
113
|
+
repository.recordRouteFile(`routes${path}.ts`);
|
|
114
|
+
for (const [operation, requestMethod] of pathOperations(pathDefinition)) {
|
|
148
115
|
repository
|
|
149
|
-
.
|
|
150
|
-
.export(new OperationCoder(
|
|
151
|
-
}
|
|
116
|
+
.route(`routes${path}.ts`, normalizedPath)
|
|
117
|
+
.export(new OperationCoder(operation, this.version, requestMethod, securitySchemes));
|
|
118
|
+
}
|
|
152
119
|
});
|
|
153
|
-
if (
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
await
|
|
158
|
-
...repository.scripts.keys(),
|
|
159
|
-
...(this.version === "" ? [] : ["types/versions.ts"]),
|
|
160
|
-
]);
|
|
161
|
-
debug("done pruning generated type files");
|
|
120
|
+
if (!deferWrite) {
|
|
121
|
+
await this.finishGeneration(repository);
|
|
122
|
+
}
|
|
123
|
+
if (this.generateOptions.types) {
|
|
124
|
+
await writeClient(specification, nodePath.join(destination, "client"), this.version, this.generateOptions);
|
|
162
125
|
}
|
|
163
|
-
debug("telling the repository to write the files to %s", destination);
|
|
164
|
-
await repository.writeFiles(destination, this.generateOptions);
|
|
165
126
|
debug("finished writing the files");
|
|
166
127
|
}
|
|
128
|
+
/** Write the complete shared route layout once all versions have registered. */
|
|
129
|
+
async finishGeneration(repository) {
|
|
130
|
+
await repository.writeFiles(this.destination, {
|
|
131
|
+
...this.generateOptions,
|
|
132
|
+
keepVersionsFile: this.version !== "",
|
|
133
|
+
});
|
|
134
|
+
}
|
|
167
135
|
/**
|
|
168
136
|
* Writes only the schema types, directly into `destination`
|
|
169
137
|
* (or `destination/<version>` for a versioned spec), and nothing else.
|
|
@@ -184,6 +152,11 @@ export class CodeGenerator extends EventTarget {
|
|
|
184
152
|
]);
|
|
185
153
|
return repository.writeSchemas(this.destination, this.version);
|
|
186
154
|
}
|
|
155
|
+
/** Generate a standalone Fetch client for this spec. */
|
|
156
|
+
async generateClient() {
|
|
157
|
+
const specification = await Specification.fromFile(this.openapiPath, this.overlays);
|
|
158
|
+
return writeClient(specification, this.destination, this.version, this.generateOptions);
|
|
159
|
+
}
|
|
187
160
|
/**
|
|
188
161
|
* Starts watching the OpenAPI document and any overlay files for changes.
|
|
189
162
|
*
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type ClientGroupingOptions } from "./named-client-operations.js";
|
|
2
|
+
import type { Specification } from "./specification.js";
|
|
3
|
+
export declare function generateClient(specification: Specification, destination: string, version: string, grouping?: ClientGroupingOptions): Promise<string[]>;
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { exportedConst, literalType, neverType, objectExpression, stringType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, valueExpression, } from "./ast.js";
|
|
3
|
+
import { clientSecurityRequirements, clientSecuritySchemes, } from "./client-security.js";
|
|
4
|
+
import { ClientMultipartSchemaTypeCoder } from "./client-multipart-schema-type-coder.js";
|
|
5
|
+
import { ClientResponseSchemas } from "./client-response-schemas.js";
|
|
6
|
+
import { namedOperations, } from "./named-client-operations.js";
|
|
7
|
+
import { pathOperations } from "./path-operations.js";
|
|
8
|
+
import { Repository } from "./repository.js";
|
|
9
|
+
import { standaloneClientValidators } from "./standalone-client-validators.js";
|
|
10
|
+
import { SchemaTypeCoder } from "./schema-type-coder.js";
|
|
11
|
+
import { isSwagger2, swaggerBody, swaggerCollection, swaggerParameterSchema, swaggerResponse, swaggerServer, } from "./swagger2-client.js";
|
|
12
|
+
const locations = new Map([
|
|
13
|
+
["path", "path"],
|
|
14
|
+
["query", "query"],
|
|
15
|
+
["header", "headers"],
|
|
16
|
+
["cookie", "cookies"],
|
|
17
|
+
]);
|
|
18
|
+
const formMediaType = "application/x-www-form-urlencoded";
|
|
19
|
+
const undefinedType = () => ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword);
|
|
20
|
+
const normalizeMediaType = (mediaType) => mediaType
|
|
21
|
+
.trim()
|
|
22
|
+
.replace(/^[^;]+/u, (essence) => essence.trimEnd().toLowerCase());
|
|
23
|
+
const isJson = (mediaType) => {
|
|
24
|
+
const essence = mediaType.split(";", 1)[0];
|
|
25
|
+
return essence === "application/json" || essence?.endsWith("+json") === true;
|
|
26
|
+
};
|
|
27
|
+
function schemaType(schema, script) {
|
|
28
|
+
return schema ? new SchemaTypeCoder(schema).write(script) : unknownType();
|
|
29
|
+
}
|
|
30
|
+
function multipartContentTypes(media) {
|
|
31
|
+
if (!media)
|
|
32
|
+
return undefined;
|
|
33
|
+
const types = new Map();
|
|
34
|
+
media.get("encoding")?.forEach((part, name) => {
|
|
35
|
+
const contentType = part.get("contentType")?.data;
|
|
36
|
+
if (typeof contentType === "string")
|
|
37
|
+
types.set(name, contentType);
|
|
38
|
+
});
|
|
39
|
+
return types.size ? Object.fromEntries(types) : undefined;
|
|
40
|
+
}
|
|
41
|
+
function parametersFor(operation) {
|
|
42
|
+
const parameters = new Map();
|
|
43
|
+
for (const scope of [operation.parent, operation]) {
|
|
44
|
+
scope?.get("parameters")?.forEach((parameter) => {
|
|
45
|
+
parameters.set(`${String(parameter.get("in")?.data)}:${String(parameter.get("name")?.data)}`, parameter);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const supported = [];
|
|
49
|
+
const swagger = isSwagger2(operation.specification);
|
|
50
|
+
let wholeQuery;
|
|
51
|
+
for (const parameter of parameters.values()) {
|
|
52
|
+
const place = String(parameter.get("in")?.data);
|
|
53
|
+
if (place === "querystring") {
|
|
54
|
+
if (wholeQuery !== undefined)
|
|
55
|
+
return undefined;
|
|
56
|
+
wholeQuery = parameter;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (swagger && (place === "body" || place === "formData"))
|
|
60
|
+
continue;
|
|
61
|
+
const location = locations.get(place);
|
|
62
|
+
if (location === undefined)
|
|
63
|
+
return undefined;
|
|
64
|
+
supported.push({ parameter, place, location });
|
|
65
|
+
}
|
|
66
|
+
if (wholeQuery && supported.some(({ place }) => place === "query"))
|
|
67
|
+
return undefined;
|
|
68
|
+
return { fields: supported, wholeQuery, swagger, parameters };
|
|
69
|
+
}
|
|
70
|
+
function describeWholeQuery(parameter, script) {
|
|
71
|
+
const [content] = parameter.get("content")?.map((media, type) => ({
|
|
72
|
+
media,
|
|
73
|
+
type: normalizeMediaType(type),
|
|
74
|
+
})) ?? [];
|
|
75
|
+
if (!content || (!isJson(content.type) && content.type !== formMediaType))
|
|
76
|
+
return undefined;
|
|
77
|
+
const { media, type: mediaType } = content;
|
|
78
|
+
const encoding = mediaType === formMediaType ? media.get("encoding") : undefined;
|
|
79
|
+
if (mediaType === formMediaType &&
|
|
80
|
+
(media.has("prefixEncoding") ||
|
|
81
|
+
media.has("itemEncoding") ||
|
|
82
|
+
encoding?.find((field) => field.has("encoding") ||
|
|
83
|
+
field.has("prefixEncoding") ||
|
|
84
|
+
field.has("itemEncoding")))) {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
const required = parameter.get("required")?.data === true;
|
|
88
|
+
return {
|
|
89
|
+
type: typeProperty("querystring", typeLiteral([
|
|
90
|
+
typeProperty("value", schemaType(media.get("schema"), script)),
|
|
91
|
+
typeProperty("required", literalType(required)),
|
|
92
|
+
])),
|
|
93
|
+
metadata: {
|
|
94
|
+
required,
|
|
95
|
+
mediaType,
|
|
96
|
+
encoding: encoding &&
|
|
97
|
+
Object.fromEntries(encoding.map((field, name) => [
|
|
98
|
+
name,
|
|
99
|
+
{
|
|
100
|
+
style: field.get("style")?.data,
|
|
101
|
+
explode: field.get("explode")?.data,
|
|
102
|
+
allowReserved: field.get("allowReserved")?.data,
|
|
103
|
+
contentType: field.get("contentType")?.data,
|
|
104
|
+
},
|
|
105
|
+
])),
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function rawBinaryRequest(mediaType, schema, specification) {
|
|
110
|
+
const [essence] = mediaType.split(";", 1);
|
|
111
|
+
if (essence === undefined ||
|
|
112
|
+
essence.includes("*") ||
|
|
113
|
+
isJson(essence) ||
|
|
114
|
+
essence === formMediaType ||
|
|
115
|
+
essence === "multipart/form-data")
|
|
116
|
+
return false;
|
|
117
|
+
if (schema?.get("format")?.data === "binary")
|
|
118
|
+
return true;
|
|
119
|
+
const version = specification?.getRequirement("#/openapi")?.data;
|
|
120
|
+
if (typeof version !== "string" || !/^3\.[1-9]\d*\./u.test(version)) {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
if (schema?.get("type") || schema?.get("contentEncoding"))
|
|
124
|
+
return false;
|
|
125
|
+
if (typeof schema?.get("contentMediaType")?.data === "string")
|
|
126
|
+
return true;
|
|
127
|
+
if (essence.startsWith("text/"))
|
|
128
|
+
return false;
|
|
129
|
+
const data = schema?.data;
|
|
130
|
+
return (data === undefined ||
|
|
131
|
+
data === true ||
|
|
132
|
+
(data !== null &&
|
|
133
|
+
typeof data === "object" &&
|
|
134
|
+
Object.keys(data).length === 0));
|
|
135
|
+
}
|
|
136
|
+
function requestBodyType(mediaType, schema, script, binary) {
|
|
137
|
+
if (isJson(mediaType)) {
|
|
138
|
+
return schemaType(schema, script);
|
|
139
|
+
}
|
|
140
|
+
if (binary || mediaType.split(";", 1)[0] === "application/octet-stream") {
|
|
141
|
+
return unionType([typeReference("Blob"), typeReference("ArrayBuffer")]);
|
|
142
|
+
}
|
|
143
|
+
if (mediaType.startsWith("text/"))
|
|
144
|
+
return stringType();
|
|
145
|
+
if (mediaType === "multipart/form-data")
|
|
146
|
+
return typeReference("FormData");
|
|
147
|
+
if (mediaType === "application/x-www-form-urlencoded")
|
|
148
|
+
return typeReference("URLSearchParams");
|
|
149
|
+
return neverType();
|
|
150
|
+
}
|
|
151
|
+
function responseBodyType(mediaType, schema, script) {
|
|
152
|
+
if (isJson(mediaType))
|
|
153
|
+
return schemaType(schema, script);
|
|
154
|
+
if (mediaType.startsWith("text/"))
|
|
155
|
+
return stringType();
|
|
156
|
+
return typeReference("ArrayBuffer");
|
|
157
|
+
}
|
|
158
|
+
function describe(operation, method, script, schemas) {
|
|
159
|
+
const operationParameters = parametersFor(operation);
|
|
160
|
+
if (operationParameters === undefined)
|
|
161
|
+
return undefined;
|
|
162
|
+
const { swagger } = operationParameters;
|
|
163
|
+
const wholeQuery = operationParameters.wholeQuery &&
|
|
164
|
+
describeWholeQuery(operationParameters.wholeQuery, script);
|
|
165
|
+
if (operationParameters.wholeQuery && !wholeQuery)
|
|
166
|
+
return undefined;
|
|
167
|
+
const inputs = new Map([...locations.values()].map((location) => [location, []]));
|
|
168
|
+
const parameters = operationParameters.fields.map(({ parameter, place, location }) => {
|
|
169
|
+
const name = String(parameter.get("name")?.data);
|
|
170
|
+
const required = place === "path" || parameter.get("required")?.data === true;
|
|
171
|
+
const style = String(parameter.get("style")?.data ??
|
|
172
|
+
(place === "query" || place === "cookie" ? "form" : "simple"));
|
|
173
|
+
const explode = (parameter.get("explode")?.data ?? style === "form") === true;
|
|
174
|
+
const [content] = parameter.get("content")?.map((value, type) => ({ value, type })) ?? [];
|
|
175
|
+
const schema = swagger
|
|
176
|
+
? swaggerParameterSchema(parameter)
|
|
177
|
+
: (content?.value.get("schema") ?? parameter.get("schema"));
|
|
178
|
+
inputs
|
|
179
|
+
.get(location)
|
|
180
|
+
?.push(typeProperty(name, schemaType(schema, script), !required, parameter.data));
|
|
181
|
+
return {
|
|
182
|
+
name,
|
|
183
|
+
location,
|
|
184
|
+
required,
|
|
185
|
+
style,
|
|
186
|
+
explode,
|
|
187
|
+
allowReserved: parameter.get("allowReserved")?.data === true || undefined,
|
|
188
|
+
contentType: content && normalizeMediaType(content.type),
|
|
189
|
+
collectionFormat: swagger ? swaggerCollection(parameter) : undefined,
|
|
190
|
+
};
|
|
191
|
+
});
|
|
192
|
+
const legacyBody = swagger
|
|
193
|
+
? swaggerBody(operation, [...operationParameters.parameters.values()])
|
|
194
|
+
: undefined;
|
|
195
|
+
const requestBody = operation.get("requestBody");
|
|
196
|
+
const bodyRequired = legacyBody?.required ?? requestBody?.get("required")?.data === true;
|
|
197
|
+
const media = legacyBody?.media ??
|
|
198
|
+
requestBody?.get("content")?.map((value, type) => ({
|
|
199
|
+
schema: value.get("schema"),
|
|
200
|
+
type: normalizeMediaType(type),
|
|
201
|
+
})) ??
|
|
202
|
+
[];
|
|
203
|
+
const selected = media.find(({ type }) => isJson(type)) ?? media[0];
|
|
204
|
+
const formFields = legacyBody?.fields;
|
|
205
|
+
const formType = formFields &&
|
|
206
|
+
typeLiteral(formFields.map(({ name, file, required, schema }) => typeProperty(name, file ? typeReference("Blob") : schemaType(schema, script), !required, schema.data)));
|
|
207
|
+
const binary = selected !== undefined &&
|
|
208
|
+
selected.type.split(";", 1)[0] !== "application/octet-stream" &&
|
|
209
|
+
rawBinaryRequest(selected.type, selected.schema, operation.specification);
|
|
210
|
+
const bodyType = selected
|
|
211
|
+
? requestBodyType(selected.type, selected.schema, script, binary)
|
|
212
|
+
: neverType();
|
|
213
|
+
const multipartMedia = selected?.type === "multipart/form-data" && !swagger
|
|
214
|
+
? requestBody
|
|
215
|
+
?.get("content")
|
|
216
|
+
?.find((_, type) => normalizeMediaType(type) === selected.type)
|
|
217
|
+
: undefined;
|
|
218
|
+
const multipartEncoding = multipartMedia?.get("encoding");
|
|
219
|
+
const multipartSchema = multipartMedia && selected?.schema;
|
|
220
|
+
const multipartType = multipartSchema
|
|
221
|
+
? new ClientMultipartSchemaTypeCoder(multipartSchema, "", "root", false, multipartEncoding).write(script)
|
|
222
|
+
: undefined;
|
|
223
|
+
const structuredBody = formType ?? multipartType;
|
|
224
|
+
const responseMetadata = new Map();
|
|
225
|
+
const responseSchemas = new Map();
|
|
226
|
+
const responseTypes = operation.get("responses")?.map((response, key) => {
|
|
227
|
+
const status = key.toUpperCase() === "DEFAULT" ? "default" : key.toUpperCase();
|
|
228
|
+
const noBody = method === "head" || ["204", "205", "304"].includes(status);
|
|
229
|
+
const content = noBody
|
|
230
|
+
? []
|
|
231
|
+
: swagger
|
|
232
|
+
? swaggerResponse(operation, response)
|
|
233
|
+
: (response.get("content")?.map((value, type) => ({
|
|
234
|
+
type: normalizeMediaType(type),
|
|
235
|
+
schema: value.get("schema"),
|
|
236
|
+
})) ?? []);
|
|
237
|
+
responseMetadata.set(status, content.map(({ type }) => type));
|
|
238
|
+
const validation = content.flatMap(({ type, schema }) => {
|
|
239
|
+
return schema && (isJson(type) || type.startsWith("text/"))
|
|
240
|
+
? [[type, schemas.add(schema)]]
|
|
241
|
+
: [];
|
|
242
|
+
});
|
|
243
|
+
if (validation.length > 0)
|
|
244
|
+
responseSchemas.set(status, Object.fromEntries(validation));
|
|
245
|
+
return typeProperty(status, content.length === 0
|
|
246
|
+
? typeLiteral([
|
|
247
|
+
typeProperty("mediaType", undefinedType()),
|
|
248
|
+
typeProperty("body", undefinedType()),
|
|
249
|
+
])
|
|
250
|
+
: unionType(content.map(({ type, schema }) => typeLiteral([
|
|
251
|
+
typeProperty("mediaType", literalType(type)),
|
|
252
|
+
typeProperty("body", responseBodyType(type, schema, script)),
|
|
253
|
+
]))));
|
|
254
|
+
}) ?? [];
|
|
255
|
+
return {
|
|
256
|
+
type: typeLiteral([
|
|
257
|
+
...[...inputs].map(([name, properties]) => typeProperty(name, typeLiteral(properties))),
|
|
258
|
+
...(wholeQuery ? [wholeQuery.type] : []),
|
|
259
|
+
typeProperty("bodyRequired", literalType(bodyRequired)),
|
|
260
|
+
typeProperty("body", structuredBody ? unionType([structuredBody, bodyType]) : bodyType),
|
|
261
|
+
...(selected &&
|
|
262
|
+
["multipart/form-data", formMediaType].includes(selected.type)
|
|
263
|
+
? [
|
|
264
|
+
typeProperty("adapterBody", formType ??
|
|
265
|
+
(multipartSchema
|
|
266
|
+
? new ClientMultipartSchemaTypeCoder(multipartSchema, "", "root", true, multipartEncoding).write(script)
|
|
267
|
+
: schemaType(selected.schema, script))),
|
|
268
|
+
]
|
|
269
|
+
: []),
|
|
270
|
+
typeProperty("responses", typeLiteral(responseTypes)),
|
|
271
|
+
]),
|
|
272
|
+
metadata: {
|
|
273
|
+
parameters,
|
|
274
|
+
querystring: wholeQuery?.metadata,
|
|
275
|
+
body: selected && {
|
|
276
|
+
mediaType: selected.type,
|
|
277
|
+
required: bodyRequired,
|
|
278
|
+
...(binary && { binary: true }),
|
|
279
|
+
formFields: formFields?.map(({ schema: _schema, ...field }) => field),
|
|
280
|
+
multipartContentTypes: multipartContentTypes(multipartMedia),
|
|
281
|
+
},
|
|
282
|
+
responses: Object.fromEntries(responseMetadata),
|
|
283
|
+
security: clientSecurityRequirements(operation),
|
|
284
|
+
responseSchemas: responseSchemas.size > 0
|
|
285
|
+
? Object.fromEntries(responseSchemas)
|
|
286
|
+
: undefined,
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
export async function generateClient(specification, destination, version, grouping = {}) {
|
|
291
|
+
const swagger = isSwagger2(specification);
|
|
292
|
+
if (!swagger && specification.getRequirement("#/swagger")) {
|
|
293
|
+
throw new Error("Fetch client generation supports Swagger 2.0 and OpenAPI 3.x");
|
|
294
|
+
}
|
|
295
|
+
const version2Server = swagger ? swaggerServer(specification) : undefined;
|
|
296
|
+
const defaultBaseUrl = version2Server?.startsWith("http")
|
|
297
|
+
? version2Server
|
|
298
|
+
: undefined;
|
|
299
|
+
const repository = new Repository();
|
|
300
|
+
const script = repository.get("index.ts");
|
|
301
|
+
for (const name of [
|
|
302
|
+
"Operations",
|
|
303
|
+
"createClient",
|
|
304
|
+
"createSdk",
|
|
305
|
+
"operations",
|
|
306
|
+
"sdkOperations",
|
|
307
|
+
]) {
|
|
308
|
+
script.reservedNames.add(name);
|
|
309
|
+
}
|
|
310
|
+
script.comments.push("Generated by Counterfact. Do not edit.");
|
|
311
|
+
const runtime = "@counterfact/client/fetch";
|
|
312
|
+
const factory = script.importExternal("createFetchRoute", runtime);
|
|
313
|
+
const sdkFactory = script.importExternal("defineFetchSdk", runtime);
|
|
314
|
+
const fetchOperations = script.importExternalType("FetchOperations", runtime);
|
|
315
|
+
const options = script.importExternalType(defaultBaseUrl ? "FetchClientOptionsWithDefault" : "FetchClientOptions", runtime);
|
|
316
|
+
const security = clientSecuritySchemes(specification);
|
|
317
|
+
const provider = security.length
|
|
318
|
+
? script.importExternalType("CredentialProvider", runtime)
|
|
319
|
+
: undefined;
|
|
320
|
+
const cookie = security.some(({ scheme }) => scheme.type === "apiKey" && scheme.location === "cookie")
|
|
321
|
+
? script.importExternalType("CookieCredential", runtime)
|
|
322
|
+
: undefined;
|
|
323
|
+
const basic = security.some(({ scheme }) => scheme.type === "basic")
|
|
324
|
+
? script.importExternalType("BasicCredential", runtime)
|
|
325
|
+
: undefined;
|
|
326
|
+
const auth = provider
|
|
327
|
+
? typeLiteral(security.map(({ name, scheme }) => typeProperty(name, typeReference(provider, [
|
|
328
|
+
scheme.type === "apiKey" && scheme.location === "cookie"
|
|
329
|
+
? typeReference(cookie)
|
|
330
|
+
: scheme.type === "basic"
|
|
331
|
+
? typeReference(basic)
|
|
332
|
+
: stringType(),
|
|
333
|
+
]), true)))
|
|
334
|
+
: neverType();
|
|
335
|
+
const securityMetadata = Object.fromEntries(security.map(({ name, scheme }) => [name, scheme]));
|
|
336
|
+
const validation = new ClientResponseSchemas(specification);
|
|
337
|
+
const paths = specification.getRequirement("#/paths")?.flatMap((pathItem, path) => {
|
|
338
|
+
const operations = pathOperations(pathItem).flatMap(([operation, method]) => {
|
|
339
|
+
if (["trace", "connect", "track"].includes(method))
|
|
340
|
+
return [];
|
|
341
|
+
const description = describe(operation, method, script, validation);
|
|
342
|
+
if (!description)
|
|
343
|
+
return [];
|
|
344
|
+
const operationId = operation.get("operationId")?.data;
|
|
345
|
+
const tags = operation.get("tags")?.data;
|
|
346
|
+
return [
|
|
347
|
+
{
|
|
348
|
+
method,
|
|
349
|
+
...description,
|
|
350
|
+
operationId: typeof operationId === "string" ? operationId : undefined,
|
|
351
|
+
tags: Array.isArray(tags)
|
|
352
|
+
? tags.filter((tag) => typeof tag === "string")
|
|
353
|
+
: [],
|
|
354
|
+
},
|
|
355
|
+
];
|
|
356
|
+
});
|
|
357
|
+
return operations.length ? [{ path, operations }] : [];
|
|
358
|
+
}) ?? [];
|
|
359
|
+
const schemaMetadata = validation.output();
|
|
360
|
+
// Always replace this generated module so removing response schemas doesn't leave old validators behind.
|
|
361
|
+
const validators = script.importExternal("responseValidators", "./response-validators.js");
|
|
362
|
+
const validatorSource = schemaMetadata
|
|
363
|
+
? standaloneClientValidators(schemaMetadata)
|
|
364
|
+
: "// Generated by Counterfact. Do not edit.\nexport const responseValidators = {};\n";
|
|
365
|
+
script.statementBuilders.set("client", () => {
|
|
366
|
+
const { createArrowFunction, createCallExpression, createIdentifier, createParameterDeclaration, createToken, } = ts.factory;
|
|
367
|
+
const metadata = Object.fromEntries(paths.map(({ path, operations }) => [
|
|
368
|
+
path,
|
|
369
|
+
Object.fromEntries(operations.map(({ method, metadata }) => [method, metadata])),
|
|
370
|
+
]));
|
|
371
|
+
const operationType = typeReference("Operations");
|
|
372
|
+
const identifier = createIdentifier("operations");
|
|
373
|
+
const sdkIdentifier = createIdentifier("sdkOperations");
|
|
374
|
+
const constExpression = (value) => ts.factory.createAsExpression(valueExpression(value), typeReference("const"));
|
|
375
|
+
const optionsIdentifier = createIdentifier("options");
|
|
376
|
+
const sharedArgs = [
|
|
377
|
+
createIdentifier(validators),
|
|
378
|
+
...(security.length ? [valueExpression(securityMetadata)] : []),
|
|
379
|
+
];
|
|
380
|
+
const declareConst = (name, value, type) => ts.factory.createVariableStatement(undefined, ts.factory.createVariableDeclarationList([ts.factory.createVariableDeclaration(name, undefined, type, value)], ts.NodeFlags.Const));
|
|
381
|
+
const defineFactory = (name, runtimeFactory, typeArguments, args) => exportedConst(name, createArrowFunction(undefined, undefined, [
|
|
382
|
+
createParameterDeclaration(undefined, undefined, optionsIdentifier, defaultBaseUrl
|
|
383
|
+
? createToken(ts.SyntaxKind.QuestionToken)
|
|
384
|
+
: undefined, typeReference(options, [auth])),
|
|
385
|
+
], undefined, createToken(ts.SyntaxKind.EqualsGreaterThanToken), createCallExpression(createIdentifier(runtimeFactory), typeArguments, args)));
|
|
386
|
+
return [
|
|
387
|
+
typeAlias("Operations", typeLiteral(paths.map(({ path, operations }) => typeProperty(path, typeLiteral(operations.map(({ method, type }) => typeProperty(method, type))))))),
|
|
388
|
+
declareConst(identifier, valueExpression(metadata), typeReference(fetchOperations, [operationType])),
|
|
389
|
+
declareConst(sdkIdentifier, constExpression(namedOperations(paths, grouping))),
|
|
390
|
+
defineFactory("createClient", factory, [operationType], [
|
|
391
|
+
identifier,
|
|
392
|
+
defaultBaseUrl
|
|
393
|
+
? ts.factory.createObjectLiteralExpression([
|
|
394
|
+
ts.factory.createSpreadAssignment(optionsIdentifier),
|
|
395
|
+
ts.factory.createPropertyAssignment("baseUrl", ts.factory.createBinaryExpression(ts.factory.createPropertyAccessChain(optionsIdentifier, createToken(ts.SyntaxKind.QuestionDotToken), "baseUrl"), createToken(ts.SyntaxKind.QuestionQuestionToken), valueExpression(defaultBaseUrl))),
|
|
396
|
+
])
|
|
397
|
+
: optionsIdentifier,
|
|
398
|
+
...sharedArgs,
|
|
399
|
+
]),
|
|
400
|
+
exportedConst("createSdk", createCallExpression(createIdentifier(sdkFactory), [
|
|
401
|
+
operationType,
|
|
402
|
+
ts.factory.createTypeQueryNode(sdkIdentifier),
|
|
403
|
+
auth,
|
|
404
|
+
...(defaultBaseUrl ? [literalType(defaultBaseUrl)] : []),
|
|
405
|
+
], [
|
|
406
|
+
objectExpression([
|
|
407
|
+
["operations", identifier],
|
|
408
|
+
...(defaultBaseUrl
|
|
409
|
+
? [["nativeBaseUrl", valueExpression(defaultBaseUrl)]]
|
|
410
|
+
: []),
|
|
411
|
+
]),
|
|
412
|
+
sdkIdentifier,
|
|
413
|
+
...sharedArgs,
|
|
414
|
+
])),
|
|
415
|
+
];
|
|
416
|
+
});
|
|
417
|
+
return repository.writeGeneratedScripts(destination, version, new Map([["response-validators.ts", validatorSource]]));
|
|
418
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface ClientVersion {
|
|
2
|
+
version: string;
|
|
3
|
+
prefix: string;
|
|
4
|
+
}
|
|
5
|
+
interface ClientSource extends ClientVersion {
|
|
6
|
+
group: string;
|
|
7
|
+
}
|
|
8
|
+
/** Write the group entry point after all version-specific clients are generated. */
|
|
9
|
+
export declare function generateVersionedClient(destination: string, versions: readonly ClientVersion[]): Promise<string[]>;
|
|
10
|
+
/** Generate a fluent client across named APIs in configuration order. */
|
|
11
|
+
export declare function generateConsolidatedClient(destination: string, sources: readonly ClientSource[], clientDirectory?: "client" | ""): Promise<string[]>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { exportedConst, literalType, objectExpression, parameter, typeLiteral, typeProperty, typeReference, } from "./ast.js";
|
|
3
|
+
import { pathJoin, pathRelative } from "./forward-slash-path.js";
|
|
4
|
+
import { Repository } from "./repository.js";
|
|
5
|
+
function prefixedRouteSource(prefix, sdk, options) {
|
|
6
|
+
return objectExpression([
|
|
7
|
+
["prefix", ts.factory.createStringLiteral(prefix)],
|
|
8
|
+
[
|
|
9
|
+
"definition",
|
|
10
|
+
ts.factory.createPropertyAccessExpression(sdk, "routeDefinition"),
|
|
11
|
+
],
|
|
12
|
+
["options", options],
|
|
13
|
+
]);
|
|
14
|
+
}
|
|
15
|
+
function exportFactory(name, optionsType, factory, bindings) {
|
|
16
|
+
return exportedConst(name, ts.factory.createArrowFunction(undefined, undefined, [parameter("options", optionsType)], undefined, undefined, ts.factory.createCallExpression(ts.factory.createIdentifier(factory), undefined, [bindings])));
|
|
17
|
+
}
|
|
18
|
+
function versionedFactory(script, name, versions) {
|
|
19
|
+
const tsf = ts.factory;
|
|
20
|
+
const runtime = "@counterfact/client/fetch";
|
|
21
|
+
const fluent = name === "createClient";
|
|
22
|
+
const factoryName = script.importExternal(fluent ? "createPrefixedFetchRoute" : "versionedFetchClient", runtime);
|
|
23
|
+
const fetchOptions = script.importExternal("fetchOptionsForVersion", runtime);
|
|
24
|
+
const commonOptions = script.importExternalType("FetchClientOptions", runtime);
|
|
25
|
+
const options = tsf.createIdentifier("options");
|
|
26
|
+
const versionFactories = versions.map(({ version, prefix }) => {
|
|
27
|
+
const path = `./${pathJoin(version, "index.js")}`;
|
|
28
|
+
return {
|
|
29
|
+
version,
|
|
30
|
+
prefix,
|
|
31
|
+
factory: tsf.createIdentifier(script.importExternal(name, path, fluent)),
|
|
32
|
+
sdk: tsf.createIdentifier(script.importExternal("createSdk", path)),
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
const overrides = typeLiteral(versionFactories.map(({ version, factory }) => {
|
|
36
|
+
const factoryOptions = tsf.createIndexedAccessTypeNode(typeReference("Parameters", [tsf.createTypeQueryNode(factory)]), literalType(0));
|
|
37
|
+
return typeProperty(version, typeReference("Partial", [
|
|
38
|
+
typeReference("NonNullable", [factoryOptions]),
|
|
39
|
+
]), true);
|
|
40
|
+
}));
|
|
41
|
+
const optionsType = tsf.createIntersectionTypeNode([
|
|
42
|
+
typeReference("Omit", [typeReference(commonOptions), literalType("auth")]),
|
|
43
|
+
typeLiteral([typeProperty("versions", overrides, true)]),
|
|
44
|
+
]);
|
|
45
|
+
const entries = versionFactories.map(({ version, prefix, factory, sdk }) => {
|
|
46
|
+
const configuredOptions = tsf.createCallExpression(tsf.createIdentifier(fetchOptions), undefined, [
|
|
47
|
+
options,
|
|
48
|
+
tsf.createStringLiteral(fluent ? "" : prefix),
|
|
49
|
+
tsf.createElementAccessChain(tsf.createPropertyAccessExpression(options, "versions"), tsf.createToken(ts.SyntaxKind.QuestionDotToken), tsf.createStringLiteral(version)),
|
|
50
|
+
]);
|
|
51
|
+
return [
|
|
52
|
+
version,
|
|
53
|
+
fluent
|
|
54
|
+
? prefixedRouteSource(prefix, sdk, configuredOptions)
|
|
55
|
+
: tsf.createArrowFunction(undefined, undefined, [], undefined, undefined, tsf.createCallExpression(factory, undefined, [configuredOptions])),
|
|
56
|
+
];
|
|
57
|
+
});
|
|
58
|
+
const bindings = fluent
|
|
59
|
+
? tsf.createArrayLiteralExpression(entries.map(([, entry]) => entry), true)
|
|
60
|
+
: objectExpression(entries, true);
|
|
61
|
+
return exportFactory(name, optionsType, factoryName, bindings);
|
|
62
|
+
}
|
|
63
|
+
/** Write the group entry point after all version-specific clients are generated. */
|
|
64
|
+
export async function generateVersionedClient(destination, versions) {
|
|
65
|
+
if (versions.length === 0 || versions.some(({ version }) => version === "")) {
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
const repository = new Repository();
|
|
69
|
+
const script = repository.get("index.ts");
|
|
70
|
+
script.reservedNames.add("createClient");
|
|
71
|
+
script.reservedNames.add("createSdk");
|
|
72
|
+
script.comments.push("Generated by Counterfact. Do not edit.");
|
|
73
|
+
const statements = [
|
|
74
|
+
versionedFactory(script, "createClient", versions),
|
|
75
|
+
versionedFactory(script, "createSdk", versions),
|
|
76
|
+
];
|
|
77
|
+
script.statementBuilders.set("versioned-client", () => statements);
|
|
78
|
+
return repository.writeGeneratedScripts(destination, "");
|
|
79
|
+
}
|
|
80
|
+
/** Generate a fluent client across named APIs in configuration order. */
|
|
81
|
+
export async function generateConsolidatedClient(destination, sources, clientDirectory = "client") {
|
|
82
|
+
const root = pathJoin(destination, clientDirectory);
|
|
83
|
+
if (sources.length === 0 ||
|
|
84
|
+
sources.some(({ group }) => pathJoin(destination, group, clientDirectory) === root)) {
|
|
85
|
+
// The unnamed API already generates its entry point here.
|
|
86
|
+
return [];
|
|
87
|
+
}
|
|
88
|
+
const repository = new Repository();
|
|
89
|
+
const script = repository.get("index.ts");
|
|
90
|
+
script.comments.push("Generated by Counterfact. Do not edit.");
|
|
91
|
+
const runtime = "@counterfact/client/fetch";
|
|
92
|
+
const factory = script.importExternal("createPrefixedFetchRoute", runtime);
|
|
93
|
+
const options = script.importExternalType("FetchClientOptions", runtime);
|
|
94
|
+
const entries = sources.map(({ group, version, prefix }) => {
|
|
95
|
+
const file = pathRelative(root, pathJoin(destination, group, clientDirectory, version, "index.js"));
|
|
96
|
+
const module = file.startsWith("../") ? file : `./${file}`;
|
|
97
|
+
const sdk = script.importExternal("createSdk", module);
|
|
98
|
+
return prefixedRouteSource(prefix, ts.factory.createIdentifier(sdk), ts.factory.createIdentifier("options"));
|
|
99
|
+
});
|
|
100
|
+
const createClient = exportFactory("createClient", typeReference(options), factory, ts.factory.createArrayLiteralExpression(entries, true));
|
|
101
|
+
script.statementBuilders.set("consolidated-client", () => [createClient]);
|
|
102
|
+
return repository.writeGeneratedScripts(root, "");
|
|
103
|
+
}
|