@counterfact/generator 1.0.0 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @counterfact/generator
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a724401: Generate a central `types/index.ts` exporting `Routes`, `Components`, and `Schemas` (an alias of `Components["schemas"]`). Include unused components, preserve lowercase OpenAPI categories, and use indexed `Routes` contracts in new route handlers while preserving existing route edits and deep imports.
8
+
9
+ Deprecate deep imports of generated operation and component types. Use the central exports throughout the manual, API reference, homepage, walkthrough, and agent guidance.
10
+
11
+ Expose `Context$`, `Scenario`, `Scenario$`, and directory-indexed `Middleware` through the central entry point. New context and scenario starters use central imports; context watching refreshes the helper module and middleware directory map. Dedicated helper imports remain compatible but deprecated.
12
+
13
+ Fix versioned handler narrowing after `minVersion()` checks, including early returns, negated conditions, and explicit else branches. Literal checks narrow both request and response contracts; dynamic union thresholds use a boolean overload to avoid incorrectly excluding possible versions.
14
+
15
+ Organize `Routes` as a tree of slash-prefixed path segments. Select `/hello/world` with `Routes["/hello"]["/world"]`; parent operations and child branches coexist, and generated handlers and documentation use the nested indexes.
16
+
17
+ Write watched helper modules atomically and skip unchanged content so TypeScript readers do not observe empty modules during regeneration.
18
+
19
+ Declare a local `Route` alias once per generated route file and annotate handlers with `Route["GET"]`, `Route["POST"]`, and other method keys. Regeneration reuses matching aliases and avoids existing local names while preserving user code.
20
+
21
+ ### Patch Changes
22
+
23
+ - 40656be: Require Node 22.22 or later for Chokidar 6 compatibility.
24
+ - 93944c6: Updated dependency `chokidar` in `@counterfact/generator` to `6.0.0`.
25
+ Updated dependency `chokidar` in `@counterfact/runtime` to `6.0.0`.
26
+ - Updated dependencies [1f340b6]
27
+ - @counterfact/openapi@0.1.7
28
+
3
29
  ## 1.0.0
4
30
 
5
31
  ### Major Changes
