@counterfact/generator 1.0.0 → 1.2.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.
@@ -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
  }
@@ -3,6 +3,7 @@ import { TypeCoder } from "./type-coder.js";
3
3
  import { Requirement } from "./requirement.js";
4
4
  import type { Script } from "./script.js";
5
5
  export declare class SchemaTypeCoder extends TypeCoder {
6
+ protected child(requirement: Requirement): SchemaTypeCoder;
6
7
  names(): Generator<string>;
7
8
  jsdoc(): string;
8
9
  additionalPropertiesType(script: Script): ts.TypeNode;
@@ -18,5 +19,5 @@ export declare class SchemaTypeCoder extends TypeCoder {
18
19
  writeEnum(requirement: Requirement): ts.TypeNode;
19
20
  modulePath(): string;
20
21
  writeCode(script: Script): ts.TypeNode;
21
- private writeSchema;
22
+ protected writeSchema(script: Script): ts.TypeNode;
22
23
  }
@@ -6,6 +6,9 @@ import { pathJoin } from "./forward-slash-path.js";
6
6
  import { buildJsDoc } from "./jsdoc.js";
7
7
  import { Requirement } from "./requirement.js";
8
8
  export class SchemaTypeCoder extends TypeCoder {
9
+ child(requirement) {
10
+ return new SchemaTypeCoder(requirement, this.version);
11
+ }
9
12
  names() {
10
13
  return super.names(this.requirement.refUrl?.split("/").at(-1));
11
14
  }
@@ -20,7 +23,7 @@ export class SchemaTypeCoder extends TypeCoder {
20
23
  Object.values(properties ?? {}).some((property) => property.type !== additionalProperties.type)))) {
21
24
  return unknownType();
22
25
  }
23
- return new SchemaTypeCoder(this.requirement.get("additionalProperties"), this.version).write(script);
26
+ return this.child(this.requirement.get("additionalProperties")).write(script);
24
27
  }
25
28
  objectSchema(script) {
26
29
  const data = this.requirement.data;
@@ -28,7 +31,7 @@ export class SchemaTypeCoder extends TypeCoder {
28
31
  const property = this.requirement.get("properties").get(name);
29
32
  const isRequired = data.required?.includes(name) ||
30
33
  property.data.required === true;
31
- return typeProperty(name, new SchemaTypeCoder(property, this.version).write(script), !isRequired, property.data);
34
+ return typeProperty(name, this.child(property).write(script), !isRequired, property.data);
32
35
  });
