@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
@@ -4,9 +4,10 @@ import nodePath, { dirname } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  /* eslint-disable security/detect-non-literal-fs-filename -- repository writes and stats generated files only inside destination output directories. */
6
6
  import createDebug from "debug";
7
+ import ts from "typescript";
8
+ import { formatStatements, importDeclaration, parameter, typeReference, withJsDoc, } from "./ast.js";
7
9
  import { ensureDirectoryExists } from "./ensure-directory-exists.js";
8
10
  import { toForwardSlashPath, pathRelative, pathDirname, } from "./forward-slash-path.js";
9
- import { CONTEXT_FILE_TOKEN } from "./context-file-token.js";
10
11
  import { Script } from "./script.js";
11
12
  import { escapePathForWindows } from "./windows-escape.js";
12
13
  const debug = createDebug("counterfact:server:repository");
@@ -113,7 +114,7 @@ export class Repository {
113
114
  debug("all %i scripts are finished", this.scripts.size);
114
115
  const writeFiles = Array.from(this.scripts.entries(), async ([path, script]) => {
115
116
  const fullPath = resolveDestinationPath(destination, path);
116
- const contents = await script.contents();
117
+ const contents = await script.contents(this.findContextPath(destination, path));
117
118
  await ensureDirectoryExists(fullPath);
118
119
  const shouldWriteRoutes = routes && path.startsWith("routes");
119
120
  const shouldWriteTypes = types && !path.startsWith("routes");
@@ -124,13 +125,13 @@ export class Repository {
124
125
  .catch(() => false);
125
126
  if (fileExists) {
126
127
  debug(`route file exists, checking for new handlers: ${fullPath}`);
127
- await this.appendNewHandlers(fullPath, contents.replaceAll(CONTEXT_FILE_TOKEN, this.findContextPath(destination, path)));
128
+ await this.appendNewHandlers(fullPath, script);
128
129
  return;
129
130
  }
130
131
  }
131
132
  if (shouldWriteRoutes || shouldWriteTypes) {
132
133
  debug("about to write", fullPath);
133
- await fs.writeFile(fullPath, contents.replaceAll(CONTEXT_FILE_TOKEN, this.findContextPath(destination, path)));
134
+ await fs.writeFile(fullPath, contents);
134
135
  debug("did write", fullPath);
135
136
  }
136
137
  });
@@ -152,109 +153,257 @@ export class Repository {
152
153
  return;
153
154
  }
154
155
  await ensureDirectoryExists(contextFilePath);
155
- await fs.writeFile(contextFilePath, `import type { Context$ } from "../types/_.context.js";
156
-
157
- /**
158
- * This is the default context for Counterfact.
159
- *
160
- * It defines the context object in the REPL
161
- * and the $.context object in the code.
162
- *
163
- * Add properties and methods to suit your needs.
164
- *
165
- * See https://github.com/counterfact/api-simulator/blob/main/docs/features/state.md
166
- */
167
-
168
- export class Context {
169
- constructor($: Context$) {
170
- void $;
171
- }
172
- }
173
- `);
156
+ const context = withJsDoc(ts.factory.createClassDeclaration([ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], "Context", undefined, undefined, [
157
+ ts.factory.createConstructorDeclaration(undefined, [parameter("$", typeReference("Context$"))], ts.factory.createBlock([
158
+ ts.factory.createExpressionStatement(ts.factory.createVoidExpression(ts.factory.createIdentifier("$"))),
159
+ ], true)),
160
+ ]), {
161
+ description: "This is the default context for Counterfact.\n\n" +
162
+ "It defines the context object in the REPL\nand the $.context object in the code.\n\n" +
163
+ "Add properties and methods to suit your needs.\n\n" +
164
+ "See https://github.com/counterfact/api-simulator/blob/main/docs/features/state.md",
165
+ });
166
+ await fs.writeFile(contextFilePath, await formatStatements([
167
+ importDeclaration("Context$", "../types/_.context.js", true),
168
+ context,
169
+ ]));
174
170
  }
