@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.
- package/CHANGELOG.md +15 -0
- package/dist/ast.d.ts +23 -0
- package/dist/ast.js +142 -0
- package/dist/coder.d.ts +16 -22
- package/dist/coder.js +15 -17
- package/dist/operation-coder.d.ts +4 -2
- package/dist/operation-coder.js +37 -24
- package/dist/operation-type-coder.d.ts +15 -20
- package/dist/operation-type-coder.js +111 -103
- package/dist/parameter-export-type-coder.d.ts +4 -3
- package/dist/parameters-type-coder.d.ts +2 -1
- package/dist/parameters-type-coder.js +7 -18
- package/dist/repository.d.ts +3 -10
- package/dist/repository.js +244 -95
- package/dist/response-type-coder.d.ts +7 -7
- package/dist/response-type-coder.js +37 -53
- package/dist/responses-type-coder.d.ts +4 -4
- package/dist/responses-type-coder.js +39 -26
- package/dist/scenario-file-generator.js +137 -134
- package/dist/schema-coder.d.ts +6 -4
- package/dist/schema-coder.js +31 -22
- package/dist/schema-type-coder.d.ts +9 -8
- package/dist/schema-type-coder.js +66 -62
- package/dist/script.d.ts +18 -95
- package/dist/script.js +137 -212
- package/dist/type-coder.d.ts +3 -1
- package/dist/type-coder.js +5 -1
- package/dist/versions-ts-generator.d.ts +0 -9
- package/dist/versions-ts-generator.js +46 -77
- package/package.json +4 -3
- package/src/README.md +23 -2
- package/dist/context-file-token.d.ts +0 -1
- package/dist/context-file-token.js +0 -1
- package/dist/printers.d.ts +0 -2
- package/dist/printers.js +0 -10
package/dist/repository.js
CHANGED
|
@@ -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,
|
|
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
|
|
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
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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
|
-
*
|
|
177
|
-
*
|
|
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,
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
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
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
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
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
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
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
if (
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
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
|
-
|
|
248
|
-
|
|
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
|
-
|
|
252
|
-
if (
|
|
253
|
-
const
|
|
254
|
-
|
|
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
|
-
|
|
257
|
-
|
|
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,
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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):
|
|
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 =
|
|
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
|
-
:
|
|
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
|
-
|
|
42
|
-
|
|
41
|
+
typeLiteral([
|
|
42
|
+
typeProperty("schema", new SchemaTypeCoder(response.get("schema"), this.version).write(script)),
|
|
43
|
+
], true),
|
|
43
44
|
]);
|
|
44
45
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
-
|
|
51
|
+
headersType(script, response) {
|
|
60
52
|
if (!response.has("headers")) {
|
|
61
|
-
return
|
|
53
|
+
return neverType();
|
|
62
54
|
}
|
|
63
|
-
return
|
|
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
|
-
|
|
66
|
-
const
|
|
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 }) =>
|
|
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
|
-
|
|
76
|
-
|
|
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
|
-
|
|
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
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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[]):
|
|
8
|
-
|
|
9
|
-
|
|
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
|
}
|