@counterfact/generator 0.1.5 → 0.1.6

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.
@@ -1,6 +1,8 @@
1
+ import ts from "typescript";
2
+ import { typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
3
+ import { TypeCoder } from "./type-coder.js";
1
4
  import { pathJoin } from "./forward-slash-path.js";
2
5
  import { buildJsDoc } from "./jsdoc.js";
3
- import { TypeCoder } from "./type-coder.js";
4
6
  import { Requirement } from "./requirement.js";
5
7
  export class SchemaTypeCoder extends TypeCoder {
6
8
  names() {
@@ -11,92 +13,89 @@ export class SchemaTypeCoder extends TypeCoder {
11
13
  }
12
14
  additionalPropertiesType(script) {
13
15
  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";
16
+ if (!additionalProperties.type ||
17
+ Object.values(properties ?? {}).some((property) => property.type !== additionalProperties.type)) {
18
+ return unknownType();
19
19
  }
20
- const requirement = this.requirement.get("additionalProperties");
21
- return new SchemaTypeCoder(requirement, this.version).write(script);
20
+ return new SchemaTypeCoder(this.requirement.get("additionalProperties"), this.version).write(script);
22
21
  }
23
22
  objectSchema(script) {
24
- const { data } = this.requirement;
25
- const typedData = data;
26
- const properties = Object.keys(typedData.properties ?? {}).map((name) => {
23
+ const data = this.requirement.data;
24
+ const members = Object.keys(data.properties ?? {}).map((name) => {
27
25
  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}`;
26
+ const isRequired = data.required?.includes(name) ||
27
+ property.data.required === true;
28
+ return typeProperty(name, new SchemaTypeCoder(property, this.version).write(script), !isRequired, property.data);
35
29
  });
36
- if (typedData.additionalProperties) {
37
- properties.push(`[key: string]: ${this.additionalPropertiesType(script)}`);
30
+ if (data.additionalProperties) {
31
+ members.push(ts.factory.createIndexSignature(undefined, [
32
+ ts.factory.createParameterDeclaration(undefined, undefined, "key", undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
33
+ ], this.additionalPropertiesType(script)));
38
34
  }
39
- return `{${properties.join(",")}}`;
35
+ return typeLiteral(members);
40
36
  }
41
37
  arraySchema(script) {
42
- return `Array<${new SchemaTypeCoder(this.requirement.get("items"), this.version).write(script)}>`;
38
+ return typeReference("Array", [
39
+ new SchemaTypeCoder(this.requirement.get("items"), this.version).write(script),
40
+ ]);
43
41
  }
44
42
  writePrimitive(value) {
45
43
  if (typeof value === "string") {
46
- return `"${value}"`;
44
+ return ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(value));
45
+ }
46
+ if (typeof value === "number") {
47
+ const literal = ts.factory.createNumericLiteral(Math.abs(value));
48
+ return ts.factory.createLiteralTypeNode(value < 0
49
+ ? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, literal)
50
+ : literal);
51
+ }
52
+ if (typeof value === "boolean") {
53
+ return ts.factory.createLiteralTypeNode(value ? ts.factory.createTrue() : ts.factory.createFalse());
47
54
  }
48
55
  if (value === null) {
49
- return "null";
56
+ return ts.factory.createLiteralTypeNode(ts.factory.createNull());
50
57
  }
51
- return String(value);
58
+ return unknownType();
52
59
  }
53
60
  writeType(script, type) {
54
61
  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";
62
+ return unionType(type.map((item) => this.writeType(script, item)));
63
+ }
64
+ switch (type) {
65
+ case "object":
66
+ return this.objectSchema(script);
67
+ case "array":
68
+ return this.arraySchema(script);
69
+ case "integer":
70
+ case "number":
71
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
72
+ case "string":
73
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
74
+ case "boolean":
75
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
76
+ case "null":
77
+ return ts.factory.createLiteralTypeNode(ts.factory.createNull());
78
+ default:
79
+ return unknownType();
61
80
  }
62
- if (type === "object") {
63
- return this.objectSchema(script);
64
- }
65
- if (type === "array") {
66
- return this.arraySchema(script);
67
- }
68
- if (type === "integer") {
69
- return "number";
70
- }
71
- return type ?? "unknown";
72
81
  }
73
82
  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();
83
+ const key = allOf ? "allOf" : anyOf ? "anyOf" : "oneOf";
84
84
  const items = (allOf ?? anyOf ?? oneOf);
85
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)
86
+ // OpenAPI 3.2 discriminator fallback participates in the union.
87
87
  if (!allOf) {
88
88
  const { discriminator } = this.requirement.data;
89
89
  if (discriminator?.defaultMapping) {
90
- const defaultRequirement = new Requirement({ $ref: discriminator.defaultMapping }, "", this.requirement.specification);
91
- types.push(new SchemaTypeCoder(defaultRequirement, this.version).write(script));
90
+ types.push(new SchemaTypeCoder(new Requirement({ $ref: discriminator.defaultMapping }, "", this.requirement.specification), this.version).write(script));
92
91
  }
93
92
  }
94
- return types.join(allOf ? " & " : " | ");
93
+ return allOf
94
+ ? ts.factory.createIntersectionTypeNode(types)
95
+ : unionType(types);
95
96
  }
96
- writeEnum(_script, requirement) {
97
- return requirement.data
98
- .map((item) => this.writePrimitive(item))
99
- .join(" | ");
97
+ writeEnum(requirement) {
98
+ return unionType(requirement.data.map((item) => this.writePrimitive(item)));
100
99
  }
101
100
  modulePath() {
102
101
  return pathJoin("types", this.version, this.requirement.refUrl.replace(/^#\//u, "") + ".ts");
@@ -105,16 +104,21 @@ export class SchemaTypeCoder extends TypeCoder {
105
104
  const { allOf, anyOf, oneOf, type, format, itemSchema } = this.requirement
106
105
  .data;
107
106
  if (itemSchema) {
108
- return `AsyncIterable<${new SchemaTypeCoder(this.requirement.get("itemSchema"), this.version).write(script)}>`;
107
+ return typeReference("AsyncIterable", [
108
+ new SchemaTypeCoder(this.requirement.get("itemSchema"), this.version).write(script),
109
+ ]);
109
110
  }
110
111
  if (allOf ?? anyOf ?? oneOf) {
111
112
  return this.writeGroup(script, { allOf, anyOf, oneOf });
112
113
  }
113
114
  if (this.requirement.has("enum")) {
114
- return this.writeEnum(script, this.requirement.get("enum"));
115
+ return this.writeEnum(this.requirement.get("enum"));
115
116
  }
116
117
  if ((type === "string" && format === "binary") || type === "file") {
117
- return "Uint8Array | string";
118
+ return unionType([
119
+ typeReference("Uint8Array"),
120
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
121
+ ]);
118
122
  }
119
123
  return this.writeType(script, type);
120
124
  }
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 {};