33
36
  if (data.additionalProperties) {
34
37
  members.push(ts.factory.createIndexSignature(undefined, [
@@ -48,7 +51,7 @@ export class SchemaTypeCoder extends TypeCoder {
48
51
  const items = this.requirement.get(tupleKey);
49
52
  const members = items
50
53
  .map((item, index) => {
51
- const type = new SchemaTypeCoder(item, this.version).write(script);
54
+ const type = this.child(item).write(script);
52
55
  return Number(index) < (data.minItems ?? 0)
53
56
  ? type
54
57
  : ts.factory.createOptionalTypeNode(type);
@@ -58,18 +61,14 @@ export class SchemaTypeCoder extends TypeCoder {
58
61
  const rest = this.requirement.get(restKey);
59
62
  if (rest?.data !== false &&
60
63
  (data.maxItems === undefined || data.maxItems > members.length)) {
61
- const restType = rest
62
- ? new SchemaTypeCoder(rest, this.version).write(script)
63
- : unknownType();
64
+ const restType = rest ? this.child(rest).write(script) : unknownType();
64
65
  members.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(restType)));
65
66
  }
66
67
  return ts.factory.createTupleTypeNode(members);
67
68
  }
68
69
  const items = this.requirement.get("items");
69
70
  return typeReference("Array", [
70
- items
71
- ? new SchemaTypeCoder(items, this.version).write(script)
72
- : unknownType(),
71
+ items ? this.child(items).write(script) : unknownType(),
73
72
  ]);
74
73
  }
75
74
  writePrimitive(value) {
@@ -123,7 +122,7 @@ export class SchemaTypeCoder extends TypeCoder {
123
122
  const { discriminator } = this.requirement.data;
124
123
  const types = items.map((_item, index) => {
125
124
  const branch = this.requirement.get(key).get(index);
126
- const type = new SchemaTypeCoder(branch, this.version).write(script);
125
+ const type = this.child(branch).write(script);
127
126
  const values = !allOf && branch.refUrl && discriminator?.propertyName
128
127
  ? Object.entries(discriminator.mapping ?? {})
129
128
  .filter(([, ref]) => ref === branch.refUrl)
@@ -142,7 +141,7 @@ export class SchemaTypeCoder extends TypeCoder {
142
141
  if (!allOf) {
143
142
  const { discriminator } = this.requirement.data;
144
143
  if (discriminator?.defaultMapping) {
145
- types.push(new SchemaTypeCoder(new Requirement({ $ref: discriminator.defaultMapping }, "", this.requirement.specification), this.version).write(script));
144
+ types.push(this.child(new Requirement({ $ref: discriminator.defaultMapping }, "", this.requirement.specification)).write(script));
146
145
  }
147
146
  }
148
147
  return allOf
@@ -175,7 +174,7 @@ export class SchemaTypeCoder extends TypeCoder {
175
174
  .data;
176
175
  if (itemSchema) {
177
176
  return typeReference("AsyncIterable", [
178
- new SchemaTypeCoder(this.requirement.get("itemSchema"), this.version).write(script),
177
+ this.child(this.requirement.get("itemSchema")).write(script),
179
178
  ]);
180
179
  }
181
180
  if (allOf ?? anyOf ?? oneOf) {
package/dist/script.d.ts CHANGED
@@ -12,6 +12,7 @@ export type ModuleReference = string | {
12
12
  context: true;
13
13
  };
14
14
  interface ExternalImportEntry {
15
+ exportedName?: string;
15
16
  isDefault?: boolean;
16
17
  isType: boolean;
17
18
  modulePath: ModuleReference;
@@ -21,19 +22,23 @@ export declare class Script {
21
22
  path: string;
22
23
  repository: Repository;
23
24
  comments: string[];
25
+ contextRoutePath?: string;
24
26
  exports: Map<string, ExportStatement>;
25
27
  versions: Map<string, Map<string, ExportStatement>>;
26
28
  versionBuilders: Map<string, (versions: Map<string, ts.TypeNode>) => ts.Statement[]>;
27
29
  imports: Map<string, ImportEntry>;
28
30
  externalImport: Map<string, ExternalImportEntry>;
29
31
  cache: Map<string, string>;
32
+ reservedNames: Set<string>;
33
+ localTypes: Map<string, ts.TypeNode>;
34
+ statementBuilders: Map<string, () => ts.Statement[]>;
30
35
  constructor(repository: Repository, path: string);
31
36
  get relativePathToBase(): string;
32
37
  firstUniqueName(coder: Coder, isType?: boolean, isDefault?: boolean): string;
33
38
  export(coder: Coder, isType?: boolean, isDefault?: boolean): string;
34
39
  exportDefault(coder: Coder, isType?: boolean): void;
35
- import(coder: Coder, isType?: boolean, isDefault?: boolean): string;
36
- importType(coder: Coder): string;
40
+ import(coder: Coder, isType?: boolean, isDefault?: boolean, preferredName?: string): string;
41
+ importType(coder: Coder, preferredName?: string): string;
37
42
  importDefault(coder: Coder, isType?: boolean): string;
38
43
  importExternal(name: string, modulePath: ModuleReference, isType?: boolean): string;
39
44
  importExternalType(name: string, path: ModuleReference): string;
package/dist/script.js CHANGED
@@ -9,12 +9,16 @@ export class Script {
9
9
  path;
10
10
  repository;
11
11
  comments = [];
12
+ contextRoutePath;
12
13
  exports = new Map();
13
14
  versions = new Map();
14
15
  versionBuilders = new Map();
15
16
  imports = new Map();
16
17
  externalImport = new Map();
17
18
  cache = new Map();
19
+ reservedNames = new Set();
20
+ localTypes = new Map();
21
+ statementBuilders = new Map();
18
22
  constructor(repository, path) {
19
23
  this.path = path;
20
24
  this.repository = repository;
@@ -28,10 +32,12 @@ export class Script {
28
32
  }
29
33
  firstUniqueName(coder, isType = false, isDefault = false) {
30
34
  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)) &&
35
+ if (!this.reservedNames.has(name) &&
36
+ (!this.imports.has(name) ||
37
+ (this.imports.get(name).id === coder.exportId &&
38
+ this.imports.get(name).script.path === coder.modulePath() &&
39
+ this.imports.get(name).isType === isType &&
40
+ this.imports.get(name).isDefault === isDefault)) &&
35
41
  (!this.exports.has(name) ||
36
42
  (this.exports.get(name).id === coder.exportId &&
37
43
  this.exports.get(name).isType === isType &&
@@ -80,14 +86,25 @@ export class Script {
80
86
  exportDefault(coder, isType = false) {
81
87
  this.export(coder, isType, true);
82
88
  }
83
- import(coder, isType = false, isDefault = false) {
89
+ import(coder, isType = false, isDefault = false, preferredName) {
84
90
  const modulePath = coder.modulePath();
85
91
  const key = `${coder.id}@${modulePath}:${isType}:${isDefault}`;
86
92
  if (this.cache.has(key))
87
93
  return this.cache.get(key);
88
94
  if (modulePath === this.path)
89
95
  return this.export(coder, isType, isDefault);
90
- const name = this.firstUniqueName(coder, isType, isDefault);
96
+ let name;
97
+ if (preferredName) {
98
+ name = preferredName;
99
+ let suffix = 2;
100
+ while (this.imports.has(name) ||
101
+ this.exports.has(name) ||
102
+ this.externalImport.has(name) ||
103
+ this.reservedNames.has(name))
104
+ name = preferredName + suffix++;
105
+ }
106
+ else
107
+ name = this.firstUniqueName(coder, isType, isDefault);
91
108
  this.cache.set(key, name);
92
109
  const script = this.repository.get(modulePath);
93
110
  const exportedName = script.export(coder, isType, isDefault);
@@ -101,15 +118,29 @@ export class Script {
101
118
  debug("import %s as %s from %s", exportedName, name, modulePath);
102
119
  return name;
103
120
  }
104
- importType(coder) {
105
- return this.import(coder, true);
121
+ importType(coder, preferredName) {
122
+ return this.import(coder, true, false, preferredName);
106
123
  }
107
124
  importDefault(coder, isType = false) {
108
125
  return this.import(coder, isType, true);
109
126
  }
110
127
  importExternal(name, modulePath, isType = false) {
111
- this.externalImport.set(name, { isType, modulePath });
112
- return name;
128
+ const existing = [...this.externalImport].find(([, entry]) => (entry.modulePath === modulePath ||
129
+ (typeof entry.modulePath !== "string" &&
130
+ typeof modulePath !== "string")) &&
131
+ entry.isType === isType &&
132
+ entry.exportedName === name);
133
+ if (existing)
134
+ return existing[0];
135
+ let local = name;
136
+ let suffix = 2;
137
+ while (this.reservedNames.has(local) ||
138
+ this.exports.has(local) ||
139
+ this.imports.has(local) ||
140
+ this.externalImport.has(local))
141
+ local = name + suffix++;
142
+ this.externalImport.set(local, { isType, modulePath, exportedName: name });
143
+ return local;
113
144
  }
114
145
  importExternalType(name, path) {
115
146
  return this.importExternal(name, path, true);
@@ -178,7 +209,7 @@ export class Script {
178
209
  pathRelative(pathDirname(this.path), "routes/_.context.ts"));
179
210
  return importDeclaration(name, modulePath.startsWith(".") || typeof entry.modulePath === "string"
180
211
  ? modulePath
181
- : `./${modulePath}`, entry.isType, entry.isDefault);
212
+ : `./${modulePath}`, entry.isType, entry.isDefault, entry.exportedName ?? name);
182
213
  });
183
214
  }
184
215
  importStatements() {
@@ -241,7 +272,9 @@ export class Script {
241
272
  ...this.externalImportStatements(contextPath),
242
273
  ...this.importStatements(),
243
274
  ...this.versionsTypeStatements(),
275
+ ...[...this.localTypes].map(([name, type]) => typeAlias(name, type, false)),
244
276
  ...this.exportStatements(),
277
+ ...[...this.statementBuilders.values()].flatMap((build) => build()),
245
278
  ], this.comments);
246
279
  }
247
280
  }
@@ -28,3 +28,4 @@ export type { ResponseBuilder } from "./response-builder.js";
28
28
  export type { ResponseBuilderFactory } from "./response-builder-factory.js";
29
29
  export type { WideOperationArgument } from "./wide-operation-argument.js";
30
30
  export type { WideResponseBuilder } from "./wide-response-builder.js";
31
+ export type { MultipartFile } from "./multipart-file.js";
@@ -0,0 +1,7 @@
1
+ /** An in-memory multipart upload. Filenames and content types are client supplied. */
2
+ export interface MultipartFile {
3
+ data: Uint8Array;
4
+ filename: string;
5
+ contentType: string;
6
+ size: number;
7
+ }
@@ -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.2.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",
56
- "@counterfact/types": "0.2.0",
57
- "chokidar": "5.0.0",
55
+ "@counterfact/openapi": "0.1.7",
56
+ "@counterfact/types": "0.3.0",
57
+ "chokidar": "6.0.0",
58
58
  "debug": "4.4.3",
59
59
  "prettier": "3.9.10",
60
60
  "typescript": "6.0.3"