@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.
- package/CHANGELOG.md +40 -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 +5 -3
- package/dist/operation-coder.js +40 -25
- package/dist/operation-type-coder.d.ts +17 -25
- package/dist/operation-type-coder.js +115 -129
- package/dist/operation-type-name-mapping.d.ts +3 -2
- package/dist/operation-type-name-mapping.js +22 -10
- 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/sanitize-identifier.d.ts +1 -0
- package/dist/sanitize-identifier.js +17 -0
- 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-required-properties.d.ts +3 -0
- package/dist/schema-required-properties.js +47 -0
- package/dist/schema-type-coder.d.ts +10 -8
- package/dist/schema-type-coder.js +157 -64
- package/dist/script.d.ts +18 -95
- package/dist/script.js +137 -212
- package/dist/templates/counterfact-types/middleware.ts +15 -2
- package/dist/templates/counterfact-types/response-builder-factory.ts +102 -6
- package/dist/templates/counterfact-types/response-builder.ts +1 -0
- package/dist/templates/counterfact-types/wide-operation-argument.ts +13 -1
- 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 +5 -4
- 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
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { typeLiteral, typeReference, unionType } from "./ast.js";
|
|
3
3
|
import { TypeCoder } from "./type-coder.js";
|
|
4
|
+
import { ResponseTypeCoder } from "./response-type-coder.js";
|
|
5
|
+
function statusName(status) {
|
|
6
|
+
return /^\d+$/u.test(status)
|
|
7
|
+
? ts.factory.createNumericLiteral(status)
|
|
8
|
+
: ts.factory.createStringLiteral(status);
|
|
9
|
+
}
|
|
10
|
+
function statusLiteral(status) {
|
|
11
|
+
return ts.factory.createLiteralTypeNode(statusName(status));
|
|
12
|
+
}
|
|
4
13
|
export class ResponsesTypeCoder extends TypeCoder {
|
|
5
14
|
openApi2MediaTypes;
|
|
6
15
|
constructor(requirement, version = "", openApi2MediaTypes = []) {
|
|
@@ -8,36 +17,40 @@ export class ResponsesTypeCoder extends TypeCoder {
|
|
|
8
17
|
this.openApi2MediaTypes = openApi2MediaTypes;
|
|
9
18
|
}
|
|
10
19
|
typeForDefaultStatusCode(listedStatusCodes) {
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
return this.typeForDefaultStatusCode(Object.keys(this.requirement.data));
|
|
20
|
-
}
|
|
21
|
-
return statusCode;
|
|
20
|
+
const defined = listedStatusCodes.filter((key) => key !== "default");
|
|
21
|
+
const status = typeReference("HttpStatusCode");
|
|
22
|
+
return defined.length === 0
|
|
23
|
+
? status
|
|
24
|
+
: typeReference("Exclude", [
|
|
25
|
+
status,
|
|
26
|
+
unionType(defined.map(statusLiteral)),
|
|
27
|
+
]);
|
|
22
28
|
}
|
|
23
29
|
buildResponseObjectType(script) {
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
30
|
+
const members = [];
|
|
31
|
+
let fallback;
|
|
32
|
+
this.requirement.forEach((response, code) => {
|
|
33
|
+
const type = new ResponseTypeCoder(response, this.version, this.openApi2MediaTypes).write(script);
|
|
34
|
+
if (code === "default") {
|
|
35
|
+
fallback = ts.factory.createMappedTypeNode(undefined, ts.factory.createTypeParameterDeclaration(undefined, "statusCode", this.typeForDefaultStatusCode(Object.keys(this.requirement.data))), undefined, undefined, type, undefined);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
members.push(ts.factory.createPropertySignature(undefined, statusName(code), undefined, type));
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
const explicit = typeLiteral(members, true);
|
|
42
|
+
return fallback
|
|
43
|
+
? members.length > 0
|
|
44
|
+
? ts.factory.createIntersectionTypeNode([explicit, fallback])
|
|
45
|
+
: fallback
|
|
46
|
+
: explicit;
|
|
34
47
|
}
|
|
35
48
|
writeCode(script) {
|
|
36
49
|
script.importSharedType("ResponseBuilderFactory");
|
|
37
|
-
const
|
|
38
|
-
if (
|
|
50
|
+
const type = this.buildResponseObjectType(script);
|
|
51
|
+
if (this.requirement.has("default")) {
|
|
39
52
|
script.importSharedType("HttpStatusCode");
|
|
40
53
|
}
|
|
41
|
-
return
|
|
54
|
+
return typeReference("ResponseBuilderFactory", [type]);
|
|
42
55
|
}
|
|
43
56
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function sanitizeIdentifier(value: string): string;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { RESERVED_WORDS } from "./reserved-words.js";
|
|
2
|
+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words
|
|
3
|
+
export function sanitizeIdentifier(value) {
|
|
4
|
+
// Treat any run of non-identifier characters as a camelCase separator
|
|
5
|
+
let result = value.replaceAll(/[^\w$]+(?<next>.)/gu, (_, char) => char.toUpperCase());
|
|
6
|
+
// Strip any trailing non-identifier characters (no following char to capitalize)
|
|
7
|
+
result = result.replaceAll(/[^\w$]/gu, "");
|
|
8
|
+
// If the identifier starts with a digit, prefix with an underscore
|
|
9
|
+
if (/^\d/u.test(result)) {
|
|
10
|
+
result = `_${result}`;
|
|
11
|
+
}
|
|
12
|
+
// If the identifier is a reserved word, append an underscore
|
|
13
|
+
if (RESERVED_WORDS.has(result)) {
|
|
14
|
+
result = `${result}_`;
|
|
15
|
+
}
|
|
16
|
+
return result || "_";
|
|
17
|
+
}
|
|
@@ -3,6 +3,8 @@ import fs from "node:fs/promises";
|
|
|
3
3
|
import nodePath from "node:path";
|
|
4
4
|
/* eslint-disable security/detect-non-literal-fs-filename -- scenario files are discovered and generated under the configured destination tree. */
|
|
5
5
|
import { watch } from "chokidar";
|
|
6
|
+
import ts from "typescript";
|
|
7
|
+
import { exportedConst, formatStatements, functionType, importDeclaration, literalType, parameter, readonlyProperty, stringType, typeAlias, typeReference, unionType, unknownType, valueExpression, withJsDoc, } from "./ast.js";
|
|
6
8
|
import { pathRelative } from "./forward-slash-path.js";
|
|
7
9
|
import { waitForEvent } from "./wait-for-event.js";
|
|
8
10
|
import { CHOKIDAR_OPTIONS } from "./watch-options.js";
|
|
@@ -15,6 +17,18 @@ async function collectContextFiles(destination) {
|
|
|
15
17
|
}
|
|
16
18
|
await walkForContextFiles(routesDir, routesDir, results);
|
|
17
19
|
results.sort((a, b) => b.depth - a.depth);
|
|
20
|
+
const names = new Set();
|
|
21
|
+
for (const context of results) {
|
|
22
|
+
const base = /^\d/u.test(context.alias)
|
|
23
|
+
? "_" + context.alias
|
|
24
|
+
: context.alias;
|
|
25
|
+
let name = base;
|
|
26
|
+
let suffix = 2;
|
|
27
|
+
while (names.has(name))
|
|
28
|
+
name = base + suffix++;
|
|
29
|
+
context.alias = name;
|
|
30
|
+
names.add(name);
|
|
31
|
+
}
|
|
18
32
|
return results;
|
|
19
33
|
}
|
|
20
34
|
async function walkForContextFiles(routesDir, currentDir, results) {
|
|
@@ -84,90 +98,94 @@ function routePathToAlias(routePath) {
|
|
|
84
98
|
.join("") + "Context");
|
|
85
99
|
}
|
|
86
100
|
const PARAM_SEGMENT_REGEX = /^\{.+\}$/u;
|
|
87
|
-
function
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
101
|
+
function pathTemplate(parts) {
|
|
102
|
+
const fragments = [""];
|
|
103
|
+
const placeholders = [];
|
|
104
|
+
for (const part of parts) {
|
|
105
|
+
fragments[fragments.length - 1] += "/";
|
|
106
|
+
if (PARAM_SEGMENT_REGEX.test(part)) {
|
|
107
|
+
placeholders.push(stringType());
|
|
108
|
+
fragments.push("");
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
fragments[fragments.length - 1] += part;
|
|
112
|
+
}
|
|
95
113
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
.
|
|
99
|
-
return ` loadContext(path: \`${templatePath}\`): ${alias};`;
|
|
114
|
+
return ts.factory.createTemplateLiteralType(ts.factory.createTemplateHead(fragments[0]), placeholders.map((type, index) => ts.factory.createTemplateLiteralTypeSpan(type, index === placeholders.length - 1
|
|
115
|
+
? ts.factory.createTemplateTail(fragments[index + 1])
|
|
116
|
+
: ts.factory.createTemplateMiddle(fragments[index + 1]))));
|
|
100
117
|
}
|
|
101
|
-
function
|
|
102
|
-
const
|
|
103
|
-
const
|
|
104
|
-
?
|
|
105
|
-
:
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
if (storeImportPath !== undefined) {
|
|
110
|
-
importLines.push(`import type { Store } from "${storeImportPath}";`);
|
|
111
|
-
}
|
|
112
|
-
const overloadLines = contextFiles.map(({ alias, routePath }) => buildLoadContextOverload(routePath, alias));
|
|
113
|
-
const parts = [
|
|
114
|
-
GENERATED_FILE_COMMENT,
|
|
115
|
-
...importLines,
|
|
116
|
-
"",
|
|
117
|
-
"interface LoadContextDefinitions {",
|
|
118
|
-
" /* code generator adds additional signatures here */",
|
|
119
|
-
...overloadLines,
|
|
120
|
-
" loadContext(path: string): Record<string, unknown>;",
|
|
121
|
-
"}",
|
|
122
|
-
"",
|
|
123
|
-
"export interface Scenario$ {",
|
|
124
|
-
' /** Root context, same as loadContext("/") */',
|
|
125
|
-
` readonly context: ${contextType};`,
|
|
126
|
-
' readonly loadContext: LoadContextDefinitions["loadContext"];',
|
|
127
|
-
" /** Named route builders stored in the REPL execution context */",
|
|
128
|
-
" readonly routes: Record<string, unknown>;",
|
|
129
|
-
" /** Create a new route builder for a given path */",
|
|
130
|
-
" readonly route: (path: string) => unknown;",
|
|
131
|
-
"}",
|
|
132
|
-
"",
|
|
133
|
-
"/** A scenario function that receives the live REPL environment */",
|
|
134
|
-
"export type Scenario = ($: Scenario$) => Promise<void> | void;",
|
|
135
|
-
"",
|
|
136
|
-
"/** Interface for Context objects defined in _.context.ts files */",
|
|
137
|
-
"export interface Context$ {",
|
|
138
|
-
...(storeImportPath === undefined
|
|
139
|
-
? []
|
|
140
|
-
: [
|
|
141
|
-
" /** Application-level store shared by every API group */",
|
|
142
|
-
" readonly store: Store;",
|
|
118
|
+
function buildLoadContextOverload(routePath, alias) {
|
|
119
|
+
const segments = routePath.split("/").filter(Boolean);
|
|
120
|
+
const path = segments.some((segment) => PARAM_SEGMENT_REGEX.test(segment))
|
|
121
|
+
? pathTemplate(segments)
|
|
122
|
+
: unionType([
|
|
123
|
+
literalType(routePath),
|
|
124
|
+
ts.factory.createTemplateLiteralType(ts.factory.createTemplateHead(routePath === "/" ? "/" : routePath + "/"), [
|
|
125
|
+
ts.factory.createTemplateLiteralTypeSpan(stringType(), ts.factory.createTemplateTail("")),
|
|
143
126
|
]),
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
return
|
|
127
|
+
]);
|
|
128
|
+
return ts.factory.createMethodSignature(undefined, "loadContext", undefined, undefined, [parameter("path", path)], typeReference(alias));
|
|
129
|
+
}
|
|
130
|
+
function recordType() {
|
|
131
|
+
return typeReference("Record", [stringType(), unknownType()]);
|
|
132
|
+
}
|
|
133
|
+
function interfaceDeclaration(name, members, exported) {
|
|
134
|
+
return ts.factory.createInterfaceDeclaration(exported
|
|
135
|
+
? [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)]
|
|
136
|
+
: undefined, name, undefined, undefined, members);
|
|
137
|
+
}
|
|
138
|
+
async function buildScenarioContextContent(contextFiles, storeImportPath) {
|
|
139
|
+
const rootContext = contextFiles.find((file) => file.routePath === "/");
|
|
140
|
+
const imports = contextFiles.map(({ importPath, alias }) => importDeclaration(alias, importPath, true, false, "Context"));
|
|
141
|
+
if (storeImportPath !== undefined)
|
|
142
|
+
imports.push(importDeclaration("Store", storeImportPath, true));
|
|
143
|
+
const loadContext = () => ts.factory.createIndexedAccessTypeNode(typeReference("LoadContextDefinitions"), literalType("loadContext"));
|
|
144
|
+
const voidType = () => ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword);
|
|
145
|
+
const overloads = contextFiles.map(({ alias, routePath }) => buildLoadContextOverload(routePath, alias));
|
|
146
|
+
const fallback = ts.factory.createMethodSignature(undefined, "loadContext", undefined, undefined, [parameter("path", stringType())], recordType());
|
|
147
|
+
return formatStatements([
|
|
148
|
+
...imports,
|
|
149
|
+
interfaceDeclaration("LoadContextDefinitions", [...overloads, fallback], false),
|
|
150
|
+
interfaceDeclaration("Scenario$", [
|
|
151
|
+
readonlyProperty("context", rootContext ? typeReference(rootContext.alias) : recordType(), 'Root context, same as loadContext("/")'),
|
|
152
|
+
readonlyProperty("loadContext", loadContext(), "Load a context object for a specific path"),
|
|
153
|
+
readonlyProperty("routes", recordType(), "Named route builders stored in the REPL execution context"),
|
|
154
|
+
readonlyProperty("route", functionType([parameter("path", stringType())], unknownType()), "Create a new route builder for a given path"),
|
|
155
|
+
], true),
|
|
156
|
+
withJsDoc(typeAlias("Scenario", functionType([parameter("$", typeReference("Scenario$"))], unionType([typeReference("Promise", [voidType()]), voidType()]))), {
|
|
157
|
+
description: "A scenario function that receives the live REPL environment",
|
|
158
|
+
}),
|
|
159
|
+
withJsDoc(interfaceDeclaration("Context$", [
|
|
160
|
+
...(storeImportPath === undefined
|
|
161
|
+
? []
|
|
162
|
+
: [
|
|
163
|
+
readonlyProperty("store", typeReference("Store"), "Application-level store shared by every API group"),
|
|
164
|
+
]),
|
|
165
|
+
readonlyProperty("loadContext", loadContext(), "Load a context object for a specific path"),
|
|
166
|
+
readonlyProperty("readJson", functionType([parameter("relativePath", stringType())], typeReference("Promise", [unknownType()])), "Load a JSON file relative to this file's path"),
|
|
167
|
+
], true), {
|
|
168
|
+
description: "Interface for Context objects defined in _.context.ts files",
|
|
169
|
+
}),
|
|
170
|
+
], [GENERATED_FILE_COMMENT.slice(3)]);
|
|
152
171
|
}
|
|
153
172
|
function ensureRelativeImportPath(path) {
|
|
154
|
-
return path.startsWith(".") ? path :
|
|
173
|
+
return path.startsWith(".") ? path : "./" + path;
|
|
155
174
|
}
|
|
156
|
-
function buildMiddlewareTypeContent(destination, routeDirectory) {
|
|
157
|
-
const
|
|
158
|
-
const
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
`import type { Middleware as MiddlewareFunction } from "${sharedTypePath}";`,
|
|
175
|
+
async function buildMiddlewareTypeContent(destination, routeDirectory) {
|
|
176
|
+
const directory = nodePath.join(destination, "types", routeDirectory.relativePath);
|
|
177
|
+
const sharedPath = ensureRelativeImportPath(pathRelative(directory, nodePath.join(destination, "counterfact-types", "index.js")));
|
|
178
|
+
const statements = [
|
|
179
|
+
importDeclaration("MiddlewareFunction", sharedPath, true, false, "Middleware"),
|
|
162
180
|
];
|
|
163
|
-
|
|
164
|
-
|
|
181
|
+
const arguments_ = [];
|
|
182
|
+
if (routeDirectory.contextFile !== undefined) {
|
|
183
|
+
const contextPath = ensureRelativeImportPath(pathRelative(directory, routeDirectory.contextFile).replace(/\.ts$/u, ".js"));
|
|
184
|
+
statements.push(importDeclaration("Context", contextPath, true));
|
|
185
|
+
arguments_.push(typeReference("Context"));
|
|
165
186
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
lines.push(`import type { Context } from "${contextImportPath}";`, "", "export type Middleware = MiddlewareFunction<Context>;");
|
|
169
|
-
}
|
|
170
|
-
return `${lines.join("\n")}\n`;
|
|
187
|
+
statements.push(typeAlias("Middleware", typeReference("MiddlewareFunction", arguments_)));
|
|
188
|
+
return formatStatements(statements, [GENERATED_FILE_COMMENT.slice(3)]);
|
|
171
189
|
}
|
|
172
190
|
async function collectGeneratedMiddlewareTypeFiles(directory) {
|
|
173
191
|
let entries;
|
|
@@ -199,7 +217,7 @@ async function writeMiddlewareTypes(destination) {
|
|
|
199
217
|
const filePath = nodePath.join(destination, "types", routeDirectory.relativePath, "_.middleware.ts");
|
|
200
218
|
expectedFiles.add(nodePath.resolve(filePath));
|
|
201
219
|
await fs.mkdir(nodePath.dirname(filePath), { recursive: true });
|
|
202
|
-
await fs.writeFile(filePath, buildMiddlewareTypeContent(destination, routeDirectory), "utf8");
|
|
220
|
+
await fs.writeFile(filePath, await buildMiddlewareTypeContent(destination, routeDirectory), "utf8");
|
|
203
221
|
}
|
|
204
222
|
const generatedFiles = await collectGeneratedMiddlewareTypeFiles(nodePath.join(destination, "types"));
|
|
205
223
|
await Promise.all(generatedFiles
|
|
@@ -226,65 +244,50 @@ async function writeScenarioContextType(destination, rootDestination) {
|
|
|
226
244
|
const storeImportPath = existsSync(storePath)
|
|
227
245
|
? `${relativeStorePath.startsWith(".") ? "" : "./"}${relativeStorePath.replace(/\.ts$/u, ".js")}`
|
|
228
246
|
: undefined;
|
|
229
|
-
const content = buildScenarioContextContent(contextFiles, storeImportPath);
|
|
247
|
+
const content = await buildScenarioContextContent(contextFiles, storeImportPath);
|
|
230
248
|
await fs.mkdir(typesDir, { recursive: true });
|
|
231
249
|
await fs.writeFile(filePath, content, "utf8");
|
|
232
250
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
console.log(
|
|
275
|
-
[
|
|
276
|
-
"Scenarios are functions that populate the context object",
|
|
277
|
-
"and / or the REPL environment. They are intended to",
|
|
278
|
-
"populate your environment with specific data and",
|
|
279
|
-
"configurations for testing purposes.",
|
|
280
|
-
].join("\\n"),
|
|
281
|
-
);
|
|
282
|
-
|
|
283
|
-
console.log(
|
|
284
|
-
"\\nScenarios (including this one) are defined in the ./scenarios directory.",
|
|
285
|
-
);
|
|
286
|
-
};
|
|
287
|
-
`;
|
|
251
|
+
async function defaultScenariosContent() {
|
|
252
|
+
const arrow = (statements) => ts.factory.createArrowFunction(undefined, undefined, [parameter("$")], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock(statements, true));
|
|
253
|
+
const ignoreArgument = () => ts.factory.createExpressionStatement(ts.factory.createVoidExpression(ts.factory.createIdentifier("$")));
|
|
254
|
+
const log = (expression) => ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("console"), "log"), undefined, [expression]));
|
|
255
|
+
const lines = valueExpression([
|
|
256
|
+
"Scenarios are functions that populate the context object",
|
|
257
|
+
"and / or the REPL environment. They are intended to",
|
|
258
|
+
"populate your environment with specific data and",
|
|
259
|
+
"configurations for testing purposes.",
|
|
260
|
+
]);
|
|
261
|
+
const joinedLines = ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(lines, "join"), undefined, [valueExpression("\n")]);
|
|
262
|
+
return formatStatements([
|
|
263
|
+
importDeclaration("Scenario", "../types/_.context.js", true),
|
|
264
|
+
withJsDoc(exportedConst("startup", arrow([ignoreArgument()]), typeReference("Scenario")), {
|
|
265
|
+
description: "Scenario scripts are plain TypeScript functions that receive the live REPL\n" +
|
|
266
|
+
"environment and can read or mutate server state. Run them from the REPL with:\n" +
|
|
267
|
+
" .scenario <functionName>\n\n" +
|
|
268
|
+
"Read or mutate the root context (same object routes see as $.context):\n" +
|
|
269
|
+
" $.context.<property> = <value>;\n\n" +
|
|
270
|
+
"Load a context for a specific path:\n" +
|
|
271
|
+
' const petsCtx = $.loadContext("/pets");\n\n' +
|
|
272
|
+
"Store a pre-configured route builder for later use in the REPL:\n" +
|
|
273
|
+
' $.routes.myRequest = $.route("/pets").method("get");\n\n' +
|
|
274
|
+
"startup() runs automatically when the server initializes, right before the\n" +
|
|
275
|
+
"REPL starts. Use it to seed dummy data so the server is ready to use\n" +
|
|
276
|
+
"immediately. It receives the same $ argument as all other scenario functions.\n\n" +
|
|
277
|
+
"Tip: delegate to other scenario functions and pass $ along so each function\n" +
|
|
278
|
+
"stays focused on a single concern. You can also pass additional arguments to\n" +
|
|
279
|
+
'configure them, e.g. addPets($, 20, "dog").\n\n' +
|
|
280
|
+
"If you don't need a startup scenario, delete this function or leave it empty.",
|
|
281
|
+
}),
|
|
282
|
+
withJsDoc(exportedConst("help", arrow([
|
|
283
|
+
ignoreArgument(),
|
|
284
|
+
log(joinedLines),
|
|
285
|
+
log(valueExpression("\nScenarios (including this one) are defined in the ./scenarios directory.")),
|
|
286
|
+
]), typeReference("Scenario")), {
|
|
287
|
+
description: "An example scenario. To use it in the REPL, type:\n .scenario help",
|
|
288
|
+
}),
|
|
289
|
+
]);
|
|
290
|
+
}
|
|
288
291
|
async function writeDefaultScenariosIndex(destination) {
|
|
289
292
|
const scenariosDir = nodePath.join(destination, "scenarios");
|
|
290
293
|
const filePath = nodePath.join(scenariosDir, "index.ts");
|
|
@@ -292,7 +295,7 @@ async function writeDefaultScenariosIndex(destination) {
|
|
|
292
295
|
return;
|
|
293
296
|
}
|
|
294
297
|
await fs.mkdir(scenariosDir, { recursive: true });
|
|
295
|
-
await fs.writeFile(filePath,
|
|
298
|
+
await fs.writeFile(filePath, await defaultScenariosContent(), "utf8");
|
|
296
299
|
}
|
|
297
300
|
/**
|
|
298
301
|
* Encapsulates the generation of scenario-related files:
|
package/dist/schema-coder.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
1
2
|
import { Coder } from "./coder.js";
|
|
2
3
|
import type { Script } from "./script.js";
|
|
3
4
|
export declare class SchemaCoder extends Coder {
|
|
4
5
|
names(): Generator<string>;
|
|
5
|
-
objectSchema(script: Script):
|
|
6
|
-
arraySchema(script: Script):
|
|
7
|
-
typeDeclaration(_namespace: Map<string, unknown> | undefined, script: Script):
|
|
6
|
+
objectSchema(script: Script): ts.Expression;
|
|
7
|
+
arraySchema(script: Script): ts.Expression;
|
|
8
|
+
typeDeclaration(_namespace: Map<string, unknown> | undefined, script: Script): ts.TypeNode;
|
|
8
9
|
modulePath(): string;
|
|
9
|
-
|
|
10
|
+
write(script: Script): ts.Expression;
|
|
11
|
+
writeCode(script: Script): ts.Expression;
|
|
10
12
|
}
|
package/dist/schema-coder.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { objectExpression, typeReference, valueExpression } from "./ast.js";
|
|
1
3
|
import { Coder } from "./coder.js";
|
|
2
4
|
function scrubSchema(schema) {
|
|
3
|
-
// remove properties that are not valid in JSON Schema 6 and not useful anyway
|
|
4
5
|
const cleaned = { ...schema };
|
|
5
6
|
delete cleaned["example"];
|
|
6
7
|
delete cleaned["xml"];
|
|
@@ -12,38 +13,46 @@ export class SchemaCoder extends Coder {
|
|
|
12
13
|
}
|
|
13
14
|
objectSchema(script) {
|
|
14
15
|
const { properties, required } = this.requirement.data;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
16
|
+
return objectExpression([
|
|
17
|
+
["type", valueExpression("object")],
|
|
18
|
+
["required", valueExpression(required ?? [])],
|
|
19
|
+
[
|
|
20
|
+
"properties",
|
|
21
|
+
objectExpression(Object.keys(properties ?? {}).map((name) => [
|
|
22
|
+
name,
|
|
23
|
+
new SchemaCoder(this.requirement.get("properties").get(name), this.version).write(script),
|
|
24
|
+
])),
|
|
25
|
+
],
|
|
26
|
+
], true);
|
|
26
27
|
}
|
|
27
28
|
arraySchema(script) {
|
|
28
|
-
return
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
29
|
+
return objectExpression([
|
|
30
|
+
["type", valueExpression("array")],
|
|
31
|
+
[
|
|
32
|
+
"items",
|
|
33
|
+
new SchemaCoder(this.requirement.get("items"), this.version).write(script),
|
|
34
|
+
],
|
|
35
|
+
], true);
|
|
32
36
|
}
|
|
33
37
|
typeDeclaration(_namespace, script) {
|
|
34
|
-
return script.importExternalType("JSONSchema6", "json-schema");
|
|
38
|
+
return typeReference(script.importExternalType("JSONSchema6", "json-schema"));
|
|
35
39
|
}
|
|
36
40
|
modulePath() {
|
|
37
41
|
return `types/${this.requirement.refUrl}.ts`;
|
|
38
42
|
}
|
|
43
|
+
write(script) {
|
|
44
|
+
if (this.requirement.isReference) {
|
|
45
|
+
// Runtime schemas refer to value exports, rather than type imports.
|
|
46
|
+
return ts.factory.createIdentifier(script.import(this));
|
|
47
|
+
}
|
|
48
|
+
return this.writeCode(script);
|
|
49
|
+
}
|
|
39
50
|
writeCode(script) {
|
|
40
51
|
const { type } = this.requirement.data;
|
|
41
|
-
if (type === "object")
|
|
52
|
+
if (type === "object")
|
|
42
53
|
return this.objectSchema(script);
|
|
43
|
-
|
|
44
|
-
if (type === "array") {
|
|
54
|
+
if (type === "array")
|
|
45
55
|
return this.arraySchema(script);
|
|
46
|
-
|
|
47
|
-
return JSON.stringify(scrubSchema(this.requirement.data));
|
|
56
|
+
return valueExpression(scrubSchema(this.requirement.data));
|
|
48
57
|
}
|
|
49
58
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { typeLiteral, typeProperty, typeReference, unionType, unknownType, neverType, } from "./ast.js";
|
|
3
|
+
/** Apply a containing schema's required list without changing shared referenced models. */
|
|
4
|
+
export function requireProperties(type, names) {
|
|
5
|
+
if (ts.isParenthesizedTypeNode(type)) {
|
|
6
|
+
return ts.factory.createParenthesizedType(requireProperties(type.type, names));
|
|
7
|
+
}
|
|
8
|
+
if (ts.isUnionTypeNode(type)) {
|
|
9
|
+
return unionType(type.types.map((branch) => requireProperties(branch, names)));
|
|
10
|
+
}
|
|
11
|
+
if (ts.isIntersectionTypeNode(type)) {
|
|
12
|
+
return ts.factory.createIntersectionTypeNode(type.types.map((part) => requireProperties(part, names)));
|
|
13
|
+
}
|
|
14
|
+
if (ts.isTypeLiteralNode(type)) {
|
|
15
|
+
const present = new Set();
|
|
16
|
+
const members = type.members.map((member) => {
|
|
17
|
+
if (!ts.isPropertySignature(member) ||
|
|
18
|
+
!member.name ||
|
|
19
|
+
ts.isComputedPropertyName(member.name))
|
|
20
|
+
return member;
|
|
21
|
+
const name = member.name.text;
|
|
22
|
+
present.add(name);
|
|
23
|
+
return names.includes(name)
|
|
24
|
+
? ts.factory.updatePropertySignature(member, member.modifiers, member.name, undefined, member.type)
|
|
25
|
+
: member;
|
|
26
|
+
});
|
|
27
|
+
for (const name of names) {
|
|
28
|
+
if (!present.has(name))
|
|
29
|
+
members.push(typeProperty(name, unknownType()));
|
|
30
|
+
}
|
|
31
|
+
return typeLiteral(members);
|
|
32
|
+
}
|
|
33
|
+
if (type.kind !== ts.SyntaxKind.TypeReference)
|
|
34
|
+
return type;
|
|
35
|
+
// Distribute over referenced unions. A mapped type preserves each property's
|
|
36
|
+
// original type while removing optionality only for the requested keys.
|
|
37
|
+
const schema = typeReference("RequiredSchema");
|
|
38
|
+
const key = typeReference("RequiredKey");
|
|
39
|
+
const keys = unionType(names.map((name) => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(name))));
|
|
40
|
+
const selected = ts.factory.createMappedTypeNode(undefined, ts.factory.createTypeParameterDeclaration(undefined, "RequiredKey", ts.factory.createTypeOperatorNode(ts.SyntaxKind.KeyOfKeyword, schema)), ts.factory.createConditionalTypeNode(key, keys, key, neverType()), ts.factory.createToken(ts.SyntaxKind.MinusToken), ts.factory.createIndexedAccessTypeNode(schema, key), undefined);
|
|
41
|
+
const enforced = ts.factory.createIntersectionTypeNode([
|
|
42
|
+
schema,
|
|
43
|
+
selected,
|
|
44
|
+
typeLiteral(names.map((name) => typeProperty(name, unknownType()))),
|
|
45
|
+
]);
|
|
46
|
+
return ts.factory.createConditionalTypeNode(type, ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(undefined, "RequiredSchema")), ts.factory.createConditionalTypeNode(schema, ts.factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword), enforced, schema), neverType());
|
|
47
|
+
}
|
|
@@ -1,20 +1,22 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
1
2
|
import { TypeCoder } from "./type-coder.js";
|
|
2
3
|
import { Requirement } from "./requirement.js";
|
|
3
4
|
import type { Script } from "./script.js";
|
|
4
5
|
export declare class SchemaTypeCoder extends TypeCoder {
|
|
5
6
|
names(): Generator<string>;
|
|
6
7
|
jsdoc(): string;
|
|
7
|
-
additionalPropertiesType(script: Script):
|
|
8
|
-
objectSchema(script: Script):
|
|
9
|
-
arraySchema(script: Script):
|
|
10
|
-
writePrimitive(value: unknown):
|
|
11
|
-
writeType(script: Script, type: unknown):
|
|
8
|
+
additionalPropertiesType(script: Script): ts.TypeNode;
|
|
9
|
+
objectSchema(script: Script): ts.TypeNode;
|
|
10
|
+
arraySchema(script: Script): ts.TypeNode;
|
|
11
|
+
writePrimitive(value: unknown): ts.TypeNode;
|
|
12
|
+
writeType(script: Script, type: unknown): ts.TypeNode;
|
|
12
13
|
writeGroup(script: Script, { allOf, anyOf, oneOf, }: {
|
|
13
14
|
allOf?: unknown[];
|
|
14
15
|
anyOf?: unknown[];
|
|
15
16
|
oneOf?: unknown[];
|
|
16
|
-
}):
|
|
17
|
-
writeEnum(
|
|
17
|
+
}): ts.TypeNode;
|
|
18
|
+
writeEnum(requirement: Requirement): ts.TypeNode;
|
|
18
19
|
modulePath(): string;
|
|
19
|
-
writeCode(script: Script):
|
|
20
|
+
writeCode(script: Script): ts.TypeNode;
|
|
21
|
+
private writeSchema;
|
|
20
22
|
}
|