@counterfact/generator 0.1.5 → 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.
Files changed (45) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/ast.d.ts +23 -0
  3. package/dist/ast.js +142 -0
  4. package/dist/coder.d.ts +16 -22
  5. package/dist/coder.js +15 -17
  6. package/dist/operation-coder.d.ts +5 -3
  7. package/dist/operation-coder.js +40 -25
  8. package/dist/operation-type-coder.d.ts +17 -25
  9. package/dist/operation-type-coder.js +115 -129
  10. package/dist/operation-type-name-mapping.d.ts +3 -2
  11. package/dist/operation-type-name-mapping.js +22 -10
  12. package/dist/parameter-export-type-coder.d.ts +4 -3
  13. package/dist/parameters-type-coder.d.ts +2 -1
  14. package/dist/parameters-type-coder.js +7 -18
  15. package/dist/repository.d.ts +3 -10
  16. package/dist/repository.js +244 -95
  17. package/dist/response-type-coder.d.ts +7 -7
  18. package/dist/response-type-coder.js +37 -53
  19. package/dist/responses-type-coder.d.ts +4 -4
  20. package/dist/responses-type-coder.js +39 -26
  21. package/dist/sanitize-identifier.d.ts +1 -0
  22. package/dist/sanitize-identifier.js +17 -0
  23. package/dist/scenario-file-generator.js +137 -134
  24. package/dist/schema-coder.d.ts +6 -4
  25. package/dist/schema-coder.js +31 -22
  26. package/dist/schema-required-properties.d.ts +3 -0
  27. package/dist/schema-required-properties.js +47 -0
  28. package/dist/schema-type-coder.d.ts +10 -8
  29. package/dist/schema-type-coder.js +157 -64
  30. package/dist/script.d.ts +18 -95
  31. package/dist/script.js +137 -212
  32. package/dist/templates/counterfact-types/middleware.ts +15 -2
  33. package/dist/templates/counterfact-types/response-builder-factory.ts +102 -6
  34. package/dist/templates/counterfact-types/response-builder.ts +1 -0
  35. package/dist/templates/counterfact-types/wide-operation-argument.ts +13 -1
  36. package/dist/type-coder.d.ts +3 -1
  37. package/dist/type-coder.js +5 -1
  38. package/dist/versions-ts-generator.d.ts +0 -9
  39. package/dist/versions-ts-generator.js +46 -77
  40. package/package.json +5 -4
  41. package/src/README.md +23 -2
  42. package/dist/context-file-token.d.ts +0 -1
  43. package/dist/context-file-token.js +0 -1
  44. package/dist/printers.d.ts +0 -2
  45. package/dist/printers.js +0 -10
@@ -1,6 +1,9 @@
1
+ import ts from "typescript";
2
+ import { typeLiteral, typeProperty, typeReference, unionType, unknownType, neverType, } from "./ast.js";
3
+ import { requireProperties } from "./schema-required-properties.js";
4
+ import { TypeCoder } from "./type-coder.js";
1
5
  import { pathJoin } from "./forward-slash-path.js";
2
6
  import { buildJsDoc } from "./jsdoc.js";
3
- import { TypeCoder } from "./type-coder.js";
4
7
  import { Requirement } from "./requirement.js";