@@ -0,0 +1,14 @@
1
+ import type { OperationTypeCoder } from "./operation-type-coder.js";
2
+ import type { Repository } from "./repository.js";
3
+ import type { Specification } from "./specification.js";
4
+ /** One public entry point per API group, assembled after all versions register. */
5
+ declare class CentralTypes {
6
+ private readonly script;
7
+ private readonly routes;
8
+ private readonly components;
9
+ constructor(repository: Repository);
10
+ addOperation(path: string, method: string, coder: OperationTypeCoder): void;
11
+ addComponents(specification: Specification, version: string): void;
12
+ }
13
+ export declare function centralTypes(repository: Repository): CentralTypes;
14
+ export {};
@@ -0,0 +1,128 @@
1
+ import ts from "typescript";
2
+ import { literalType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
3
+ import { pathJoin } from "./forward-slash-path.js";
4
+ import { routesType } from "./route-type-tree.js";
5
+ import { helperTypeExports } from "./scenario-file-generator.js";
6
+ import { READ_ONLY_COMMENTS } from "./read-only-comments.js";
7
+ import { SchemaTypeCoder } from "./schema-type-coder.js";
8
+ import { ResponseTypeCoder } from "./response-type-coder.js";
9
+ import { TypeCoder } from "./type-coder.js";
10
+ import { Requirement } from "./requirement.js";
11
+ const CATEGORIES = [
12
+ "schemas",
13
+ "parameters",
14
+ "responses",
15
+ "requestBodies",
16
+ "headers",
17
+ "examples",
18
+ "securitySchemes",
19
+ "links",
20
+ "callbacks",
21
+ "pathItems",
22
+ "mediaTypes",
23
+ ];
24
+ /** Non-schema components keep their structure; embedded schemas become data types. */
25
+ class ComponentTypeCoder extends TypeCoder {
26
+ modulePath() {
27
+ return pathJoin("types", this.version, (this.requirement.refUrl ?? this.requirement.url).replace(/^#\//u, "") +
28
+ ".ts");
29
+ }
30
+ writeCode(script) {
31
+ const category = this.requirement.url.split("/").at(-2);
32
+ if (category === "parameters" || category === "headers") {
33
+ const schema = this.requirement.get("schema");
34
+ if (schema)
35
+ return new SchemaTypeCoder(schema, this.version).write(script);
36
+ const content = this.requirement.get("content");
37
+ return content ? this.structure(content, script) : unknownType();
38
+ }
39
+ return this.structure(this.requirement, script, !["examples", "securitySchemes", "links"].includes(category ?? ""));
40
+ }
41
+ structure(requirement, script, schemas = true) {
42
+ if (!schemas)
43
+ return literalStructure(requirement.data);
44
+ if (requirement.isReference) {
45
+ return typeReference(script.importType(new ComponentTypeCoder(requirement, this.version)));
46
+ }
47
+ const { data } = requirement;
48
+ if (Array.isArray(data)) {
49
+ return ts.factory.createTupleTypeNode(data.map((_, index) => this.structure(requirement.get(index), script, schemas)));
50
+ }
51
+ if (data !== null && typeof data === "object") {
52
+ return typeLiteral(requirement.map((value, key) => typeProperty(key, schemas && (key === "schema" || key === "itemSchema")
53
+ ? new SchemaTypeCoder(value, this.version).write(script)
54
+ : this.structure(value, script, key !== "example" && key !== "value"))));
55
+ }
56
+ return literalType(data);
57
+ }
58
+ }
59
+ /** One public entry point per API group, assembled after all versions register. */
60
+ class CentralTypes {
61
+ script;
62
+ routes = new Map();
63
+ components = new Map();
64
+ constructor(repository) {
65
+ this.script = repository.get("types/index.ts");
66
+ this.script.comments.push(...READ_ONLY_COMMENTS);
67
+ this.script.reservedNames = new Set([
68
+ "Routes",
69
+ "Components",
70
+ "Schemas",
71
+ "Context$",
72
+ "Scenario",
73
+ "Scenario$",
74
+ "Middleware",
75
+ ]);
76
+ this.script.statementBuilders.set("api-types", () => [
77
+ helperTypeExports(),
78
+ typeAlias("Routes", routesType(this.routes)),
79
+ typeAlias("Components", typeLiteral(CATEGORIES.map((category) => typeProperty(category, typeLiteral([...(this.components.get(category) ?? [])].map(([name, versions]) => typeProperty(name, unionType([...versions.values()])))))))),
80
+ typeAlias("Schemas", ts.factory.createIndexedAccessTypeNode(typeReference("Components"), literalType("schemas"))),
81
+ ]);
82
+ }
83
+ addOperation(path, method, coder) {
84
+ const methods = this.routes.get(path) ?? new Map();
85
+ this.routes.set(path, methods);
86
+ methods.set(method.toUpperCase(), typeReference(this.script.importType(coder, `Route${this.routes.size}_${method.toUpperCase()}`)));
87
+ }
88
+ addComponents(specification, version) {
89
+ for (const category of CATEGORIES) {
90
+ specification
91
+ .getRequirement(`#/components/${category}`)
92
+ ?.forEach((component, name) => {
93
+ const components = this.components.get(category) ??
94
+ new Map();
95
+ this.components.set(category, components);
96
+ const versions = components.get(name) ?? new Map();
97
+ components.set(name, versions);
98
+ // Import by reference so the existing coder chooses the canonical module
99
+ // and resolves component aliases without duplicating their definitions.
100
+ const reference = new Requirement({
101
+ $ref: `#/components/${category}/${name.replaceAll("~", "~0").replaceAll("/", "~1")}`,
102
+ }, component.url, specification);
103
+ const Coder = category === "schemas"
104
+ ? SchemaTypeCoder
105
+ : category === "responses"
106
+ ? ResponseTypeCoder
107
+ : ComponentTypeCoder;
108
+ versions.set(version, typeReference(this.script.importType(new Coder(reference, version))));
109
+ });
110
+ }
111
+ }
112
+ }
113
+ const indexes = new WeakMap();
114
+ export function centralTypes(repository) {
115
+ let index = indexes.get(repository);
116
+ if (!index) {
117
+ index = new CentralTypes(repository);
118
+ indexes.set(repository, index);
119
+ }
120
+ return index;
121
+ }
122
+ function literalStructure(data) {
123
+ if (Array.isArray(data))
124
+ return ts.factory.createTupleTypeNode(data.map(literalStructure));
125
+ if (data !== null && typeof data === "object")
126
+ return typeLiteral(Object.entries(data).map(([key, value]) => typeProperty(key, literalStructure(value))));
127
+ return literalType(data);
128
+ }
@@ -6,9 +6,11 @@ import { watch } from "chokidar";
6
6
  import createDebug from "debug";
7
7
  import { getLocalOpenApiSourcePaths } from "@counterfact/openapi";
8
8
  import { ensureDirectoryExists } from "./ensure-directory-exists.js";
9
+ import { centralTypes } from "./central-types.js";
9
10
  import { OperationCoder } from "./operation-coder.js";
10
11
  import { assertNoNormalizedPathCollisions, normalizeOpenApiPath, } from "./openapi-path.js";
11
12
  import { pruneRoutes, pruneTypes } from "./prune.js";
13
+ import { Requirement } from "./requirement.js";
12
14
  import { Repository } from "./repository.js";
13
15
  import { Specification } from "./specification.js";
14
16
  import { waitForEvent } from "./wait-for-event.js";
@@ -67,11 +69,12 @@ export class CodeGenerator extends EventTarget {
67
69
  */
68
70
  async getPathsFromSpecification(specification) {
69
71
  try {
70
- return specification.getRequirement("#/paths") ?? new Set();
72
+ return (specification.getRequirement("#/paths") ??
73
+ new Requirement({}, "#/paths", specification));
71
74
  }
72
75
  catch (error) {
73
76
  process.stderr.write(`Could not find #/paths in the specification.\n${error}\n`);
74
- return undefined;
77
+ return new Requirement({}, "#/paths", specification);
75
78
  }
76
79
  }
77
80
  /**
@@ -94,6 +97,7 @@ export class CodeGenerator extends EventTarget {
94
97
  const specification = await Specification.fromFile(this.openapiPath, this.overlays);
95
98
  debug("created specification: $o", specification);
96
99
  debug("reading the #/paths from the specification");
100
+ centralTypes(repository).addComponents(specification, this.version);
97
101
  const paths = await this.getPathsFromSpecification(specification);
98
102
  debug("got %i paths", paths?.map?.length ?? 0);
99
103
  const openApiPaths = paths.map((_pathDefinition, key) => key);
@@ -115,26 +119,35 @@ export class CodeGenerator extends EventTarget {
115
119
  "patch",
116
120
  "trace",
117
121
  ]);
118
- const operationMethodsForPath = (pathDefinition) => pathDefinition.flatMap((operation, requestMethod) => {
119
- if (requestMethod === "additionalOperations") {
120
- return operation.map((additionalOperation, additionalMethod) => [
121
- additionalOperation,
122
- additionalMethod.toLowerCase(),
123
- ]);
124
- }
125
- if (!HTTP_VERBS.has(requestMethod)) {
126
- return [];
127
- }
128
- return [[operation, requestMethod]];
129
- });
122
+ const operationMethodsForPath = (pathDefinition) => {
123
+ let resolved = pathDefinition;
124
+ while (resolved.isReference)
125
+ resolved = resolved.reference();
126
+ return resolved.flatMap((operation, requestMethod) => {
127
+ if (requestMethod === "additionalOperations") {
128
+ return operation.map((additionalOperation, additionalMethod) => [
129
+ additionalOperation,
130
+ additionalMethod.toLowerCase(),
131
+ ]);
132
+ }
133
+ if (!HTTP_VERBS.has(requestMethod)) {
134
+ return [];
135
+ }
136
+ return [[operation, requestMethod]];
137
+ });
138
+ };
130
139
  paths.forEach((pathDefinition, key) => {
131
140
  debug("processing path %s", key);
132
141
  const normalizedPath = normalizeOpenApiPath(key);
133
142
  const path = normalizedPath === "/" ? "/index" : normalizedPath;
134
143
  operationMethodsForPath(pathDefinition).forEach(([operation, requestMethod]) => {
144
+ // Keep the logical route location when a Path Item is a reference or
145
+ // a method is declared under OpenAPI 3.2 additionalOperations.
146
+ const logicalOperation = new Requirement(operation.data, `${pathDefinition.url}/${requestMethod}`, specification);
147
+ logicalOperation.parent = pathDefinition;
135
148
  repository
136
149
  .get(`routes${path}.ts`)
137
- .export(new OperationCoder(operation, this.version, requestMethod, securitySchemes));
150
+ .export(new OperationCoder(logicalOperation, this.version, requestMethod, securitySchemes));
138
151
  });
139
152
  });
140
153
  if (this.generateOptions.prune && this.generateOptions.types) {
@@ -1,7 +1,9 @@
1
1
  import { STREAMING_CONTENT_TYPES } from "@counterfact/types/streaming-content-types";
2
2
  import { pathJoin } from "./forward-slash-path.js";
3
3
  import ts from "typescript";
4
- import { parameter, typeReference } from "./ast.js";
4
+ import { literalType, parameter, typeReference } from "./ast.js";
5
+ import { routeTypeReference } from "./route-type-tree.js";
6
+ import { centralTypes } from "./central-types.js";
5
7
  import { Coder } from "./coder.js";
6
8
  import { normalizeOpenApiPath } from "./openapi-path.js";
7
9
  import { OperationTypeCoder, VersionedArgTypeCoder, } from "./operation-type-coder.js";
@@ -79,7 +81,13 @@ export class OperationCoder extends Coder {
79
81
  const sharedScript = script.repository.get(operationTypeCoder.modulePath());
80
82
  sharedScript.declareVersion(versionedArgCoder, operationTypeCoder.getOperationBaseName());
81
83
  }
82
- return typeReference(script.importType(operationTypeCoder));
84
+ const path = this.requirement.parent?.url.split("/").at(-1) ??
85
+ this.requirement.url.split("/").at(-2);
86
+ const routePath = path.replaceAll("~1", "/").replaceAll("~0", "~");
87
+ centralTypes(script.repository).addOperation(routePath, this.requestMethod, operationTypeCoder);
88
+ const routes = script.importExternalType("Routes", pathJoin(script.relativePathToBase, "types/index.js"));
89
+ script.localTypes.set("Route", routeTypeReference(routes, routePath));
90
+ return ts.factory.createIndexedAccessTypeNode(typeReference("Route"), literalType(this.requestMethod.toUpperCase()));
83
91
  }
84
92
  modulePath() {
85
93
  const pathString = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
@@ -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
+ }
@@ -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
  }
package/dist/script.d.ts CHANGED
@@ -27,13 +27,16 @@ export declare class Script {
27
27
  imports: Map<string, ImportEntry>;
28
28
  externalImport: Map<string, ExternalImportEntry>;
29
29
  cache: Map<string, string>;
30
+ reservedNames: Set<string>;
31
+ localTypes: Map<string, ts.TypeNode>;
32
+ statementBuilders: Map<string, () => ts.Statement[]>;
30
33
  constructor(repository: Repository, path: string);
31
34
  get relativePathToBase(): string;
32
35
  firstUniqueName(coder: Coder, isType?: boolean, isDefault?: boolean): string;
33
36
  export(coder: Coder, isType?: boolean, isDefault?: boolean): string;
34
37
  exportDefault(coder: Coder, isType?: boolean): void;
35
- import(coder: Coder, isType?: boolean, isDefault?: boolean): string;
36
- importType(coder: Coder): string;
38
+ import(coder: Coder, isType?: boolean, isDefault?: boolean, preferredName?: string): string;
39
+ importType(coder: Coder, preferredName?: string): string;
37
40
  importDefault(coder: Coder, isType?: boolean): string;
38
41
  importExternal(name: string, modulePath: ModuleReference, isType?: boolean): string;
39
42
  importExternalType(name: string, path: ModuleReference): string;
package/dist/script.js CHANGED
@@ -15,6 +15,9 @@ export class Script {
15
15
  imports = new Map();
16
16
  externalImport = new Map();
17
17
  cache = new Map();
18
+ reservedNames = new Set();
19
+ localTypes = new Map();
20
+ statementBuilders = new Map();
18
21
  constructor(repository, path) {
19
22
  this.path = path;
20
23
  this.repository = repository;
@@ -28,10 +31,12 @@ export class Script {
28
31
  }
29
32
  firstUniqueName(coder, isType = false, isDefault = false) {
30
33
  for (const name of coder.names()) {
31
- if ((!this.imports.has(name) ||
32
- (this.imports.get(name).id === coder.exportId &&
33
- this.imports.get(name).isType === isType &&
34
- this.imports.get(name).isDefault === isDefault)) &&
34
+ if (!this.reservedNames.has(name) &&
35
+ (!this.imports.has(name) ||
36
+ (this.imports.get(name).id === coder.exportId &&
37
+ this.imports.get(name).script.path === coder.modulePath() &&
38
+ this.imports.get(name).isType === isType &&
39
+ this.imports.get(name).isDefault === isDefault)) &&
35
40
  (!this.exports.has(name) ||
36
41
  (this.exports.get(name).id === coder.exportId &&
37
42
  this.exports.get(name).isType === isType &&
@@ -80,14 +85,25 @@ export class Script {
80
85
  exportDefault(coder, isType = false) {
81
86
  this.export(coder, isType, true);
82
87
  }
83
- import(coder, isType = false, isDefault = false) {
88
+ import(coder, isType = false, isDefault = false, preferredName) {
84
89
  const modulePath = coder.modulePath();
85
90
  const key = `${coder.id}@${modulePath}:${isType}:${isDefault}`;
86
91
  if (this.cache.has(key))
87
92
  return this.cache.get(key);
88
93
  if (modulePath === this.path)
89
94
  return this.export(coder, isType, isDefault);
90
- const name = this.firstUniqueName(coder, isType, isDefault);
95
+ let name;
96
+ if (preferredName) {
97
+ name = preferredName;
98
+ let suffix = 2;
99
+ while (this.imports.has(name) ||
100
+ this.exports.has(name) ||
101
+ this.externalImport.has(name) ||
102
+ this.reservedNames.has(name))
103
+ name = preferredName + suffix++;
104
+ }
105
+ else
106
+ name = this.firstUniqueName(coder, isType, isDefault);
91
107
  this.cache.set(key, name);
92
108
  const script = this.repository.get(modulePath);
93
109
  const exportedName = script.export(coder, isType, isDefault);
@@ -101,8 +117,8 @@ export class Script {
101
117
  debug("import %s as %s from %s", exportedName, name, modulePath);
102
118
  return name;
103
119
  }
104
- importType(coder) {
105
- return this.import(coder, true);
120
+ importType(coder, preferredName) {
121
+ return this.import(coder, true, false, preferredName);
106
122
  }
107
123
  importDefault(coder, isType = false) {
108
124
  return this.import(coder, isType, true);
@@ -241,7 +257,9 @@ export class Script {
241
257
  ...this.externalImportStatements(contextPath),
242
258
  ...this.importStatements(),
243
259
  ...this.versionsTypeStatements(),
260
+ ...[...this.localTypes].map(([name, type]) => typeAlias(name, type, false)),
244
261
  ...this.exportStatements(),
262
+ ...[...this.statementBuilders.values()].flatMap((build) => build()),
245
263
  ], this.comments);
246
264
  }
247
265
  }
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { formatStatements, literalType, parameter, typeAlias, typeLiteral, typeProperty, typeReference, unionType, withJsDoc, } from "./ast.js";
2
+ import { formatStatements, literalType, neverType, stringType, parameter, typeAlias, typeLiteral, typeProperty, typeReference, unionType, withJsDoc, } from "./ast.js";
3
3
  function buildVersionsGTE(versions) {
4
4
  return new Map(versions.map((version, index) => [version, versions.slice(index)]));
5
5
  }
@@ -10,10 +10,11 @@ const VERSIONED_DESCRIPTION = `The type of the \u0060$\u0060 argument in a versi
10
10
  @typeParam V - The union of currently active version keys; defaults to all keys of \u0060T\u0060.
11
11
 
12
12
  An instance of \u0060Versioned<T, V>\u0060 exposes:
13
- - All properties of the intersection \u0060T[V]\u0060 (request data, response builders, etc.)
13
+ - A discriminated union of the active version arguments (request data, response builders, etc.)
14
14
  - \u0060version\u0060 — the version string for the current request (e.g. \u0060"v2"\u0060).
15
15
  - \u0060minVersion(min)\u0060 — type predicate that returns \u0060true\u0060 when the current version
16
- is at or after \u0060min\u0060 in the declared version order and narrows \u0060$\u0060 accordingly.`;
16
+ is at or after \u0060min\u0060 in the declared version order. A literal threshold narrows
17
+ both branches; a dynamic union threshold returns boolean without narrowing.`;
17
18
  export async function generateVersionsTsContent(versions) {
18
19
  if (versions.length === 0)
19
20
  return "";
@@ -24,9 +25,14 @@ export async function generateVersionsTsContent(versions) {
24
25
  const activeVersionMap = ts.factory.createIndexedAccessTypeNode(typeReference("VersionsGTE"), typeReference("M"));
25
26
  const narrowing = ts.factory.createTypePredicateNode(undefined, ts.factory.createThisTypeNode(), typeReference("Versioned", [
26
27
  typeReference("T"),
27
- typeReference("Extract", [typeReference("V"), activeVersionMap]),
28
+ typeReference("Extract", [activeKeys(), activeVersionMap]),
28
29
  ]));
29
- const minVersion = ts.factory.createMethodSignature(undefined, "minVersion", undefined, [ts.factory.createTypeParameterDeclaration(undefined, "M", activeKeys())], [parameter("min", typeReference("M"))], narrowing);
30
+ const minVersion = ts.factory.createMethodSignature(undefined, "minVersion", undefined, [ts.factory.createTypeParameterDeclaration(undefined, "M", activeKeys())], [
31
+ parameter("min", ts.factory.createIntersectionTypeNode([
32
+ typeReference("M"),
33
+ typeReference("SingleVersion", [typeReference("M")]),
34
+ ])),
35
+ ], narrowing);
30
36
  return formatStatements([
31
37
  withJsDoc(typeAlias("Versions", unionType(versions.map(literalType))), {
32
38
  description: 'Union of all version strings declared for this API group (e.g. \u0060"v1" | "v2" | "v3"\u0060).',
@@ -40,10 +46,22 @@ export async function generateVersionsTsContent(versions) {
40
46
  ts.factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
41
47
  ]),
42
48
  ]), false),
43
- withJsDoc(typeAlias("Versioned", ts.factory.createIntersectionTypeNode([
44
- ts.factory.createIndexedAccessTypeNode(typeReference("T"), typeReference("V")),
45
- typeLiteral([typeProperty("version", typeReference("V")), minVersion], true),
46
- ]), true, [
49
+ // Distribute over a threshold's possible values. Only a single literal
50
+ // can safely exclude versions from a guard's false branch.
51
+ typeAlias("SingleVersion", ts.factory.createConditionalTypeNode(stringType(), typeReference("V"), neverType(), ts.factory.createConditionalTypeNode(typeReference("V"), typeReference("All"), ts.factory.createConditionalTypeNode(ts.factory.createTupleTypeNode([typeReference("All")]), ts.factory.createTupleTypeNode([typeReference("V")]), typeReference("V"), neverType()), neverType())), false, [
52
+ ts.factory.createTypeParameterDeclaration(undefined, "V"),
53
+ ts.factory.createTypeParameterDeclaration(undefined, "All", undefined, typeReference("V")),
54
+ ]),
55
+ withJsDoc(typeAlias("Versioned", ts.factory.createIndexedAccessTypeNode(ts.factory.createMappedTypeNode(undefined, ts.factory.createTypeParameterDeclaration(undefined, "K", typeReference("V")), undefined, undefined, ts.factory.createIntersectionTypeNode([
56
+ ts.factory.createIndexedAccessTypeNode(typeReference("T"), typeReference("K")),
57
+ typeLiteral([
58
+ typeProperty("version", typeReference("K")),
59
+ minVersion,
60
+ ts.factory.createMethodSignature(undefined, "minVersion", undefined, [
61
+ ts.factory.createTypeParameterDeclaration(undefined, "M", activeKeys()),
62
+ ], [parameter("min", typeReference("M"))], ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword)),
63
+ ], true),
64
+ ]), undefined), typeReference("V")), true, [
47
65
  ts.factory.createTypeParameterDeclaration(undefined, "T", typeReference("VersionMap")),
48
66
  ts.factory.createTypeParameterDeclaration(undefined, "V", activeKeys(), activeKeys()),
49
67
  ]), { description: VERSIONED_DESCRIPTION }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@counterfact/generator",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Generate Counterfact route scaffolds and OpenAPI-derived TypeScript contracts.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -40,7 +40,7 @@
40
40
  "testing"
41
41
  ],
42
42
  "engines": {
43
- "node": ">=22"
43
+ "node": ">=22.22"
44
44
  },
45
45
  "publishConfig": {
46
46
  "access": "public"
@@ -52,9 +52,9 @@
52
52
  "test:packed-consumer": "node test/package/generator-consumer-smoke.mjs"
53
53
  },
54
54
  "dependencies": {
55
- "@counterfact/openapi": "0.1.6",
55
+ "@counterfact/openapi": "0.1.7",
56
56
  "@counterfact/types": "0.2.0",
57
- "chokidar": "5.0.0",
57
+ "chokidar": "6.0.0",
58
58
  "debug": "4.4.3",
59
59
  "prettier": "3.9.10",
60
60
  "typescript": "6.0.3"
package/src/README.md CHANGED
@@ -10,6 +10,25 @@ Fortunately, we _do_ have pretty much all the information we need to generate _t
10
10
 
11
11
  We can also use those types on the _client_ side, assuming the client is written in TypeScript.
12
12
 
13
+ ## Public generated types
14
+
15
+ Generated projects expose `Routes`, `Components`, and `Schemas` through
16
+ `types/index.ts`. `Routes` is a tree of slash-prefixed segments: an operation on
17
+ `/hello/world` uses `Routes["/hello"]["/world"]["GET"]`. Parent operations and
18
+ child paths can share one branch. Routes import `Routes` from that entry point and use
19
+ `Routes["/hello-world"]["GET"]`; model consumers use `Schemas["Message"]`
20
+ or `Components["schemas"]["Message"]`. Direct imports of operation and
21
+ component types are deprecated for consumers.
22
+
23
+ The individual operation and component modules remain generator implementation
24
+ and compatibility surfaces. Internal coders continue importing dependencies
25
+ directly. `central-types.ts` registers operations and all declared components,
26
+ then emits the central maps after the repository has resolved their types.
27
+ The central entry point also re-exports `Context$`, `Scenario`, `Scenario$`, and
28
+ the directory-indexed `Middleware` map from `types/helpers.ts`. Helper generation
29
+ and context watching own that module; OpenAPI generation owns the API maps.
30
+ Both writers serialize helper updates without rewriting each other's exports.
31
+
13
32
  ## Files
14
33
 
15
34
  | File | Description |
@@ -21,6 +40,7 @@ We can also use those types on the _client_ side, assuming the client is written
21
40
  | `script.ts` | `Script` class: manages code generation for a single output file — imports, exports, deduplication, and Prettier formatting |
22
41
  | `coder.ts` | Abstract `Coder` base class: defines the Template Method pattern used by all code-generating components |
23
42
  | `type-coder.ts` | Abstract `TypeCoder` base class (extends `Coder`): specialises `Coder` for type-generating components |
43
+ | `central-types.ts` | Assembles the public `Routes`, `Components`, and `Schemas` maps, preserving logical paths and combining component versions |
24
44
  | `operation-coder.ts` | `OperationCoder`: generates the route handler function for an OpenAPI operation |
25
45
  | `operation-type-coder.ts` | `OperationTypeCoder`: generates the TypeScript type for a route handler, including parameters and response builder |
26
46
  | `parameters-type-coder.ts` | `ParametersTypeCoder`: generates the typed object for path/query/header parameters of an operation |
@@ -29,7 +49,7 @@ We can also use those types on the _client_ side, assuming the client is written
29
49
  | `response-type-coder.ts` | `ResponseTypeCoder`: generates the type for a single HTTP response, including headers, content, and named examples |
30
50
  | `schema-type-coder.ts` | `SchemaTypeCoder`: converts an OpenAPI schema definition to a TypeScript type (objects, arrays, unions, enums) |
31
51
  | `schema-coder.ts` | `SchemaCoder`: generates a JSON Schema representation of an OpenAPI schema for use in runtime validation |
32
- | `ast.ts` | TypeScript AST construction and printing helpers |
52
+ | `ast.ts` | TypeScript AST construction and printing helpers |
33
53
  | `read-only-comments.ts` | Standard warning comments inserted into generated type files to discourage manual edits |
34
54
 
35
55
  ## Architecture
@@ -136,14 +156,20 @@ paths:
136
156
  type: string
137
157
  ```
138
158
 
139
- Our goal is to produce a file at `/routes/hello.ts` that exports a function named `GET` (1). Our implementation will depend on a type for the `GET` function which lives in `/routes/types-hello.ts` (2). That type, in turn, will depend on a type named `Message` which lives in `/components/message.ts` (3).
140
-
141
- (1) We kick off the process by iterating over the paths. (In our simple example there's only one path, at `/hello`.) In our model, each path is represented as a `Requirement`. We give each path / `Requirement` to an `OperationCoder` who will write the code. We ask the repository for a `Script` and then hand the `Script` our `OperationCoder` instance and ask it to create an export.
142
-
143
- (2a) The `OperationCoder` knows that the function has to have a type, but it doesn't know to create that type. So it recruits an `OperationTypeCoder` and hands it the `Requirement`. It then asks the `Script` to _import_ a type, passing along the `OperationTypeCoder`. The `Script` returns the name of the variable to which the imported type will be assigned. That name is all the `OperationCoder` needs to know to continue writing its portion of the code. The `OperationCoder` continues on, writing the `GET` function. Depending on what it finds in the `Requirement`, it will break off parts and delegate some of the work to other `Coder`s.
144
-
145
- (2b) The `Script` has promised that it will import the type from `/types/paths/hello.type.ts` so it needs to make sure that file exists and has a matching export. It goes to the repository to get another `Script` and asks it to _export_ the type, passing along the `OperationTypeCoder` in the process. It's a little tricky here because `OperationTypeCoder`'s `Requirement` may not have the information it needs to proceed. It might have a `$ref` pointer to some _other_ requirement that might be in a different file. So before asking for the export, it asks the `OperationTypeCoder` to give it _another_ `OperationTypeCoder` that definitely has the requirement. Because the other requirement may be in another file that the `Repository` hasn't loaded yet, this part happens asynchronously.
146
-
147
- (2c) When it's ready, the `Script` asks the `OperationTypeCoder` which definitely has an immediately usable requirement to write the export for the `Script` at `/types/paths/hello.types.ts`.
148
-
149
- (3) The `OperationTypeCoder` needs the help of a `SchemaCoder` so it asks the `Script` at `/types/paths/hello.types.ts` for an export...
159
+ Our goal is to produce `routes/hello-world.ts`, exporting a `GET` handler typed
160
+ as `Routes["/hello-world"]["GET"]`, and a reusable model available as
161
+ `Schemas["Message"]`.
162
+
163
+ 1. `CodeGenerator` registers every declared component with the central index,
164
+ including unused schemas. It traverses path operations and exports each
165
+ `OperationCoder` to its route script.
166
+ 2. `OperationCoder.typeDeclaration()` registers its `OperationTypeCoder` with
167
+ the central index and imports `Routes` into the route. The index imports the
168
+ handler contract from its existing operation module. Versioned operations
169
+ still register each version's argument type on the shared operation script.
170
+ 3. The operation contract uses other coders for parameters, responses, and
171
+ schemas. `Script.importType()` resolves their exports through `Repository`,
172
+ keeping those internal imports direct and collision-safe.
173
+ 4. After all types resolve, the central script emits `Routes`, `Components`,
174
+ and `Schemas = Components["schemas"]` through a deferred statement builder.
175
+ `Repository` writes regenerated types and preserves user-edited route text.