@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/script.js
CHANGED
|
@@ -19,6 +19,15 @@ export class Script {
|
|
|
19
19
|
reservedNames = new Set();
|
|
20
20
|
localTypes = new Map();
|
|
21
21
|
statementBuilders = new Map();
|
|
22
|
+
primaryVersionPaths = new Map();
|
|
23
|
+
operationVersionKey(name, logicalPath) {
|
|
24
|
+
const first = this.primaryVersionPaths.get(name);
|
|
25
|
+
if (first === undefined) {
|
|
26
|
+
this.primaryVersionPaths.set(name, logicalPath);
|
|
27
|
+
return name;
|
|
28
|
+
}
|
|
29
|
+
return first === logicalPath ? name : `${name}:${logicalPath}`;
|
|
30
|
+
}
|
|
22
31
|
constructor(repository, path) {
|
|
23
32
|
this.path = path;
|
|
24
33
|
this.repository = repository;
|
|
@@ -35,7 +44,8 @@ export class Script {
|
|
|
35
44
|
if (!this.reservedNames.has(name) &&
|
|
36
45
|
(!this.imports.has(name) ||
|
|
37
46
|
(this.imports.get(name).id === coder.exportId &&
|
|
38
|
-
this.imports.get(name).script.path ===
|
|
47
|
+
this.repository.outputPath(this.imports.get(name).script.path) ===
|
|
48
|
+
this.repository.outputPath(coder.modulePath()) &&
|
|
39
49
|
this.imports.get(name).isType === isType &&
|
|
40
50
|
this.imports.get(name).isDefault === isDefault)) &&
|
|
41
51
|
(!this.exports.has(name) ||
|
|
@@ -91,7 +101,8 @@ export class Script {
|
|
|
91
101
|
const key = `${coder.id}@${modulePath}:${isType}:${isDefault}`;
|
|
92
102
|
if (this.cache.has(key))
|
|
93
103
|
return this.cache.get(key);
|
|
94
|
-
|
|
104
|
+
const script = this.repository.get(modulePath);
|
|
105
|
+
if (script === this)
|
|
95
106
|
return this.export(coder, isType, isDefault);
|
|
96
107
|
let name;
|
|
97
108
|
if (preferredName) {
|
|
@@ -106,7 +117,6 @@ export class Script {
|
|
|
106
117
|
else
|
|
107
118
|
name = this.firstUniqueName(coder, isType, isDefault);
|
|
108
119
|
this.cache.set(key, name);
|
|
109
|
-
const script = this.repository.get(modulePath);
|
|
110
120
|
const exportedName = script.export(coder, isType, isDefault);
|
|
111
121
|
this.imports.set(name, {
|
|
112
122
|
id: coder.exportId,
|
|
@@ -214,7 +224,9 @@ export class Script {
|
|
|
214
224
|
}
|
|
215
225
|
importStatements() {
|
|
216
226
|
return Array.from(this.imports, ([name, entry]) => {
|
|
217
|
-
const path = escapePathForWindows(pathRelative(pathDirname(this.
|
|
227
|
+
const path = escapePathForWindows(pathRelative(pathDirname(this.repository.outputPath(this.path)), this.repository
|
|
228
|
+
.outputPath(entry.script.path)
|
|
229
|
+
.replace(/\.ts$/u, ".js")));
|
|
218
230
|
return importDeclaration(name, path.includes("../") ? path : `./${path}`, entry.isType, entry.isDefault, entry.name);
|
|
219
231
|
});
|
|
220
232
|
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import Ajv from "ajv";
|
|
2
|
+
import Ajv2020 from "ajv/dist/2020.js";
|
|
3
|
+
import standaloneCode from "ajv/dist/standalone/index.js";
|
|
4
|
+
import ts from "typescript";
|
|
5
|
+
import { exportedConst, functionType, importDeclaration, objectExpression, parameter, printStatements, stringType, typeReference, unknownType, } from "./ast.js";
|
|
6
|
+
const helpers = new Map([
|
|
7
|
+
["ajv/dist/runtime/equal", "equal"],
|
|
8
|
+
["ajv/dist/runtime/ucs2length", "ucs2length"],
|
|
9
|
+
]);
|
|
10
|
+
/** Ajv's standalone ESM still uses CommonJS for its runtime helpers. */
|
|
11
|
+
function importHelpers(code) {
|
|
12
|
+
const file = ts.createSourceFile("validators.js", code, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
|
13
|
+
const imports = new Set();
|
|
14
|
+
const replacements = [];
|
|
15
|
+
function visit(node) {
|
|
16
|
+
if (ts.isCallExpression(node) &&
|
|
17
|
+
ts.isIdentifier(node.expression) &&
|
|
18
|
+
node.expression.text === "require") {
|
|
19
|
+
const [argument] = node.arguments;
|
|
20
|
+
const helper = argument && ts.isStringLiteral(argument)
|
|
21
|
+
? helpers.get(argument.text)
|
|
22
|
+
: undefined;
|
|
23
|
+
const access = node.parent;
|
|
24
|
+
if (!helper ||
|
|
25
|
+
!ts.isPropertyAccessExpression(access) ||
|
|
26
|
+
access.name.text !== "default") {
|
|
27
|
+
throw new Error(`Unsupported dependency in generated response validator: ${node.getText(file)}`);
|
|
28
|
+
}
|
|
29
|
+
imports.add(helper);
|
|
30
|
+
replacements.push({
|
|
31
|
+
start: access.getStart(file),
|
|
32
|
+
end: access.getEnd(),
|
|
33
|
+
helper,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
ts.forEachChild(node, visit);
|
|
37
|
+
}
|
|
38
|
+
visit(file);
|
|
39
|
+
for (const { start, end, helper } of replacements.reverse()) {
|
|
40
|
+
code = code.slice(0, start) + helper + code.slice(end);
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
code,
|
|
44
|
+
imports: [...imports].map((helper) => importDeclaration(helper, "@counterfact/client/validation-helpers")),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export function standaloneClientValidators(metadata) {
|
|
48
|
+
const Validator = metadata.draft === "7" ? Ajv : Ajv2020;
|
|
49
|
+
const ajv = new Validator({
|
|
50
|
+
strict: false,
|
|
51
|
+
ownProperties: true,
|
|
52
|
+
strictNumbers: true,
|
|
53
|
+
validateFormats: false,
|
|
54
|
+
code: { source: true, esm: true, lines: true },
|
|
55
|
+
});
|
|
56
|
+
ajv.addSchema(metadata.schema);
|
|
57
|
+
for (const uri of Object.values(metadata.validators)) {
|
|
58
|
+
const validate = ajv.getSchema(uri);
|
|
59
|
+
if (validate && "$async" in validate) {
|
|
60
|
+
throw new Error("Fetch client response schemas must use synchronous validation");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// Ajv assigns its own bindings such as schema12. Give public exports
|
|
64
|
+
// a distinct prefix so a larger schema graph cannot redeclare them.
|
|
65
|
+
const entries = Object.entries(metadata.validators).map(([key, uri], index) => ({
|
|
66
|
+
key,
|
|
67
|
+
uri,
|
|
68
|
+
name: `validateResponse${index}`,
|
|
69
|
+
}));
|
|
70
|
+
const standalone = importHelpers(standaloneCode(ajv, Object.fromEntries(entries.map(({ name, uri }) => [name, uri]))));
|
|
71
|
+
const boolean = ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
|
|
72
|
+
const validatorType = functionType([parameter("body", unknownType())], boolean);
|
|
73
|
+
const registry = exportedConst("responseValidators", objectExpression(entries.map(({ key, name }) => [key, ts.factory.createIdentifier(name)])), typeReference("Readonly", [
|
|
74
|
+
typeReference("Record", [stringType(), validatorType]),
|
|
75
|
+
]));
|
|
76
|
+
// Ajv emits JavaScript. Keep it in the TypeScript build with a typed registry
|
|
77
|
+
// so consumers can emit the validator along with the rest of the client.
|
|
78
|
+
// Keep Ajv's line breaks; reformatting the generated functions adds another
|
|
79
|
+
// full parse and print on every regeneration.
|
|
80
|
+
return ("// @ts-nocheck\n// Generated by Counterfact and Ajv. Do not edit.\n" +
|
|
81
|
+
printStatements(standalone.imports) +
|
|
82
|
+
standalone.code +
|
|
83
|
+
"\n" +
|
|
84
|
+
printStatements([registry]));
|
|
85
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Requirement } from "./requirement.js";
|
|
2
|
+
import type { Specification } from "./specification.js";
|
|
3
|
+
export declare function isSwagger2(specification: Specification | undefined): boolean;
|
|
4
|
+
export declare function swaggerCollection(parameter: Requirement): "multi" | "ssv" | "tsv" | "pipes" | "csv" | undefined;
|
|
5
|
+
export declare function swaggerParameterSchema(parameter: Requirement): Requirement;
|
|
6
|
+
export declare function swaggerBody(operation: Requirement, parameters: readonly Requirement[]): {
|
|
7
|
+
media: {
|
|
8
|
+
type: string;
|
|
9
|
+
schema: Requirement | undefined;
|
|
10
|
+
}[];
|
|
11
|
+
required: boolean;
|
|
12
|
+
fields: undefined;
|
|
13
|
+
} | {
|
|
14
|
+
media: {
|
|
15
|
+
type: "application/x-www-form-urlencoded" | "multipart/form-data";
|
|
16
|
+
schema: undefined;
|
|
17
|
+
}[];
|
|
18
|
+
required: boolean;
|
|
19
|
+
fields: {
|
|
20
|
+
name: string;
|
|
21
|
+
required: boolean;
|
|
22
|
+
file: boolean;
|
|
23
|
+
collectionFormat: string | undefined;
|
|
24
|
+
schema: Requirement;
|
|
25
|
+
}[];
|
|
26
|
+
} | undefined;
|
|
27
|
+
export declare function swaggerResponse(operation: Requirement, response: Requirement): {
|
|
28
|
+
type: string;
|
|
29
|
+
schema: Requirement | undefined;
|
|
30
|
+
}[];
|
|
31
|
+
export declare function swaggerServer(specification: Specification): string;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
const multipart = "multipart/form-data";
|
|
2
|
+
const urlEncoded = "application/x-www-form-urlencoded";
|
|
3
|
+
export function isSwagger2(specification) {
|
|
4
|
+
return specification?.getRequirement("#/swagger")?.data === "2.0";
|
|
5
|
+
}
|
|
6
|
+
function list(requirement) {
|
|
7
|
+
const { data } = requirement ?? {};
|
|
8
|
+
return Array.isArray(data)
|
|
9
|
+
? data.filter((value) => typeof value === "string")
|
|
10
|
+
: [];
|
|
11
|
+
}
|
|
12
|
+
function mediaTypes(operation, key) {
|
|
13
|
+
return list(operation.get(key) ?? operation.specification?.getRequirement(`#/${key}`)).map((type) => type.toLowerCase());
|
|
14
|
+
}
|
|
15
|
+
export function swaggerCollection(parameter) {
|
|
16
|
+
if (parameter.get("type")?.data !== "array")
|
|
17
|
+
return undefined;
|
|
18
|
+
const format = parameter.get("collectionFormat")?.data;
|
|
19
|
+
switch (format) {
|
|
20
|
+
case "multi":
|
|
21
|
+
case "ssv":
|
|
22
|
+
case "tsv":
|
|
23
|
+
case "pipes":
|
|
24
|
+
return format;
|
|
25
|
+
default:
|
|
26
|
+
return "csv";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function swaggerParameterSchema(parameter) {
|
|
30
|
+
while (parameter.isReference)
|
|
31
|
+
parameter = parameter.reference();
|
|
32
|
+
return parameter;
|
|
33
|
+
}
|
|
34
|
+
export function swaggerBody(operation, parameters) {
|
|
35
|
+
const content = mediaTypes(operation, "consumes");
|
|
36
|
+
const body = parameters.find((parameter) => parameter.get("in")?.data === "body");
|
|
37
|
+
if (body) {
|
|
38
|
+
return {
|
|
39
|
+
media: (content.length ? content : ["application/json"]).map((type) => ({
|
|
40
|
+
type,
|
|
41
|
+
schema: body.get("schema"),
|
|
42
|
+
})),
|
|
43
|
+
required: body.get("required")?.data === true,
|
|
44
|
+
fields: undefined,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const fields = parameters
|
|
48
|
+
.filter((parameter) => parameter.get("in")?.data === "formData")
|
|
49
|
+
.map((parameter) => ({
|
|
50
|
+
name: String(parameter.get("name")?.data),
|
|
51
|
+
required: parameter.get("required")?.data === true,
|
|
52
|
+
file: parameter.get("type")?.data === "file",
|
|
53
|
+
collectionFormat: swaggerCollection(parameter),
|
|
54
|
+
schema: swaggerParameterSchema(parameter),
|
|
55
|
+
}));
|
|
56
|
+
if (fields.length === 0)
|
|
57
|
+
return undefined;
|
|
58
|
+
const type = fields.some(({ file }) => file)
|
|
59
|
+
? multipart
|
|
60
|
+
: (content.find((media) => media === urlEncoded || media === multipart) ??
|
|
61
|
+
urlEncoded);
|
|
62
|
+
return {
|
|
63
|
+
media: [{ type, schema: undefined }],
|
|
64
|
+
required: fields.some(({ required }) => required),
|
|
65
|
+
fields,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export function swaggerResponse(operation, response) {
|
|
69
|
+
const schema = response.get("schema");
|
|
70
|
+
if (!schema)
|
|
71
|
+
return [];
|
|
72
|
+
const file = schema.get("type")?.data === "file";
|
|
73
|
+
const types = mediaTypes(operation, "produces");
|
|
74
|
+
return (types.length
|
|
75
|
+
? types
|
|
76
|
+
: [file ? "application/octet-stream" : "application/json"]).map((type) => ({ type, schema: file ? undefined : schema }));
|
|
77
|
+
}
|
|
78
|
+
export function swaggerServer(specification) {
|
|
79
|
+
const source = specification.rootRequirement.url;
|
|
80
|
+
const origin = /^https?:\/\//iu.test(source) && URL.canParse(source)
|
|
81
|
+
? new URL(source)
|
|
82
|
+
: undefined;
|
|
83
|
+
const host = specification.getRequirement("#/host")?.data ?? origin?.host;
|
|
84
|
+
const basePath = specification.getRequirement("#/basePath")?.data;
|
|
85
|
+
const path = typeof basePath === "string" && basePath !== "/" ? basePath : "";
|
|
86
|
+
const scheme = list(specification.getRequirement("#/schemes")).find((value) => value === "http" || value === "https") ??
|
|
87
|
+
origin?.protocol.slice(0, -1) ??
|
|
88
|
+
"https";
|
|
89
|
+
if (typeof host !== "string" || host === "")
|
|
90
|
+
return path;
|
|
91
|
+
return `${scheme}://${host}${path}`;
|
|
92
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@counterfact/generator",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Generate Counterfact route scaffolds and OpenAPI-derived TypeScript contracts.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -46,14 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|
|
49
|
-
"build": "rimraf dist && tsc --build --force && copyfiles -f \"../types/src/*.ts\" dist/templates/counterfact-types && rimraf dist/templates/counterfact-types/streaming-content-types.ts",
|
|
49
|
+
"build": "rimraf dist && tsc --build --force && copyfiles -f \"../types/src/*.ts\" dist/templates/counterfact-types && rimraf dist/templates/counterfact-types/streaming-content-types.ts dist/templates/counterfact-types/client-route.ts",
|
|
50
50
|
"prepack": "yarn build",
|
|
51
51
|
"test": "node --experimental-vm-modules ../../node_modules/jest-cli/bin/jest.js --config ../../jest.config.js packages/generator/test",
|
|
52
52
|
"test:packed-consumer": "node test/package/generator-consumer-smoke.mjs"
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
55
|
"@counterfact/openapi": "0.1.7",
|
|
56
|
-
"@counterfact/types": "0.
|
|
56
|
+
"@counterfact/types": "0.4.0",
|
|
57
|
+
"ajv": "8.20.0",
|
|
57
58
|
"chokidar": "6.0.0",
|
|
58
59
|
"debug": "4.4.3",
|
|
59
60
|
"prettier": "3.9.10",
|
package/src/README.md
CHANGED
|
@@ -36,8 +36,9 @@ Both writers serialize helper updates without rewriting each other's exports.
|
|
|
36
36
|
| `code-generator.ts` | Top-level `CodeGenerator` class; orchestrates the full generate pipeline (reads the OpenAPI spec, iterates over paths/operations, drives the `Repository` to write output files; `generateSchemas()` writes only the component schema types) and file watching via `EventTarget` |
|
|
37
37
|
| `specification.ts` | `Specification` class: loads and parses an OpenAPI document and provides cached `Requirement` lookup via JSON Pointer |
|
|
38
38
|
| `requirement.ts` | `Requirement` class: wraps a single OpenAPI schema object with its URL and resolves `$ref` pointers |
|
|
39
|
-
| `repository.ts` | `Repository` class: manages all output `Script` instances, deduplicates them, and coordinates async export resolution
|
|
39
|
+
| `repository.ts` | `Repository` class: manages all output `Script` instances, deduplicates them, and coordinates async export resolution, and coalesces case-variant generated type scripts before export resolution |
|
|
40
40
|
| `script.ts` | `Script` class: manages code generation for a single output file — imports, exports, deduplication, and Prettier formatting |
|
|
41
|
+
| `case-safe-paths.ts` | `caseSafeOutputPaths()`: gives distinct generated helper-type paths to legacy case-variant middleware directories |
|
|
41
42
|
| `coder.ts` | Abstract `Coder` base class: defines the Template Method pattern used by all code-generating components |
|
|
42
43
|
| `type-coder.ts` | Abstract `TypeCoder` base class (extends `Coder`): specialises `Coder` for type-generating components |
|
|
43
44
|
| `central-types.ts` | Assembles the public `Routes`, `Components`, and `Schemas` maps, preserving logical paths and combining component versions |
|