5
8
  export class SchemaTypeCoder extends TypeCoder {
6
9
  names() {
@@ -11,110 +14,200 @@ export class SchemaTypeCoder extends TypeCoder {
11
14
  }
12
15
  additionalPropertiesType(script) {
13
16
  const { additionalProperties, properties } = this.requirement.data;
14
- if (!additionalProperties.type) {
15
- return "unknown";
16
- }
17
- if (Object.values(properties ?? {}).some((property) => property.type !== additionalProperties.type)) {
18
- return "unknown";
17
+ if (typeof additionalProperties !== "object" ||
18
+ (Object.keys(properties ?? {}).length > 0 &&
19
+ (!additionalProperties.type ||
20
+ Object.values(properties ?? {}).some((property) => property.type !== additionalProperties.type)))) {
21
+ return unknownType();
19
22
  }
20
- const requirement = this.requirement.get("additionalProperties");
21
- return new SchemaTypeCoder(requirement, this.version).write(script);
23
+ return new SchemaTypeCoder(this.requirement.get("additionalProperties"), this.version).write(script);
22
24
  }
23
25
  objectSchema(script) {
24
- const { data } = this.requirement;
25
- const typedData = data;
26
- const properties = Object.keys(typedData.properties ?? {}).map((name) => {
26
+ const data = this.requirement.data;
27
+ const members = Object.keys(data.properties ?? {}).map((name) => {
27
28
  const property = this.requirement.get("properties").get(name);
28
- const propertyData = property.data;
29
- const isRequired = typedData.required?.includes(name) || propertyData.required === true;
30
- const optionalFlag = isRequired ? "" : "?";
31
- const comment = buildJsDoc(property.data);
32
- const commentPrefix = comment ? `\n${comment}` : "";
33
- const propertyType = new SchemaTypeCoder(property, this.version).write(script);
34
- return `${commentPrefix}"${name}"${optionalFlag}: ${propertyType}`;
29
+ const isRequired = data.required?.includes(name) ||
30
+ property.data.required === true;
31
+ return typeProperty(name, new SchemaTypeCoder(property, this.version).write(script), !isRequired, property.data);
35
32
  });
36
- if (typedData.additionalProperties) {
37
- properties.push(`[key: string]: ${this.additionalPropertiesType(script)}`);
33
+ if (data.additionalProperties) {
34
+ members.push(ts.factory.createIndexSignature(undefined, [
35
+ ts.factory.createParameterDeclaration(undefined, undefined, "key", undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
36
+ ], this.additionalPropertiesType(script)));
38
37
  }
39
- return `{${properties.join(",")}}`;
38
+ return typeLiteral(members);
40
39
  }
41
40
  arraySchema(script) {
42
- return `Array<${new SchemaTypeCoder(this.requirement.get("items"), this.version).write(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");
69
+ return typeReference("Array", [
70
+ items
71
+ ? new SchemaTypeCoder(items, this.version).write(script)
72
+ : unknownType(),
73
+ ]);
43
74
  }
44
75
  writePrimitive(value) {
45
76
  if (typeof value === "string") {
46
- return `"${value}"`;
77
+ return ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(value));
78
+ }
79
+ if (typeof value === "number") {
80
+ const literal = ts.factory.createNumericLiteral(Math.abs(value));
81
+ return ts.factory.createLiteralTypeNode(value < 0
82
+ ? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, literal)
83
+ : literal);
84
+ }
85
+ if (typeof value === "boolean") {
86
+ return ts.factory.createLiteralTypeNode(value ? ts.factory.createTrue() : ts.factory.createFalse());
47
87
  }
48
88
  if (value === null) {
49
- return "null";
89
+ return ts.factory.createLiteralTypeNode(ts.factory.createNull());
50
90
  }
51
- return String(value);
91
+ return unknownType();
52
92
  }
53
93
  writeType(script, type) {
54
94
  if (Array.isArray(type)) {
55
- return type
56
- .map((item) => this.writeType(script, item))
57
- .join(" | ");
58
- }
59
- if (typeof type !== "string") {
60
- return "unknown";
61
- }
62
- if (type === "object") {
63
- return this.objectSchema(script);
64
- }
65
- if (type === "array") {
66
- return this.arraySchema(script);
95
+ return unionType(type.map((item) => this.writeType(script, item)));
96
+ }
97
+ switch (type) {
98
+ case "object":
99
+ return this.objectSchema(script);
100
+ case "array":
101
+ return this.arraySchema(script);
102
+ case "integer":
103
+ case "number":
104
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
105
+ case "string":
106
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
107
+ case "boolean":
108
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
109
+ case "null":
110
+ return ts.factory.createLiteralTypeNode(ts.factory.createNull());
111
+ default:
112
+ if (type === undefined &&
113
+ (this.requirement.has("properties") ||
114
+ this.requirement.has("additionalProperties"))) {
115
+ return this.objectSchema(script);
116
+ }
117
+ return unknownType();
67
118
  }
68
- if (type === "integer") {
69
- return "number";
70
- }
71
- return type ?? "unknown";
72
119
  }
73
120
  writeGroup(script, { allOf, anyOf, oneOf, }) {
74
- function matchingKey() {
75
- if (allOf) {
76
- return "allOf";
77
- }
78
- if (anyOf) {
79
- return "anyOf";
80
- }
81
- return "oneOf";
82
- }
83
- const key = matchingKey();
121
+ const key = allOf ? "allOf" : anyOf ? "anyOf" : "oneOf";
84
122
  const items = (allOf ?? anyOf ?? oneOf);
85
- const types = items.map((_item, index) => new SchemaTypeCoder(this.requirement.get(key).get(index), this.version).write(script));
86
- // Include the default schema from discriminator.defaultMapping (OpenAPI 3.2)
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
+ });
141
+ // OpenAPI 3.2 discriminator fallback participates in the union.
87
142
  if (!allOf) {
88
143
  const { discriminator } = this.requirement.data;
89
144
  if (discriminator?.defaultMapping) {
90
- const defaultRequirement = new Requirement({ $ref: discriminator.defaultMapping }, "", this.requirement.specification);
91
- types.push(new SchemaTypeCoder(defaultRequirement, this.version).write(script));
145
+ types.push(new SchemaTypeCoder(new Requirement({ $ref: discriminator.defaultMapping }, "", this.requirement.specification), this.version).write(script));
92
146
  }
93
147
  }
94
- return types.join(allOf ? " & " : " | ");
148
+ return allOf
149
+ ? ts.factory.createIntersectionTypeNode(types)
150
+ : unionType(types);
95
151
  }
96
- writeEnum(_script, requirement) {
97
- return requirement.data
98
- .map((item) => this.writePrimitive(item))
99
- .join(" | ");
152
+ writeEnum(requirement) {
153
+ return unionType(requirement.data.map((item) => this.writePrimitive(item)));
100
154
  }
101
155
  modulePath() {
102
156
  return pathJoin("types", this.version, this.requirement.refUrl.replace(/^#\//u, "") + ".ts");
103
157
  }
104
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) {
105
174
  const { allOf, anyOf, oneOf, type, format, itemSchema } = this.requirement
106
175
  .data;
107
176
  if (itemSchema) {
108
- return `AsyncIterable<${new SchemaTypeCoder(this.requirement.get("itemSchema"), this.version).write(script)}>`;
177
+ return typeReference("AsyncIterable", [
178
+ new SchemaTypeCoder(this.requirement.get("itemSchema"), this.version).write(script),
179
+ ]);
109
180
  }
110
181
  if (allOf ?? anyOf ?? oneOf) {
111
- return this.writeGroup(script, { allOf, anyOf, oneOf });
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);
112
202
  }
113
203
  if (this.requirement.has("enum")) {
114
- return this.writeEnum(script, this.requirement.get("enum"));
204
+ return this.writeEnum(this.requirement.get("enum"));
115
205
  }
116
206
  if ((type === "string" && format === "binary") || type === "file") {
117
- return "Uint8Array | string";
207
+ return unionType([
208
+ typeReference("Uint8Array"),
209
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
210
+ ]);
118
211
  }
119
212
  return this.writeType(script, type);
120
213
  }
package/dist/script.d.ts CHANGED
@@ -1,130 +1,53 @@
1
+ import ts from "typescript";
1
2
  import type { Coder, ExportStatement } from "./coder.js";
2
3
  import type { Repository } from "./repository.js";
3
4
  interface ImportEntry {
5
+ id: string;
4
6
  isDefault: boolean;
5
7
  isType: boolean;
6
8
  name: string;
7
9
  script: Script;
8
10
  }
11
+ export type ModuleReference = string | {
12
+ context: true;
13
+ };
9
14
  interface ExternalImportEntry {
10
15
  isDefault?: boolean;
11
16
  isType: boolean;
12
- modulePath: string;
17
+ modulePath: ModuleReference;
13
18
  }
14
- /**
15
- * Represents a single TypeScript file being assembled by the code generator.
16
- *
17
- * A `Script` accumulates exports, imports, and external imports contributed by
18
- * {@link Coder} instances. Once all coders have resolved, {@link contents}
19
- * formats the result with Prettier and returns the final source text.
20
- *
21
- * Scripts are created and retrieved through a {@link Repository} so that the
22
- * same module path always maps to the same `Script` instance.
23
- */
19
+ /** One generated module: coders register nodes; printing occurs after resolution. */
24
20
  export declare class Script {
21
+ path: string;
25
22
  repository: Repository;
26
23
  comments: string[];
27
24
  exports: Map<string, ExportStatement>;
28
25
  versions: Map<string, Map<string, ExportStatement>>;
29
- versionFormatters: Map<string, (versionCodes: Map<string, string>) => string>;
26
+ versionBuilders: Map<string, (versions: Map<string, ts.TypeNode>) => ts.Statement[]>;
30
27
  imports: Map<string, ImportEntry>;
31
28
  externalImport: Map<string, ExternalImportEntry>;
32
29
  cache: Map<string, string>;
33
- typeCache: Map<string, string>;
34
- path: string;
35
30
  constructor(repository: Repository, path: string);
36
- /**
37
- * A `"../"` path fragment that points from this script's directory back to
38
- * the repository root, used to resolve relative import paths.
39
- */
40
31
  get relativePathToBase(): string;
41
- /**
42
- * Picks the first name from `coder.names()` that is not already used as an
43
- * import in this script, ensuring export/import name uniqueness.
44
- *
45
- * @param coder - The coder needing a name.
46
- * @throws When all 100 candidate names are already taken.
47
- */
48
- firstUniqueName(coder: Coder): string;
49
- /**
50
- * Registers an export for `coder` in this script and returns the export name.
51
- *
52
- * If the same coder has already been exported (cache hit), the previously
53
- * assigned name is returned without creating a duplicate.
54
- *
55
- * @param coder - The coder to export.
56
- * @param isType - Emit `export type` instead of `export const`.
57
- * @param isDefault - Emit `export default` instead of a named export.
58
- * @returns The name under which the coder is exported.
59
- */
32
+ firstUniqueName(coder: Coder, isType?: boolean, isDefault?: boolean): string;
60
33
  export(coder: Coder, isType?: boolean, isDefault?: boolean): string;
61
34
  exportDefault(coder: Coder, isType?: boolean): void;
62
- /**
63
- * Registers an import of `coder` from its owning module and returns the
64
- * local alias used in this script.
65
- *
66
- * The coder is also exported from its home module as a side effect.
67
- *
68
- * @param coder - The coder to import.
69
- * @param isType - Use a `import type` declaration.
70
- * @param isDefault - Import the default export rather than a named export.
71
- */
72
35
  import(coder: Coder, isType?: boolean, isDefault?: boolean): string;
73
36
  importType(coder: Coder): string;
74
37
  importDefault(coder: Coder, isType?: boolean): string;
75
- /**
76
- * Registers an import from an external npm package or absolute module path
77
- * (not managed by the repository).
78
- *
79
- * @param name - The local binding name.
80
- * @param modulePath - The module specifier (e.g. `"counterfact-types/index"`).
81
- * @param isType - Use a `import type` declaration.
82
- * @returns `name` (for convenience in method chaining).
83
- */
84
- importExternal(name: string, modulePath: string, isType?: boolean): string;
85
- /**
86
- * Convenience wrapper that calls {@link importExternal} with `isType = true`.
87
- */
88
- importExternalType(name: string, modulePath: string): string;
89
- /**
90
- * Imports a type from the shared `counterfact-types/index.ts` module,
91
- * resolving the path relative to this script's location in the repository.
92
- *
93
- * @param name - The type name to import (e.g. `"WideOperationArgument"`).
94
- */
38
+ importExternal(name: string, modulePath: ModuleReference, isType?: boolean): string;
39
+ importExternalType(name: string, path: ModuleReference): string;
95
40
  importSharedType(name: string): string;
96
- /**
97
- * Imports a type from the generated `types/versions.ts` module,
98
- * resolving the path relative to this script's location in the repository.
99
- *
100
- * @param name - The type name to import (e.g. `"Versioned"`).
101
- */
102
41
  importVersionsType(name: string): string;
103
42
  exportType(coder: Coder): string;
104
- /**
105
- * Registers a formatter function for the merged versioned type emitted under
106
- * `name` by {@link versionsTypeStatements}.
107
- *
108
- * When a formatter is present for a name, `versionsTypeStatements` delegates
109
- * the entire type declaration to it instead of generating the default
110
- * `Versions` object type. The formatter receives a `Map<version, importAlias>`
111
- * and must return the complete TypeScript source for that operation type.
112
- */
113
- setVersionFormatter(name: string, formatter: (versionCodes: Map<string, string>) => string): void;
43
+ setVersionBuilder(name: string, builder: (versions: Map<string, ts.TypeNode>) => ts.Statement[]): void;
114
44
  declareVersion(coder: Coder, name: string): void;
115
- /** `true` while at least one export promise is still pending. */
116
45
  isInProgress(): boolean;
117
- /** Returns a promise that resolves when all pending export promises settle. */
118
46
  finished(): Promise<(Coder | undefined)[]>;
119
- externalImportStatements(): string[];
120
- importStatements(): string[];
121
- exportStatements(): string[];
122
- versionsTypeStatements(): string[];
123
- /**
124
- * Formats the fully assembled script source with Prettier and returns it.
125
- *
126
- * All pending export promises are awaited before formatting.
127
- */
128
- contents(): Promise<string>;
47
+ externalImportStatements(contextPath?: string): ts.ImportDeclaration[];
48
+ importStatements(): ts.ImportDeclaration[];
49
+ exportStatements(): ts.Statement[];
50
+ versionsTypeStatements(): ts.Statement[];
51
+ contents(contextPath?: string): Promise<string>;
129
52
  }
130
53
  export {};