@counterfact/generator 1.2.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/adopt-spellings.d.ts +15 -0
  3. package/dist/adopt-spellings.js +48 -0
  4. package/dist/case-safe-paths.d.ts +21 -0
  5. package/dist/case-safe-paths.js +57 -0
  6. package/dist/central-types.d.ts +2 -1
  7. package/dist/central-types.js +2 -2
  8. package/dist/client-multipart-schema-type-coder.d.ts +16 -0
  9. package/dist/client-multipart-schema-type-coder.js +78 -0
  10. package/dist/client-response-schemas.d.ts +29 -0
  11. package/dist/client-response-schemas.js +120 -0
  12. package/dist/client-security.d.ts +10 -0
  13. package/dist/client-security.js +49 -0
  14. package/dist/code-generator.d.ts +22 -4
  15. package/dist/code-generator.js +51 -57
  16. package/dist/generate-client.d.ts +3 -0
  17. package/dist/generate-client.js +418 -0
  18. package/dist/generate-versioned-client.d.ts +12 -0
  19. package/dist/generate-versioned-client.js +103 -0
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +1 -0
  22. package/dist/migrate-route-layout.d.ts +8 -0
  23. package/dist/migrate-route-layout.js +448 -0
  24. package/dist/named-client-operations.d.ts +19 -0
  25. package/dist/named-client-operations.js +96 -0
  26. package/dist/operation-coder.js +3 -3
  27. package/dist/operation-type-coder.d.ts +9 -3
  28. package/dist/operation-type-coder.js +43 -33
  29. package/dist/path-operations.d.ts +2 -0
  30. package/dist/path-operations.js +31 -0
  31. package/dist/prune.d.ts +1 -1
  32. package/dist/prune.js +10 -3
  33. package/dist/repository.d.ts +30 -1
  34. package/dist/repository.js +224 -34
  35. package/dist/requirement.js +3 -1
  36. package/dist/route-file-layout.d.ts +32 -0
  37. package/dist/route-file-layout.js +152 -0
  38. package/dist/scenario-file-generator.js +27 -7
  39. package/dist/script.d.ts +2 -0
  40. package/dist/script.js +16 -4
  41. package/dist/standalone-client-validators.d.ts +2 -0
  42. package/dist/standalone-client-validators.js +85 -0
  43. package/dist/swagger2-client.d.ts +31 -0
  44. package/dist/swagger2-client.js +92 -0
  45. package/examples/generate-routes.mjs +2 -0
  46. package/package.json +4 -3
  47. package/src/README.md +21 -20
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 === coder.modulePath() &&
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
- if (modulePath === this.path)
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.path), entry.script.path.replace(/\.ts$/u, ".js")));
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,2 @@
1
+ import type { ClientResponseSchemas } from "./client-response-schemas.js";
2
+ export declare function standaloneClientValidators(metadata: NonNullable<ReturnType<ClientResponseSchemas["output"]>>): string;
@@ -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
+ }
@@ -10,6 +10,7 @@ const directory = await mkdtemp(path.join(tmpdir(), "counterfact-generator-"));
10
10
  try {
11
11
  const specPath = path.join(directory, "openapi.yaml");
12
12
  const outputPath = path.join(directory, "generated");
13
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- This example reads/writes fixed relative filenames beneath its own mkdtemp directory.
13
14
  await writeFile(
14
15
  specPath,
15
16
  `openapi: 3.0.3
@@ -32,6 +33,7 @@ paths:
32
33
  }).generate();
33
34
 
34
35
  assert.match(
36
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- This example reads/writes fixed relative filenames beneath its own mkdtemp directory.
35
37
  await readFile(path.join(outputPath, "routes", "health.ts"), "utf8"),
36
38
  /export const GET/u,
37
39
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@counterfact/generator",
3
- "version": "1.2.0",
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.3.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
@@ -31,26 +31,27 @@ Both writers serialize helper updates without rewriting each other's exports.
31
31
 
32
32
  ## Files
33
33
 
34
- | File | Description |
35
- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
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) and file watching via `EventTarget` |
37
- | `specification.ts` | `Specification` class: loads and parses an OpenAPI document and provides cached `Requirement` lookup via JSON Pointer |
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 |
40
- | `script.ts` | `Script` class: manages code generation for a single output file — imports, exports, deduplication, and Prettier formatting |
41
- | `coder.ts` | Abstract `Coder` base class: defines the Template Method pattern used by all code-generating components |
42
- | `type-coder.ts` | Abstract `TypeCoder` base class (extends `Coder`): specialises `Coder` for type-generating components |
43
- | `central-types.ts` | Assembles the public `Routes`, `Components`, and `Schemas` maps, preserving logical paths and combining component versions |
44
- | `operation-coder.ts` | `OperationCoder`: generates the route handler function for an OpenAPI operation |
45
- | `operation-type-coder.ts` | `OperationTypeCoder`: generates the TypeScript type for a route handler, including parameters and response builder |
46
- | `parameters-type-coder.ts` | `ParametersTypeCoder`: generates the typed object for path/query/header parameters of an operation |
47
- | `parameter-export-type-coder.ts` | `ParameterExportTypeCoder`: generates and exports the type for a single request parameter |
48
- | `responses-type-coder.ts` | `ResponsesTypeCoder`: generates the response builder factory type covering all HTTP status codes for an operation |
49
- | `response-type-coder.ts` | `ResponseTypeCoder`: generates the type for a single HTTP response, including headers, content, and named examples |
50
- | `schema-type-coder.ts` | `SchemaTypeCoder`: converts an OpenAPI schema definition to a TypeScript type (objects, arrays, unions, enums) |
51
- | `schema-coder.ts` | `SchemaCoder`: generates a JSON Schema representation of an OpenAPI schema for use in runtime validation |
52
- | `ast.ts` | TypeScript AST construction and printing helpers |
53
- | `read-only-comments.ts` | Standard warning comments inserted into generated type files to discourage manual edits |
34
+ | File | Description |
35
+ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
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
+ | `specification.ts` | `Specification` class: loads and parses an OpenAPI document and provides cached `Requirement` lookup via JSON Pointer |
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, and coalesces case-variant generated type scripts before export resolution |
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 |
42
+ | `coder.ts` | Abstract `Coder` base class: defines the Template Method pattern used by all code-generating components |
43
+ | `type-coder.ts` | Abstract `TypeCoder` base class (extends `Coder`): specialises `Coder` for type-generating components |
44
+ | `central-types.ts` | Assembles the public `Routes`, `Components`, and `Schemas` maps, preserving logical paths and combining component versions |
45
+ | `operation-coder.ts` | `OperationCoder`: generates the route handler function for an OpenAPI operation |
46
+ | `operation-type-coder.ts` | `OperationTypeCoder`: generates the TypeScript type for a route handler, including parameters and response builder |
47
+ | `parameters-type-coder.ts` | `ParametersTypeCoder`: generates the typed object for path/query/header parameters of an operation |
48
+ | `parameter-export-type-coder.ts` | `ParameterExportTypeCoder`: generates and exports the type for a single request parameter |
49
+ | `responses-type-coder.ts` | `ResponsesTypeCoder`: generates the response builder factory type covering all HTTP status codes for an operation |
50
+ | `response-type-coder.ts` | `ResponseTypeCoder`: generates the type for a single HTTP response, including headers, content, and named examples |
51
+ | `schema-type-coder.ts` | `SchemaTypeCoder`: converts an OpenAPI schema definition to a TypeScript type (objects, arrays, unions, enums) |
52
+ | `schema-coder.ts` | `SchemaCoder`: generates a JSON Schema representation of an OpenAPI schema for use in runtime validation |
53
+ | `ast.ts` | TypeScript AST construction and printing helpers |
54
+ | `read-only-comments.ts` | Standard warning comments inserted into generated type files to discourage manual edits |
54
55
 
55
56
  ## Architecture
56
57