@counterfact/generator 0.1.6 → 1.1.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.
@@ -5,9 +5,10 @@ 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
7
  import ts from "typescript";
8
- import { formatStatements, importDeclaration, parameter, typeReference, withJsDoc, } from "./ast.js";
8
+ import { formatStatements, importDeclaration, parameter, typeAlias, typeReference, withJsDoc, } from "./ast.js";
9
9
  import { ensureDirectoryExists } from "./ensure-directory-exists.js";
10
10
  import { toForwardSlashPath, pathRelative, pathDirname, } from "./forward-slash-path.js";
11
+ import { writeHelperTypes } from "./scenario-file-generator.js";
11
12
  import { Script } from "./script.js";
12
13
  import { escapePathForWindows } from "./windows-escape.js";
13
14
  const debug = createDebug("counterfact:server:repository");
@@ -140,6 +141,8 @@ export class Repository {
140
141
  if (routes) {
141
142
  await this.createDefaultContextFile(destination);
142
143
  }
144
+ if (types)
145
+ await writeHelperTypes(destination, destination, true);
143
146
  }
144
147
  /**
145
148
  * Creates the default `routes/_.context.ts` file if it does not already
@@ -164,7 +167,7 @@ export class Repository {
164
167
  "See https://github.com/counterfact/api-simulator/blob/main/docs/features/state.md",
165
168
  });
166
169
  await fs.writeFile(contextFilePath, await formatStatements([
167
- importDeclaration("Context$", "../types/_.context.js", true),
170
+ importDeclaration("Context$", "../types/index.js", true),
168
171
  context,
169
172
  ]));
170
173
  }
@@ -297,8 +300,36 @@ export class Repository {
297
300
  }
298
301
  }
299
302
  const newImports = [];
303
+ const newAliases = [];
304
+ const aliases = new Map();
305
+ const typeKey = (node) => {
306
+ const keys = [];
307
+ while (ts.isIndexedAccessTypeNode(node)) {
308
+ if (!ts.isLiteralTypeNode(node.indexType) ||
309
+ !ts.isStringLiteral(node.indexType.literal))
310
+ return undefined;
311
+ keys.unshift(node.indexType.literal.text);
312
+ node = node.objectType;
313
+ }
314
+ return ts.isTypeReferenceNode(node) &&
315
+ ts.isIdentifier(node.typeName) &&
316
+ !node.typeArguments?.length
317
+ ? JSON.stringify([node.typeName.text, ...keys])
318
+ : undefined;
319
+ };
320
+ for (const statement of source.statements) {
321
+ if (ts.isTypeAliasDeclaration(statement) &&
322
+ !statement.typeParameters?.length) {
323
+ const key = typeKey(statement.type);
324
+ if (key)
325
+ aliases.set(key, statement.name.text);
326
+ }
327
+ }
300
328
  const handlers = [];
301
- const generatedImports = script.importStatements();
329
+ const generatedImports = [
330
+ ...script.importStatements(),
331
+ ...script.externalImportStatements(),
332
+ ];
302
333
  for (const statement of script.exportStatements()) {
303
334
  if (!ts.isVariableStatement(statement))
304
335
  continue;
@@ -312,12 +343,24 @@ export class Repository {
312
343
  declaration.name.text +
313
344
  ": a local binding already exists in " +
314
345
  fullPath);
315
- if (!declaration.type ||
316
- !ts.isTypeReferenceNode(declaration.type) ||
317
- !ts.isIdentifier(declaration.type.typeName)) {
346
+ let handlerType = declaration.type;
347
+ const generatedAlias = ts.isIndexedAccessTypeNode(handlerType) &&
348
+ ts.isTypeReferenceNode(handlerType.objectType) &&
349
+ ts.isIdentifier(handlerType.objectType.typeName)
350
+ ? script.localTypes.get(handlerType.objectType.typeName.text)
351
+ : undefined;
352
+ if (generatedAlias && ts.isIndexedAccessTypeNode(handlerType)) {
353
+ handlerType = ts.factory.createIndexedAccessTypeNode(generatedAlias, handlerType.indexType);
354
+ }
355
+ let rootType = handlerType;
356
+ while (rootType && ts.isIndexedAccessTypeNode(rootType))
357
+ rootType = rootType.objectType;
358
+ if (!rootType ||
359
+ !ts.isTypeReferenceNode(rootType) ||
360
+ !ts.isIdentifier(rootType.typeName)) {
318
361
  throw new Error("Generated handler lacks a named type: " + declaration.name.text);
319
362
  }
320
- let localType = declaration.type.typeName.text;
363
+ let localType = rootType.typeName.text;
321
364
  const originalType = localType;
322
365
  const imported = generatedImports.flatMap((item) => {
323
366
  const named = item.importClause?.namedBindings;
@@ -331,6 +374,9 @@ export class Repository {
331
374
  throw new Error("Cannot find handler type import for " + declaration.name.text);
332
375
  const module = imported.item.moduleSpecifier.text;
333
376
  const exportedType = imported.element.propertyName?.text ?? imported.element.name.text;
377
+ const matchingImport = [...imports].find(([, entry]) => entry.module === module && entry.exported === exportedType);
378
+ if (matchingImport)
379
+ localType = matchingImport[0];
334
380
  const existingImport = imports.get(localType);
335
381
  if (!existingImport ||
336
382
  existingImport.module !== module ||
@@ -342,8 +388,23 @@ export class Repository {
342
388
  imports.set(localType, { module, exported: exportedType });
343
389
  bindings.add(localType);
344
390
  }
391
+ handlerType = renameTypeRoot(handlerType, localType);
392
+ if (generatedAlias && ts.isIndexedAccessTypeNode(handlerType)) {
393
+ const key = typeKey(handlerType.objectType);
394
+ let alias = aliases.get(key);
395
+ if (!alias) {
396
+ alias = "Route";
397
+ let suffix = 2;
398
+ while (bindings.has(alias))
399
+ alias = "Route" + suffix++;
400
+ newAliases.push(typeAlias(alias, handlerType.objectType, false));
401
+ aliases.set(key, alias);
402
+ bindings.add(alias);
403
+ }
404
+ handlerType = ts.factory.createIndexedAccessTypeNode(typeReference(alias), handlerType.indexType);
405
+ }
345
406
  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),
407
+ ts.factory.updateVariableDeclaration(declaration, declaration.name, declaration.exclamationToken, handlerType, declaration.initializer),
347
408
  ])));
348
409
  exported.add(declaration.name.text);
349
410
  bindings.add(declaration.name.text);
@@ -392,12 +453,12 @@ export class Repository {
392
453
  }
393
454
  }
394
455
  let updated = existing;
395
- if (newImports.length > 0) {
456
+ if (newImports.length > 0 || newAliases.length > 0) {
396
457
  const prefix = existing.slice(0, insertAt);
397
458
  updated =
398
459
  prefix +
399
460
  (prefix !== "" && !prefix.endsWith("\n") ? "\n" : "") +
400
- (await formatStatements(newImports)) +
461
+ (await formatStatements([...newImports, ...newAliases])) +
401
462
  existing.slice(insertAt);
402
463
  }
403
464
  updated +=
@@ -423,7 +484,13 @@ export class Repository {
423
484
  * @param path - Repository-relative path to start from.
424
485
  */