175
171
  /**
176
- * Appends any HTTP-method handler exports that appear in `generatedContent`
177
- * but are absent from the existing file at `fullPath`.
178
- *
179
- * For each new export the corresponding `import type` statement is inserted
180
- * after the last existing import line (or prepended when no imports exist),
181
- * and the export block is appended at the end of the file.
182
- *
183
- * @param fullPath - Absolute path of the route file to update.
184
- * @param generatedContent - The fully-generated file content (used as the
185
- * source of new import and export statements).
172
+ * Inserts newly generated handlers and their type imports without reprinting
173
+ * existing user code. Only the existing file is parsed; generated declarations
174
+ * are taken directly from the Script's AST.
186
175
  */
187
- async appendNewHandlers(fullPath, generatedContent) {
188
- const existingContent = await fs.readFile(fullPath, "utf8");
189
- // Names already exported by the existing file (e.g. GET, POST).
190
- // RegExp match groups are typed as optional strings, so narrow defensively.
191
- const existingExportNames = new Set(Array.from(existingContent.matchAll(/^export\s+const\s+(\w+)/gmu), (m) => m[1]).filter((name) => name !== undefined));
192
- // All named exports in the generated content together with their type names.
193
- const generatedExports = Array.from(generatedContent.matchAll(/^export\s+const\s+(\w+)\s*:\s*(\w+)/gmu), (m) => ({ methodName: m[1], typeName: m[2] })).filter((value) => value.methodName !== undefined && value.typeName !== undefined);
194
- const newExports = generatedExports.filter(({ methodName }) => !existingExportNames.has(methodName));
195
- if (newExports.length === 0) {
196
- debug(`no new handlers to append to ${fullPath}`);
197
- return;
198
- }
199
- debug(`appending ${newExports.length} new handler(s) to ${fullPath}: %o`, newExports.map(({ methodName }) => methodName));
200
- const newImportLines = [];
201
- const newExportBlocks = [];
202
- for (const { methodName, typeName } of newExports) {
203
- // Both names come from \w+ captures so they are safe identifiers, but
204
- // guard explicitly to satisfy static analysis and avoid RegExp injection.
205
- if (!/^\w+$/u.test(typeName) || !/^\w+$/u.test(methodName)) {
206
- debug(`skipping handler with unsafe name – methodName: %s, typeName: %s`, methodName, typeName);
207
- continue;
176
+ async appendNewHandlers(fullPath, script) {
177
+ const existing = await fs.readFile(fullPath, "utf8");
178
+ const source = ts.createSourceFile(fullPath, existing, ts.ScriptTarget.Latest, true);
179
+ const exported = new Set();
180
+ const bindings = new Set();
181
+ const valueBindings = new Set();
182
+ const imports = new Map();
183
+ let lastImport;
184
+ const collectBinding = (name) => {
185
+ if (ts.isIdentifier(name)) {
186
+ bindings.add(name.text);
187
+ valueBindings.add(name.text);
188
+ }
189
+ else
190
+ for (const element of name.elements) {
191
+ if (ts.isBindingElement(element))
192
+ collectBinding(element.name);
193
+ }
194
+ };
195
+ for (const statement of source.statements) {
196
+ const isExported = ts.canHaveModifiers(statement) &&
197
+ ts
198
+ .getModifiers(statement)
199
+ ?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
200
+ if (ts.isVariableStatement(statement)) {
201
+ for (const declaration of statement.declarationList.declarations) {
202
+ collectBinding(declaration.name);
203
+ if (isExported && ts.isIdentifier(declaration.name))
204
+ exported.add(declaration.name.text);
205
+ }
208
206
  }
209
- // Find the `import type { TypeName } from "..."` line for this type.
210
- const importMatch = generatedContent.match(new RegExp(`^import\\s+type\\s+\\{[^}]*\\b${typeName}\\b[^}]*\\}\\s+from\\s+["'][^"']+["'];`, "mu"));
211
- if (importMatch?.[0] && !existingContent.includes(importMatch[0])) {
212
- newImportLines.push(importMatch[0]);
207
+ else if ((ts.isFunctionDeclaration(statement) ||
208
+ ts.isClassDeclaration(statement) ||
209
+ ts.isEnumDeclaration(statement) ||
210
+ ts.isTypeAliasDeclaration(statement) ||
211
+ ts.isInterfaceDeclaration(statement)) &&
212
+ statement.name) {
213
+ bindings.add(statement.name.text);
214
+ if (!ts.isTypeAliasDeclaration(statement) &&
215
+ !ts.isInterfaceDeclaration(statement)) {
216
+ valueBindings.add(statement.name.text);
217
+ if (isExported)
218
+ exported.add(statement.name.text);
219
+ }
213
220
  }
214
- // Find the export block: from `export const METHOD` to the closing `};`.
215
- // The generated code is always Prettier-formatted, so the closing brace
216
- // and semicolon of every top-level arrow-function export appear on their
217
- // own line as `\n};`.
218
- const startMatch = new RegExp(`^export\\s+const\\s+${methodName}\\b`, "mu").exec(generatedContent);
219
- if (startMatch) {
220
- const fromExport = generatedContent.slice(startMatch.index);
221
- const closingIndex = fromExport.indexOf("\n};");
222
- if (closingIndex !== -1) {
223
- // Include the closing `};` (3 chars: \n, }, ;)
224
- newExportBlocks.push(fromExport.slice(0, closingIndex + 3));
221
+ else if (ts.isExportDeclaration(statement)) {
222
+ if (statement.isTypeOnly)
223
+ continue;
224
+ // Resolve aliases and re-exports using TypeScript's value namespace,
225
+ // without loading or executing any user-authored JavaScript.
226
+ const program = ts.createProgram([fullPath], {
227
+ allowJs: true,
228
+ noLib: true,
229
+ types: [],
230
+ module: ts.ModuleKind.ESNext,
231
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
232
+ });
233
+ const checker = program.getTypeChecker();
234
+ const moduleSource = program.getSourceFile(fullPath);
235
+ const hasValue = (symbol) => {
236
+ if (!symbol)
237
+ return false;
238
+ if (symbol.flags & ts.SymbolFlags.Alias) {
239
+ if (symbol.declarations?.some((declaration) => (ts.isExportSpecifier(declaration) &&
240
+ (declaration.isTypeOnly ||
241
+ declaration.parent.parent.isTypeOnly)) ||
242
+ (ts.isImportSpecifier(declaration) &&
243
+ (declaration.isTypeOnly ||
244
+ declaration.parent.parent.isTypeOnly))))
245
+ return false;
246
+ return hasValue(checker.getAliasedSymbol(symbol));
247
+ }
248
+ return (symbol.flags & ts.SymbolFlags.Value) !== 0;
249
+ };
250
+ const item = moduleSource.statements.find((candidate) => candidate.pos === statement.pos);
251
+ if (ts.isExportDeclaration(item)) {
252
+ if (item.exportClause && ts.isNamedExports(item.exportClause)) {
253
+ for (const element of item.exportClause.elements)
254
+ if (!element.isTypeOnly &&
255
+ hasValue(checker.getSymbolAtLocation(element.name)))
256
+ exported.add(element.name.text);
257
+ }
258
+ else if (item.exportClause &&
259
+ ts.isNamespaceExport(item.exportClause)) {
260
+ if (hasValue(checker.getSymbolAtLocation(item.exportClause.name)))
261
+ exported.add(item.exportClause.name.text);
262
+ }
263
+ else if (item.moduleSpecifier) {
264
+ const symbol = checker.getSymbolAtLocation(item.moduleSpecifier);
265
+ if (!symbol)
266
+ throw new Error("Cannot resolve a star re-export while updating " + fullPath);
267
+ for (const entry of checker.getExportsOfModule(symbol))
268
+ if (entry.name !== "default" && hasValue(entry))
269
+ exported.add(entry.name);
270
+ }
271
+ }
272
+ }
273
+ if (ts.isImportDeclaration(statement)) {
274
+ lastImport = statement;
275
+ if (statement.importClause?.name) {
276
+ bindings.add(statement.importClause.name.text);
277
+ if (!statement.importClause.isTypeOnly)
278
+ valueBindings.add(statement.importClause.name.text);
279
+ }
280
+ const named = statement.importClause?.namedBindings;
281
+ if (named && ts.isNamespaceImport(named)) {
282
+ bindings.add(named.name.text);
283
+ if (!statement.importClause?.isTypeOnly)
284
+ valueBindings.add(named.name.text);
285
+ }
286
+ else if (named && ts.isStringLiteral(statement.moduleSpecifier)) {
287
+ for (const element of named.elements) {
288
+ bindings.add(element.name.text);
289
+ if (!statement.importClause?.isTypeOnly && !element.isTypeOnly)
290
+ valueBindings.add(element.name.text);
291
+ imports.set(element.name.text, {
292
+ module: statement.moduleSpecifier.text,
293
+ exported: element.propertyName?.text ?? element.name.text,
294
+ });
295
+ }
225
296
  }
226
297
  }
227
298
  }
228
- let updatedContent = existingContent;
229
- // Insert new import lines right after the last existing import statement.
230
- if (newImportLines.length > 0) {
231
- const importMatches = [...existingContent.matchAll(/^import\s[^\n]*/gmu)];
232
- if (importMatches.length > 0) {
233
- const lastImport = importMatches[importMatches.length - 1];
234
- const importIndex = lastImport?.index;
235
- const insertPos = importIndex === undefined
236
- ? 0
237
- : (() => {
238
- const lineEnd = existingContent.indexOf("\n", importIndex);
239
- return lineEnd === -1 ? existingContent.length : lineEnd + 1;
240
- })();
241
- updatedContent =
242
- existingContent.slice(0, insertPos) +
243
- newImportLines.join("\n") +
244
- "\n" +
245
- existingContent.slice(insertPos);
299
+ const newImports = [];
300
+ const handlers = [];
301
+ const generatedImports = script.importStatements();
302
+ for (const statement of script.exportStatements()) {
303
+ if (!ts.isVariableStatement(statement))
304
+ continue;
305
+ const declaration = statement.declarationList.declarations[0];
306
+ if (!declaration ||
307
+ !ts.isIdentifier(declaration.name) ||
308
+ exported.has(declaration.name.text))
309
+ continue;
310
+ if (valueBindings.has(declaration.name.text))
311
+ throw new Error("Cannot add handler " +
312
+ declaration.name.text +
313
+ ": a local binding already exists in " +
314
+ fullPath);
315
+ if (!declaration.type ||
316
+ !ts.isTypeReferenceNode(declaration.type) ||
317
+ !ts.isIdentifier(declaration.type.typeName)) {
318
+ throw new Error("Generated handler lacks a named type: " + declaration.name.text);
319
+ }
320
+ let localType = declaration.type.typeName.text;
321
+ const originalType = localType;
322
+ const imported = generatedImports.flatMap((item) => {
323
+ const named = item.importClause?.namedBindings;
324
+ return named && ts.isNamedImports(named)
325
+ ? named.elements
326
+ .filter((element) => element.name.text === originalType)
327
+ .map((element) => ({ item, element }))
328
+ : [];
329
+ })[0];
330
+ if (!imported || !ts.isStringLiteral(imported.item.moduleSpecifier))
331
+ throw new Error("Cannot find handler type import for " + declaration.name.text);
332
+ const module = imported.item.moduleSpecifier.text;
333
+ const exportedType = imported.element.propertyName?.text ?? imported.element.name.text;
334
+ const existingImport = imports.get(localType);
335
+ if (!existingImport ||
336
+ existingImport.module !== module ||
337
+ existingImport.exported !== exportedType) {
338
+ let suffix = 2;
339
+ while (bindings.has(localType))
340
+ localType = originalType + suffix++;
341
+ newImports.push(importDeclaration(localType, module, true, false, exportedType));
342
+ imports.set(localType, { module, exported: exportedType });
343
+ bindings.add(localType);
344
+ }
345
+ handlers.push(ts.factory.updateVariableStatement(statement, statement.modifiers, ts.factory.updateVariableDeclarationList(statement.declarationList, [
346
+ ts.factory.updateVariableDeclaration(declaration, declaration.name, declaration.exclamationToken, typeReference(localType), declaration.initializer),
347
+ ])));
348
+ exported.add(declaration.name.text);
349
+ bindings.add(declaration.name.text);
350
+ valueBindings.add(declaration.name.text);
351
+ }
352
+ if (handlers.length === 0)
353
+ return;
354
+ // Include complete trailing comments before inserting after an import.
355
+ const afterLine = (position) => {
356
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, existing);
357
+ scanner.setTextPos(position);
358
+ let end = position;
359
+ for (let token = scanner.scan(); token !== ts.SyntaxKind.EndOfFileToken; token = scanner.scan()) {
360
+ if (token === ts.SyntaxKind.NewLineTrivia)
361
+ return scanner.getTextPos();
362
+ if (token !== ts.SyntaxKind.WhitespaceTrivia &&
363
+ token !== ts.SyntaxKind.SingleLineCommentTrivia &&
364
+ token !== ts.SyntaxKind.MultiLineCommentTrivia)
365
+ break;
366
+ end = scanner.getTextPos();
246
367
  }
247
- else {
248
- updatedContent = newImportLines.join("\n") + "\n" + existingContent;
368
+ return end;
369
+ };
370
+ let insertAt = lastImport ? afterLine(lastImport.end) : 0;
371
+ if (!lastImport) {
372
+ const references = [
373
+ ...source.referencedFiles,
374
+ ...source.typeReferenceDirectives,
375
+ ...source.libReferenceDirectives,
376
+ ];
377
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, existing);
378
+ const trivia = new Set([
379
+ ts.SyntaxKind.WhitespaceTrivia,
380
+ ts.SyntaxKind.NewLineTrivia,
381
+ ts.SyntaxKind.SingleLineCommentTrivia,
382
+ ts.SyntaxKind.MultiLineCommentTrivia,
383
+ ts.SyntaxKind.ShebangTrivia,
384
+ ts.SyntaxKind.ConflictMarkerTrivia,
385
+ ]);
386
+ for (let token = scanner.scan(); trivia.has(token); token = scanner.scan()) {
387
+ const start = scanner.getTokenPos();
388
+ const end = scanner.getTextPos();
389
+ if (token === ts.SyntaxKind.ShebangTrivia ||
390
+ references.some((reference) => start <= reference.pos && end >= reference.end))
391
+ insertAt = afterLine(end);
249
392
  }
250
393
  }
251
- // Append new export blocks at the end of the file.
252
- if (newExportBlocks.length > 0) {
253
- const separator = updatedContent.endsWith("\n") ? "\n" : "\n\n";
254
- updatedContent += separator + newExportBlocks.join("\n\n") + "\n";
394
+ let updated = existing;
395
+ if (newImports.length > 0) {
396
+ const prefix = existing.slice(0, insertAt);
397
+ updated =
398
+ prefix +
399
+ (prefix !== "" && !prefix.endsWith("\n") ? "\n" : "") +
400
+ (await formatStatements(newImports)) +
401
+ existing.slice(insertAt);
255
402
  }
256
- await fs.writeFile(fullPath, updatedContent);
257
- debug(`appended new handlers to ${fullPath}`);
403
+ updated +=
404
+ (updated.endsWith("\n") ? "\n" : "\n\n") +
405
+ (await formatStatements(handlers));
406
+ await fs.writeFile(fullPath, updated);
258
407
  }
259
408
  /**
260
409
  * Returns the path of the `_.context.ts` file that is nearest to `path` in
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { TypeCoder } from "./type-coder.js";
2
3
  import type { Requirement } from "./requirement.js";
3
4
  import type { Script } from "./script.js";
@@ -5,12 +6,11 @@ export declare class ResponseTypeCoder extends TypeCoder {
5
6
  openApi2MediaTypes: string[];
6
7
  constructor(requirement: Requirement, version?: string, openApi2MediaTypes?: string[]);
7
8
  names(): Generator<string>;
8
- buildContentObjectType(script: Script, response: Requirement): [string, string][];
9
- printContentObjectType(script: Script, response: Requirement): string;
10
- buildHeaders(script: Script, response: Requirement): [string, string][];
11
- printHeaders(script: Script, response: Requirement): string;
12
- printRequiredHeaders(response: Requirement): string;
13
- buildExamplesObjectType(response: Requirement): string;
9
+ buildContentObjectType(script: Script, response: Requirement): [string, ts.TypeNode][];
10
+ contentType(script: Script, response: Requirement): ts.TypeNode;
11
+ headersType(script: Script, response: Requirement): ts.TypeNode;
12
+ requiredHeadersType(response: Requirement): ts.TypeNode;
13
+ buildExamplesObjectType(response: Requirement): ts.TypeLiteralNode;
14
14
  modulePath(): string;
15
- writeCode(script: Script): string;
15
+ writeCode(script: Script): ts.TypeNode;
16
16
  }
@@ -1,8 +1,9 @@
1
1
  import { STREAMING_CONTENT_TYPES } from "@counterfact/types/streaming-content-types";
2
+ import ts from "typescript";
3
+ import { neverType, typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
4
+ import { TypeCoder } from "./type-coder.js";
2
5
  import { pathJoin } from "./forward-slash-path.js";
3
- import { printObject } from "./printers.js";
4
6
  import { SchemaTypeCoder } from "./schema-type-coder.js";
5
- import { TypeCoder } from "./type-coder.js";
6
7
  export class ResponseTypeCoder extends TypeCoder {
7
8
  openApi2MediaTypes;
8
9
  constructor(requirement, version = "", openApi2MediaTypes = []) {
@@ -20,85 +21,68 @@ export class ResponseTypeCoder extends TypeCoder {
20
21
  let schemaType;
21
22
  if (content.has("itemSchema") &&
22
23
  STREAMING_CONTENT_TYPES.has(mediaType)) {
23
- schemaType = `AsyncIterable<${new SchemaTypeCoder(content.get("itemSchema"), this.version).write(script)}>`;
24
+ schemaType = typeReference("AsyncIterable", [
25
+ new SchemaTypeCoder(content.get("itemSchema"), this.version).write(script),
26
+ ]);
24
27
  }
25
28
  else {
26
29
  schemaType = content.has("schema")
27
30
  ? new SchemaTypeCoder(content.get("schema"), this.version).write(script)
28
- : "unknown";
31
+ : unknownType();
29
32
  }
30
33
  return [
31
34
  mediaType,
32
- `{
33
- schema: ${schemaType}
34
- }`,
35
+ typeLiteral([typeProperty("schema", schemaType)], true),
35
36
  ];
36
37
  });
37
38
  }
38
39
  return this.openApi2MediaTypes.map((mediaType) => [
39
40
  mediaType,
40
- `{
41
- schema: ${new SchemaTypeCoder(response.get("schema"), this.version).write(script)}
42
- }`,
41
+ typeLiteral([
42
+ typeProperty("schema", new SchemaTypeCoder(response.get("schema"), this.version).write(script)),
43
+ ], true),
43
44
  ]);
44
45
  }
45
- printContentObjectType(script, response) {
46
- if (response.has("content") || response.has("schema")) {
47
- return printObject(this.buildContentObjectType(script, response));
48
- }
49
- return "never";
50
- }
51
- buildHeaders(script, response) {
52
- return response
53
- .get("headers")
54
- .map((value, name) => [
55
- name,
56
- `{ schema: ${new SchemaTypeCoder(value.get("schema") ?? value, this.version).write(script)}}`,
57
- ]);
46
+ contentType(script, response) {
47
+ return response.has("content") || response.has("schema")
48
+ ? typeLiteral(this.buildContentObjectType(script, response).map(([name, type]) => typeProperty(name, type)), true)
49
+ : neverType();
58
50
  }
59
- printHeaders(script, response) {
51
+ headersType(script, response) {
60
52
  if (!response.has("headers")) {
61
- return "never";
53
+ return neverType();
62
54
  }
63
- return printObject(this.buildHeaders(script, response));
55
+ return typeLiteral(response
56
+ .get("headers")
57
+ .map((value, name) => typeProperty(name, typeLiteral([
58
+ typeProperty("schema", new SchemaTypeCoder(value.get("schema") ?? value, this.version).write(script)),
59
+ ]))), true);
64
60
  }
65
- printRequiredHeaders(response) {
66
- const requiredHeaders = (response.get("headers")?.map((value, name) => ({
61
+ requiredHeadersType(response) {
62
+ const headers = response.get("headers")?.map((value, name) => ({
67
63
  name,
68
64
  required: value.data.required,
69
- })) ?? [])
65
+ })) ?? [];
66
+ return unionType(headers
70
67
  .filter(({ required }) => required)
71
- .map(({ name }) => `"${name}"`);
72
- return requiredHeaders.length === 0 ? "never" : requiredHeaders.join(" | ");
68
+ .map(({ name }) => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(name))));
73
69
  }
74
70
  buildExamplesObjectType(response) {
75
- if (!response.has("content")) {
76
- return "{}";
77
- }
78
- const exampleNames = [];
79
- response.get("content").forEach((content) => {
80
- if (content.has("examples")) {
81
- content.get("examples").forEach((_, name) => {
82
- if (!exampleNames.includes(name)) {
83
- exampleNames.push(name);
84
- }
85
- });
86
- }
71
+ const names = new Set();
72
+ response.get("content")?.forEach((content) => {
73
+ content.get("examples")?.forEach((_, name) => names.add(name));
87
74
  });
88
- if (exampleNames.length === 0) {
89
- return "{}";
90
- }
91
- return printObject(exampleNames.map((name) => [name, "unknown"]));
75
+ return typeLiteral([...names].map((name) => typeProperty(name, unknownType())), names.size > 0);
92
76
  }
93
77
  modulePath() {
94
78
  return pathJoin("types", this.version, this.requirement.refUrl + ".ts");
95
79
  }
96
80
  writeCode(script) {
97
- return `{
98
- headers: ${this.printHeaders(script, this.requirement)};
99
- requiredHeaders: ${this.printRequiredHeaders(this.requirement)};
100
- content: ${this.printContentObjectType(script, this.requirement)};
101
- examples: ${this.buildExamplesObjectType(this.requirement)};
102
- }`;
81
+ return typeLiteral([
82
+ typeProperty("headers", this.headersType(script, this.requirement)),
83
+ typeProperty("requiredHeaders", this.requiredHeadersType(this.requirement)),
84
+ typeProperty("content", this.contentType(script, this.requirement)),
85
+ typeProperty("examples", this.buildExamplesObjectType(this.requirement)),
86
+ ], true);
103
87
  }
104
88
  }
@@ -1,11 +1,11 @@
1
+ import ts from "typescript";
1
2
  import { TypeCoder } from "./type-coder.js";
2
3
  import type { Requirement } from "./requirement.js";
3
4
  import type { Script } from "./script.js";
4
5
  export declare class ResponsesTypeCoder extends TypeCoder {
5
6
  openApi2MediaTypes: string[];
6
7
  constructor(requirement: Requirement, version?: string, openApi2MediaTypes?: string[]);
7
- typeForDefaultStatusCode(listedStatusCodes: string[]): string;
8
- normalizeStatusCode(statusCode: string): string;
9
- buildResponseObjectType(script: Script): string;
10
- writeCode(script: Script): string;
8
+ typeForDefaultStatusCode(listedStatusCodes: string[]): ts.TypeNode;
9
+ buildResponseObjectType(script: Script): ts.TypeNode;
10
+ writeCode(script: Script): ts.TypeNode;
11
11
  }