425
486
  nearestContextFile(destination, path) {
426
- const directory = pathDirname(path).replace("types/paths", "routes");
487
+ const parts = pathDirname(path)
488
+ .split("/")
489
+ .filter((part) => part !== ".");
490
+ const pathsIndex = parts[0] === "types" ? parts.indexOf("paths") : -1;
491
+ const directory = pathsIndex === 1 || pathsIndex === 2
492
+ ? ["routes", ...parts.slice(pathsIndex + 1)].join("/")
493
+ : parts.join("/");
427
494
  const candidate = nodePath.join(destination, directory, "_.context.ts");
428
495
  if (directory.length <= 1) {
429
496
  // No _context.ts was found so import the one that should be in the root
@@ -435,3 +502,8 @@ export class Repository {
435
502
  return this.nearestContextFile(destination, nodePath.join(path, ".."));
436
503
  }
437
504
  }
505
+ function renameTypeRoot(type, name) {
506
+ return ts.isIndexedAccessTypeNode(type)
507
+ ? ts.factory.updateIndexedAccessTypeNode(type, renameTypeRoot(type.objectType, name), type.indexType)
508
+ : typeReference(name);
509
+ }
@@ -0,0 +1,6 @@
1
+ import ts from "typescript";
2
+ /** Preserve the leading slash on each segment, including root/trailing slashes. */
3
+ export declare function routeTypeSegments(path: string): string[];
4
+ export declare function routeTypeReference(name: string, path: string): ts.TypeNode;
5
+ /** Parent operations and child paths share a branch, regardless of input order. */
6
+ export declare function routesType(routes: ReadonlyMap<string, ReadonlyMap<string, ts.TypeNode>>): ts.TypeNode;
@@ -0,0 +1,37 @@
1
+ import ts from "typescript";
2
+ import { literalType, typeLiteral, typeProperty, typeReference, } from "./ast.js";
3
+ /** Preserve the leading slash on each segment, including root/trailing slashes. */
4
+ export function routeTypeSegments(path) {
5
+ return path.startsWith("/")
6
+ ? path
7
+ .slice(1)
8
+ .split("/")
9
+ .map((segment) => `/${segment}`)
10
+ : [path];
11
+ }
12
+ export function routeTypeReference(name, path) {
13
+ return routeTypeSegments(path).reduce((type, key) => ts.factory.createIndexedAccessTypeNode(type, literalType(key)), typeReference(name));
14
+ }
15
+ /** Parent operations and child paths share a branch, regardless of input order. */
16
+ export function routesType(routes) {
17
+ const root = { children: new Map(), methods: new Map() };
18
+ for (const [path, methods] of routes) {
19
+ let branch = root;
20
+ for (const segment of routeTypeSegments(path)) {
21
+ let child = branch.children.get(segment);
22
+ if (!child) {
23
+ child = { children: new Map(), methods: new Map() };
24
+ branch.children.set(segment, child);
25
+ }
26
+ branch = child;
27
+ }
28
+ branch.methods = methods;
29
+ }
30
+ return branchType(root);
31
+ }
32
+ function branchType(branch) {
33
+ return typeLiteral([
34
+ ...[...branch.methods].map(([method, type]) => typeProperty(method, type)),
35
+ ...[...branch.children].map(([segment, child]) => typeProperty(segment, branchType(child))),
36
+ ]);
37
+ }
@@ -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
+ }
@@ -1,3 +1,8 @@
1
+ import ts from "typescript";
2
+ /** Stable public exports; the filesystem watcher owns only their target module. */
3
+ export declare function helperTypeExports(): ts.ExportDeclaration;
4
+ /** Serialize OpenAPI generation and context-watch updates for each API group. */
5
+ export declare function writeHelperTypes(destination: string, rootDestination?: string, preserveStore?: boolean): Promise<void>;
1
6
  /**
2
7
  * Encapsulates the generation of scenario-related files:
3
8
  * - `types/_.context.ts` — the typed `Scenario$` interface derived from all
@@ -4,7 +4,7 @@ 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
6
  import ts from "typescript";
7
- import { exportedConst, formatStatements, functionType, importDeclaration, literalType, parameter, readonlyProperty, stringType, typeAlias, typeReference, unionType, unknownType, valueExpression, withJsDoc, } from "./ast.js";
7
+ import { exportedConst, formatStatements, functionType, importDeclaration, literalType, parameter, readonlyProperty, stringType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, valueExpression, withJsDoc, } from "./ast.js";
8
8
  import { pathRelative } from "./forward-slash-path.js";
9
9
  import { waitForEvent } from "./wait-for-event.js";
10
10
  import { CHOKIDAR_OPTIONS } from "./watch-options.js";
@@ -56,7 +56,7 @@ async function walkForContextFiles(routesDir, currentDir, results) {
56
56
  async function collectRouteDirectories(destination) {
57
57
  const routesDir = nodePath.join(destination, "routes");
58
58
  if (!existsSync(routesDir)) {
59
- return [];
59
+ return [{ relativePath: "" }];
60
60
  }
61
61
  const results = [];
62
62
  await walkRouteDirectories(routesDir, routesDir, undefined, results);
@@ -210,14 +210,34 @@ async function collectGeneratedMiddlewareTypeFiles(directory) {
210
210
  }
211
211
  return files;
212
212
  }
213
- async function writeMiddlewareTypes(destination) {
214
- const routeDirectories = await collectRouteDirectories(destination);
213
+ /** Readers must see a complete module while watcher events are queued. */
214
+ async function writeGeneratedType(filePath, content) {
215
+ const previous = await fs
216
+ .readFile(filePath, "utf8")
217
+ .catch((error) => {
218
+ if (error.code !== "ENOENT")
219
+ throw error;
220
+ return undefined;
221
+ });
222
+ if (previous === content)
223
+ return;
224
+ const temporaryDirectory = await fs.mkdtemp(nodePath.join(nodePath.dirname(filePath), ".counterfact-type-"));
225
+ try {
226
+ const temporaryFile = nodePath.join(temporaryDirectory, "contents.tmp");
227
+ await fs.writeFile(temporaryFile, content, "utf8");
228
+ await fs.rename(temporaryFile, filePath);
229
+ }
230
+ finally {
231
+ await fs.rm(temporaryDirectory, { recursive: true, force: true });
232
+ }
233
+ }
234
+ async function writeMiddlewareTypes(destination, routeDirectories) {
215
235
  const expectedFiles = new Set();
216
236
  for (const routeDirectory of routeDirectories) {
217
237
  const filePath = nodePath.join(destination, "types", routeDirectory.relativePath, "_.middleware.ts");
218
238
  expectedFiles.add(nodePath.resolve(filePath));
219
239
  await fs.mkdir(nodePath.dirname(filePath), { recursive: true });
220
- await fs.writeFile(filePath, await buildMiddlewareTypeContent(destination, routeDirectory), "utf8");
240
+ await writeGeneratedType(filePath, await buildMiddlewareTypeContent(destination, routeDirectory));
221
241
  }
222
242
  const generatedFiles = await collectGeneratedMiddlewareTypeFiles(nodePath.join(destination, "types"));
223
243
  await Promise.all(generatedFiles
@@ -235,7 +255,7 @@ async function writeMiddlewareTypes(destination) {
235
255
  * @param destination - Root output directory.
236
256
  * @param rootDestination - Application root containing the optional store.
237
257
  */
238
- async function writeScenarioContextType(destination, rootDestination) {
258
+ async function writeScenarioContextType(destination, rootDestination, preserveStore = false) {
239
259
  const typesDir = nodePath.join(destination, "types");
240
260
  const filePath = nodePath.join(typesDir, "_.context.ts");
241
261
  const storePath = nodePath.join(rootDestination, "_.store.ts");
@@ -243,10 +263,88 @@ async function writeScenarioContextType(destination, rootDestination) {
243
263
  const relativeStorePath = pathRelative(typesDir, storePath);
244
264
  const storeImportPath = existsSync(storePath)
245
265
  ? `${relativeStorePath.startsWith(".") ? "" : "./"}${relativeStorePath.replace(/\.ts$/u, ".js")}`
246
- : undefined;
266
+ : preserveStore
267
+ ? await existingStoreImport(filePath, typesDir)
268
+ : undefined;
247
269
  const content = await buildScenarioContextContent(contextFiles, storeImportPath);
248
270
  await fs.mkdir(typesDir, { recursive: true });
249
- await fs.writeFile(filePath, content, "utf8");
271
+ await writeGeneratedType(filePath, content);
272
+ }
273
+ // OpenAPI generation knows the group directory but not the application's root.
274
+ // Recover only an existing, still-live store reference; regenerate context
275
+ // overloads from the current route tree on every pass.
276
+ async function existingStoreImport(filePath, typesDir) {
277
+ const contents = await fs
278
+ .readFile(filePath, "utf8")
279
+ .catch((error) => {
280
+ if (error.code !== "ENOENT")
281
+ throw error;
282
+ return undefined;
283
+ });
284
+ if (contents === undefined)
285
+ return undefined;
286
+ const source = ts.createSourceFile(filePath, contents, ts.ScriptTarget.Latest, true);
287
+ for (const statement of source.statements) {
288
+ if (!ts.isImportDeclaration(statement) ||
289
+ !ts.isStringLiteral(statement.moduleSpecifier))
290
+ continue;
291
+ const bindings = statement.importClause?.namedBindings;
292
+ if (bindings &&
293
+ ts.isNamedImports(bindings) &&
294
+ bindings.elements.some((element) => element.name.text === "Store" &&
295
+ (element.propertyName?.text ?? element.name.text) === "Store")) {
296
+ const modulePath = statement.moduleSpecifier.text;
297
+ if (existsSync(nodePath.resolve(typesDir, modulePath.replace(/\.js$/u, ".ts"))))
298
+ return modulePath;
299
+ }
300
+ }
301
+ return undefined;
302
+ }
303
+ /** Stable public exports; the filesystem watcher owns only their target module. */
304
+ export function helperTypeExports() {
305
+ return ts.factory.createExportDeclaration(undefined, true, ts.factory.createNamedExports(["Context$", "Scenario", "Scenario$", "Middleware"].map((name) => ts.factory.createExportSpecifier(false, undefined, name))), ts.factory.createStringLiteral("./helpers.js"));
306
+ }
307
+ const helperWrites = new Map();
308
+ /** Serialize OpenAPI generation and context-watch updates for each API group. */
309
+ export async function writeHelperTypes(destination, rootDestination = destination, preserveStore = false) {
310
+ const key = nodePath.resolve(destination);
311
+ const previous = helperWrites.get(key) ?? Promise.resolve();
312
+ const pending = (async () => {
313
+ await previous.catch(() => undefined);
314
+ await writeScenarioContextType(destination, rootDestination, preserveStore);
315
+ const directories = (await collectRouteDirectories(destination)).sort((a, b) => a.relativePath < b.relativePath
316
+ ? -1
317
+ : a.relativePath > b.relativePath
318
+ ? 1
319
+ : 0);
320
+ await writeMiddlewareTypes(destination, directories);
321
+ const declarations = [
322
+ ts.factory.createExportDeclaration(undefined, true, ts.factory.createNamedExports(["Context$", "Scenario", "Scenario$"].map((name) => ts.factory.createExportSpecifier(false, undefined, name))), ts.factory.createStringLiteral("./_.context.js")),
323
+ ];
324
+ const properties = directories.map((directory, index) => {
325
+ const alias = `Middleware${index}`;
326
+ const modulePath = ensureRelativeImportPath(nodePath.posix.join(directory.relativePath, "_.middleware.js"));
327
+ declarations.push(importDeclaration(alias, modulePath, true, false, "Middleware"));
328
+ return typeProperty(directory.relativePath === "" ? "/" : `/${directory.relativePath}`, typeReference(alias));
329
+ });
330
+ declarations.push(typeAlias("Middleware", typeLiteral(properties)));
331
+ await writeGeneratedType(nodePath.join(destination, "types/helpers.ts"), await formatStatements(declarations, [GENERATED_FILE_COMMENT.slice(3)]));
332
+ // Spec-free projects can generate helpers independently of the OpenAPI index.
333
+ await fs
334
+ .writeFile(nodePath.join(destination, "types/index.ts"), await formatStatements([helperTypeExports()], [GENERATED_FILE_COMMENT.slice(3)]), { encoding: "utf8", flag: "wx" })
335
+ .catch((error) => {
336
+ if (error.code !== "EEXIST")
337
+ throw error;
338
+ });
339
+ })();
340
+ helperWrites.set(key, pending);
341
+ try {
342
+ await pending;
343
+ }
344
+ finally {
345
+ if (helperWrites.get(key) === pending)
346
+ helperWrites.delete(key);
347
+ }
250
348
  }
251
349
  async function defaultScenariosContent() {
252
350
  const arrow = (statements) => ts.factory.createArrowFunction(undefined, undefined, [parameter("$")], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock(statements, true));
@@ -260,7 +358,7 @@ async function defaultScenariosContent() {
260
358
  ]);
261
359
  const joinedLines = ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(lines, "join"), undefined, [valueExpression("\n")]);
262
360
  return formatStatements([
263
- importDeclaration("Scenario", "../types/_.context.js", true),
361
+ importDeclaration("Scenario", "../types/index.js", true),
264
362
  withJsDoc(exportedConst("startup", arrow([ignoreArgument()]), typeReference("Scenario")), {
265
363
  description: "Scenario scripts are plain TypeScript functions that receive the live REPL\n" +
266
364
  "environment and can read or mutate server state. Run them from the REPL with:\n" +
@@ -320,8 +418,7 @@ export class ScenarioFileGenerator {
320
418
  }
321
419
  /** Generates both scenario-related files once and resolves when complete. */
322
420
  async generate() {
323
- await writeScenarioContextType(this.destination, this.rootDestination);
324
- await writeMiddlewareTypes(this.destination);
421
+ await writeHelperTypes(this.destination, this.rootDestination);
325
422
  await writeDefaultScenariosIndex(this.destination);
326
423
  }
327
424
  /**
@@ -335,10 +432,7 @@ export class ScenarioFileGenerator {
335
432
  const routesDir = nodePath.join(this.destination, "routes");
336
433
  const storePath = nodePath.join(this.rootDestination, "_.store.ts");
337
434
  const regenerate = () => {
338
- void Promise.all([
339
- writeScenarioContextType(this.destination, this.rootDestination),
340
- writeMiddlewareTypes(this.destination),
341
- ]).catch((error) => {
435
+ void writeHelperTypes(this.destination, this.rootDestination).catch((error) => {
342
436
  console.error("Failed to regenerate scenario files:", error);
343
437
  });
344
438
  };
@@ -367,5 +461,8 @@ export class ScenarioFileGenerator {
367
461
  /** Closes the file-system watcher. */
368
462
  async stopWatching() {
369
463
  await Promise.all([this.watcher?.close(), this.storeWatcher?.close()]);
464
+ await helperWrites
465
+ .get(nodePath.resolve(this.destination))
466
+ ?.catch(() => undefined);
370
467
  }
371
468
  }
@@ -0,0 +1,3 @@
1
+ import ts from "typescript";
2
+ /** Apply a containing schema's required list without changing shared referenced models. */
3
+ export declare function requireProperties(type: ts.TypeNode, names: readonly string[]): ts.TypeNode;
@@ -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
+ }
@@ -18,4 +18,5 @@ export declare class SchemaTypeCoder extends TypeCoder {
18
18
  writeEnum(requirement: Requirement): ts.TypeNode;
19
19
  modulePath(): string;
20
20
  writeCode(script: Script): ts.TypeNode;
21
+ private writeSchema;
21
22
  }
@@ -1,5 +1,6 @@
1
1
  import ts from "typescript";
2
- import { typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
2
+ import { typeLiteral, typeProperty, typeReference, unionType, unknownType, neverType, } from "./ast.js";
3
+ import { requireProperties } from "./schema-required-properties.js";
3
4
  import { TypeCoder } from "./type-coder.js";
4
5
  import { pathJoin } from "./forward-slash-path.js";
5
6
  import { buildJsDoc } from "./jsdoc.js";
@@ -13,8 +14,10 @@ export class SchemaTypeCoder extends TypeCoder {
13
14
  }
14
15
  additionalPropertiesType(script) {
15
16
  const { additionalProperties, properties } = this.requirement.data;
16
- if (!additionalProperties.type ||
17
- Object.values(properties ?? {}).some((property) => property.type !== additionalProperties.type)) {
17
+ if (typeof additionalProperties !== "object" ||
18
+ (Object.keys(properties ?? {}).length > 0 &&
19
+ (!additionalProperties.type ||
20
+ Object.values(properties ?? {}).some((property) => property.type !== additionalProperties.type)))) {
18
21
  return unknownType();
19
22
  }
20
23
  return new SchemaTypeCoder(this.requirement.get("additionalProperties"), this.version).write(script);
@@ -35,8 +38,38 @@ export class SchemaTypeCoder extends TypeCoder {
35
38
  return typeLiteral(members);
36
39
  }
37
40
  arraySchema(script) {
41
+ const data = this.requirement.data;
42
+ const tupleKey = Array.isArray(data.prefixItems)
43
+ ? "prefixItems"
44
+ : Array.isArray(data.items)
45
+ ? "items"
46
+ : undefined;
47
+ if (tupleKey) {
48
+ const items = this.requirement.get(tupleKey);
49
+ const members = items
50
+ .map((item, index) => {
51
+ const type = new SchemaTypeCoder(item, this.version).write(script);
52
+ return Number(index) < (data.minItems ?? 0)
53
+ ? type
54
+ : ts.factory.createOptionalTypeNode(type);
55
+ })
56
+ .slice(0, data.maxItems);
57
+ const restKey = tupleKey === "prefixItems" ? "items" : "additionalItems";
58
+ const rest = this.requirement.get(restKey);
59
+ if (rest?.data !== false &&
60
+ (data.maxItems === undefined || data.maxItems > members.length)) {
61
+ const restType = rest
62
+ ? new SchemaTypeCoder(rest, this.version).write(script)
63
+ : unknownType();
64
+ members.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(restType)));
65
+ }
66
+ return ts.factory.createTupleTypeNode(members);
67
+ }
68
+ const items = this.requirement.get("items");
38
69
  return typeReference("Array", [
39
- new SchemaTypeCoder(this.requirement.get("items"), this.version).write(script),
70
+ items
71
+ ? new SchemaTypeCoder(items, this.version).write(script)
72
+ : unknownType(),
40
73
  ]);
41
74
  }
42
75
  writePrimitive(value) {
@@ -76,13 +109,35 @@ export class SchemaTypeCoder extends TypeCoder {
76
109
  case "null":
77
110
  return ts.factory.createLiteralTypeNode(ts.factory.createNull());
78
111
  default:
112
+ if (type === undefined &&
113
+ (this.requirement.has("properties") ||
114
+ this.requirement.has("additionalProperties"))) {
115
+ return this.objectSchema(script);
116
+ }
79
117
  return unknownType();
80
118
  }
81
119
  }
82
120
  writeGroup(script, { allOf, anyOf, oneOf, }) {
83
121
  const key = allOf ? "allOf" : anyOf ? "anyOf" : "oneOf";
84
122
  const items = (allOf ?? anyOf ?? oneOf);
85
- const types = items.map((_item, index) => new SchemaTypeCoder(this.requirement.get(key).get(index), this.version).write(script));
123
+ const { discriminator } = this.requirement.data;
124
+ const types = items.map((_item, index) => {
125
+ const branch = this.requirement.get(key).get(index);
126
+ const type = new SchemaTypeCoder(branch, this.version).write(script);
127
+ const values = !allOf && branch.refUrl && discriminator?.propertyName
128
+ ? Object.entries(discriminator.mapping ?? {})
129
+ .filter(([, ref]) => ref === branch.refUrl)
130
+ .map(([value]) => this.writePrimitive(value))
131
+ : [];
132
+ return values.length > 0
133
+ ? unionType(values.map((value) => ts.factory.createIntersectionTypeNode([
134
+ type,
135
+ typeLiteral([
136
+ typeProperty(discriminator.propertyName, value),
137
+ ]),
138
+ ])))
139
+ : type;
140
+ });
86
141
  // OpenAPI 3.2 discriminator fallback participates in the union.
87
142
  if (!allOf) {
88
143
  const { discriminator } = this.requirement.data;
@@ -101,6 +156,21 @@ export class SchemaTypeCoder extends TypeCoder {
101
156
  return pathJoin("types", this.version, this.requirement.refUrl.replace(/^#\//u, "") + ".ts");
102
157
  }
103
158
  writeCode(script) {
159
+ if (this.requirement.data === false)
160
+ return neverType();
161
+ if (this.requirement.data === true || this.requirement.data === null)
162
+ return unknownType();
163
+ const type = this.writeSchema(script);
164
+ const data = this.requirement.data;
165
+ // nullable expands the declared type; enum/const remain independent constraints.
166
+ return data.nullable === true &&
167
+ data.type !== undefined &&
168
+ !this.requirement.has("enum") &&
169
+ !this.requirement.has("const")
170
+ ? unionType([type, this.writePrimitive(null)])
171
+ : type;
172
+ }
173
+ writeSchema(script) {
104
174
  const { allOf, anyOf, oneOf, type, format, itemSchema } = this.requirement
105
175
  .data;
106
176
  if (itemSchema) {
@@ -109,7 +179,26 @@ export class SchemaTypeCoder extends TypeCoder {
109
179
  ]);
110
180
  }
111
181
  if (allOf ?? anyOf ?? oneOf) {
112
- return this.writeGroup(script, { allOf, anyOf, oneOf });
182
+ const parts = [];
183
+ for (const group of [{ allOf }, { anyOf }, { oneOf }]) {
184
+ if (Object.values(group)[0] !== undefined)
185
+ parts.push(this.writeGroup(script, group));
186
+ }
187
+ if (this.requirement.has("properties") ||
188
+ this.requirement.has("additionalProperties")) {
189
+ parts.push(this.objectSchema(script));
190
+ }
191
+ const result = parts.length === 1
192
+ ? parts[0]
193
+ : ts.factory.createIntersectionTypeNode(parts);
194
+ const required = this.requirement.data
195
+ .required;
196
+ return Array.isArray(required) && required.length > 0
197
+ ? requireProperties(result, required)
198
+ : result;
199
+ }
200
+ if (this.requirement.has("const")) {
201
+ return this.writePrimitive(this.requirement.get("const").data);
113
202
  }
114
203
  if (this.requirement.has("enum")) {
115
204
  return this.writeEnum(this.requirement.get("enum"));