@7nohe/openapi-react-query-codegen 4.0.0-beta.6 → 4.0.0-beta.8

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,353 @@
1
+ import { HEADER } from "./emitSdk.mjs";
2
+ import { isEnumDeclaration } from "./emitTypes.mjs";
3
+ import { exampleValue, mockValue } from "./mockValue.mjs";
4
+ import { uniqueName } from "./naming.mjs";
5
+ import { classifyResponses, mediaKind, } from "./operations.mjs";
6
+ import { componentSchemaView, hasObjectKeywords, isNullableSchema, isRequiredOnly, renderSchema, } from "./schema.mjs";
7
+ import { resolveRef } from "./spec.mjs";
8
+ /** Statuses whose response cannot have a body. */
9
+ const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
10
+ /** The methods `http` of MSW has a handler for. */
11
+ const MSW_METHODS = new Set([
12
+ "get",
13
+ "post",
14
+ "put",
15
+ "delete",
16
+ "patch",
17
+ "head",
18
+ "options",
19
+ ]);
20
+ function lowerFirst(name) {
21
+ return name.charAt(0).toLowerCase() + name.slice(1);
22
+ }
23
+ /**
24
+ * Whether the schema is one object type, which `Partial` of it can override
25
+ * property by property. A union is not: a part of one member spread over
26
+ * another member is a value of neither.
27
+ */
28
+ function isPlainObject(doc, schema, depth = 0) {
29
+ const resolved = resolveRef(doc, schema);
30
+ if (!resolved || typeof resolved !== "object" || depth > 16)
31
+ return false;
32
+ if (resolved.oneOf !== undefined ||
33
+ resolved.anyOf !== undefined ||
34
+ resolved.enum !== undefined ||
35
+ resolved.const !== undefined ||
36
+ isNullableSchema(resolved)) {
37
+ return false;
38
+ }
39
+ const members = Array.isArray(resolved.allOf)
40
+ ? resolved.allOf.filter((member) => !isRequiredOnly(member))
41
+ : [];
42
+ if (resolved.type !== undefined && resolved.type !== "object")
43
+ return false;
44
+ if (resolved.type === undefined &&
45
+ !hasObjectKeywords(resolved) &&
46
+ members.length === 0) {
47
+ return false;
48
+ }
49
+ return members.every((member) => isPlainObject(doc, member, depth + 1));
50
+ }
51
+ const PATH_PARAMETER = /\{([^{}]+)\}/g;
52
+ const REGEXP_SYNTAX = /[.*+?^${}()|[\]\\]/;
53
+ /**
54
+ * A regular expression for the fixed text of a path as a request carries it.
55
+ * A URL percent-encodes what is not ASCII (`/café` is requested as
56
+ * `/caf%C3%A9`); what is encoded already stays as it is. A few ASCII
57
+ * characters are encoded by some URL parsers and not by others (`^` is by
58
+ * Node.js 24 and not by 22), so both spellings match. The parser is not
59
+ * asked: the output must not depend on what runs the generator.
60
+ */
61
+ function pathTextPattern(text) {
62
+ return text.replace(/[^\x21-\x7e]|[.*+?^${}()|[\]\\"<>`]/gu, (char) => {
63
+ const literal = REGEXP_SYNTAX.test(char) ? `\\${char}` : char;
64
+ if (/["<>^`{}]/.test(char)) {
65
+ return `(?:${literal}|${encodeURIComponent(char)})`;
66
+ }
67
+ if (char >= "!" && char <= "~")
68
+ return literal;
69
+ // A lone surrogate is sent as the replacement character.
70
+ return encodeURIComponent(char.isWellFormed() ? char : "\uFFFD");
71
+ });
72
+ }
73
+ /**
74
+ * What a handler matches the path with, as an expression. `*` stands for the
75
+ * base URL, so the handlers match wherever the API is.
76
+ *
77
+ * MSW reads `:` and a few other characters in a path as its own syntax, so a
78
+ * path that has one outside its parameters (`/pets:count`) is matched with a
79
+ * regular expression instead, which gives the resolver no named parameters.
80
+ * So is a path whose parameter is followed by another one or by a letter
81
+ * (`/files/{name}{extension}`, `/v{major}beta`): MSW 2 rejects the first, and
82
+ * would take the letters for the rest of the parameter's name.
83
+ */
84
+ function mswPath(path) {
85
+ const fixed = path.replace(PATH_PARAMETER, "");
86
+ if (/^[\w/.~-]*$/.test(fixed) && !/\}[\w{]/.test(path)) {
87
+ return JSON.stringify(`*${path.replace(PATH_PARAMETER, (_match, name) => {
88
+ // A parameter name is made of word characters and starts with none
89
+ // of the digits.
90
+ const safe = name.replace(/\W/g, "_");
91
+ return `:${/^\d/.test(safe) ? "_" : ""}${safe}`;
92
+ })}`);
93
+ }
94
+ const source = path
95
+ .split(PATH_PARAMETER)
96
+ // Every other part is the name of a parameter.
97
+ .map((part, index) => (index % 2 === 1 ? "([^/]+)" : pathTextPattern(part)))
98
+ .join("");
99
+ // As in a path given as text, a trailing slash is only required when the
100
+ // path has one.
101
+ return `new RegExp(${JSON.stringify(`${source}${path.endsWith("/") ? "" : "/?"}$`)})`;
102
+ }
103
+ /**
104
+ * Where a path sorts among the handlers. MSW answers with the first handler
105
+ * that matches, so a segment has to come before a looser one in its place:
106
+ * `/pets/mine` and `/pets/{id}:archive` before `/pets/{id}`.
107
+ */
108
+ function specificity(path) {
109
+ return path
110
+ .split("/")
111
+ .map((segment) => /^\{[^{}]+\}$/.test(segment) ? "2" : segment.includes("{") ? "1" : "0")
112
+ .join("");
113
+ }
114
+ /** The response a handler answers with: the lowest of the successful ones. */
115
+ function pickResponse(operation) {
116
+ // A range (`2XX`) comes after the statuses it stands for. `default` is only
117
+ // ever here alone.
118
+ const rank = (status) => /^\d+$/.test(status) ? Number(status) : 999;
119
+ return [...classifyResponses(operation).responses].sort((a, b) => rank(a.status) - rank(b.status))[0];
120
+ }
121
+ /** The body of a mock that no value can be written for. */
122
+ function noValue(type) {
123
+ return `{} as unknown as ${type}`;
124
+ }
125
+ function declareFunction(name, parameters, type, body) {
126
+ return `export function ${name}(${parameters}): ${type} {\n return ${body};\n}`;
127
+ }
128
+ const DATA_INTRO = `/**
129
+ * Mock data for the schemas and the responses of the API. The values are fixed:
130
+ * an \`example\` or a \`default\` from the specification where it has one, and
131
+ * otherwise the first \`enum\` value or a value made up from the type.
132
+ */`;
133
+ const HANDLERS_INTRO = `/**
134
+ * MSW request handlers for the API. Each answers with the mock of its
135
+ * operation's successful response. Pass a handler another body, or a resolver
136
+ * of your own, to answer with something else:
137
+ *
138
+ * setupWorker(findPetsHandler([]), ...handlers)
139
+ *
140
+ * MSW uses the first handler that matches, so yours go before \`handlers\`.
141
+ */`;
142
+ /** Emit the files of `<output>/mocks`: the mock data and the MSW handlers. */
143
+ export function emitMocks(operations, ctx, options) {
144
+ const { doc } = ctx;
145
+ const readCtx = { ...ctx, mode: "read", onRef: undefined };
146
+ const schemas = (doc.components?.schemas ?? {});
147
+ const warnings = [];
148
+ const used = new Set();
149
+ const typeOf = (key) => `Types.${ctx.names.get(key)}`;
150
+ const mockNames = new Map();
151
+ for (const key of Object.keys(schemas)) {
152
+ mockNames.set(key, uniqueName(`${lowerFirst(ctx.names.get(key))}Mock`, used));
153
+ }
154
+ // The mocks call each other, so a schema that holds itself would never
155
+ // return. Schemas are built depth first, and a reference back to one that is
156
+ // still being built is cut: left out, an empty array or `null`, whichever the
157
+ // schema allows there. A mock only ever calls mocks finished before it.
158
+ const bodies = new Map();
159
+ const building = new Set();
160
+ const unbuildable = [];
161
+ let attempts = 0;
162
+ const valueCtx = {
163
+ schema: readCtx,
164
+ callMock: (key) => buildComponent(key) === undefined
165
+ ? undefined
166
+ : `${mockNames.get(key)}()`,
167
+ enumCast: (key) => options.enums === "typescript" &&
168
+ isEnumDeclaration(schemas[key], options.enums)
169
+ ? typeOf(key)
170
+ : undefined,
171
+ };
172
+ function buildComponent(key) {
173
+ const done = bodies.get(key);
174
+ if (done !== undefined)
175
+ return done;
176
+ if (building.has(key))
177
+ return undefined;
178
+ building.add(key);
179
+ attempts += 1;
180
+ const view = componentSchemaView(schemas[key], key, readCtx);
181
+ let body = mockValue(view, valueCtx, " ");
182
+ building.delete(key);
183
+ if (body === undefined) {
184
+ // Under another schema the cut can fall where this one cannot take it,
185
+ // so it is tried again from the top. The limit keeps a specification
186
+ // that is full of such schemas from being built over and over.
187
+ const retry = attempts <= Object.keys(schemas).length * 20;
188
+ if (building.size > 0 && retry)
189
+ return undefined;
190
+ unbuildable.push(key);
191
+ body = noValue(typeOf(key));
192
+ }
193
+ else {
194
+ const cast = valueCtx.enumCast(key);
195
+ if (cast !== undefined)
196
+ body = `${body} as ${cast}`;
197
+ }
198
+ bodies.set(key, body);
199
+ return body;
200
+ }
201
+ const dataBlocks = [];
202
+ for (const key of Object.keys(schemas)) {
203
+ const body = buildComponent(key);
204
+ const name = mockNames.get(key);
205
+ const type = typeOf(key);
206
+ const view = componentSchemaView(schemas[key], key, readCtx);
207
+ if (!unbuildable.includes(key) && isPlainObject(doc, view)) {
208
+ const base = body === "{}"
209
+ ? ""
210
+ : body.startsWith("{\n")
211
+ ? body.slice(2, body.lastIndexOf("\n"))
212
+ : ` ...${body},`;
213
+ const literal = `{\n${base === "" ? "" : `${base}\n`} ...overrides,\n }`;
214
+ dataBlocks.push(declareFunction(name, `overrides?: Partial<${type}>`, type, literal));
215
+ }
216
+ else {
217
+ dataBlocks.push(declareFunction(name, "", type, body));
218
+ }
219
+ }
220
+ if (unbuildable.length > 0) {
221
+ warnings.push(`--mock: no value can be written for these schemas: they require themselves, or put schemas together that no value is one of all of. Their mocks return an empty object:\n${unbuildable
222
+ .map((key) => ` - ${key}`)
223
+ .join("\n")}`);
224
+ }
225
+ const sorted = operations
226
+ .map((operation, index) => ({ operation, index }))
227
+ .sort((a, b) => {
228
+ const [left, right] = [a, b].map((entry) => specificity(entry.operation.path));
229
+ return left < right ? -1 : left > right ? 1 : a.index - b.index;
230
+ })
231
+ .map((entry) => entry.operation);
232
+ const helpers = new Set();
233
+ const handlerBlocks = [];
234
+ const handlerNames = [];
235
+ const skipped = [];
236
+ let usesTypes = false;
237
+ for (const operation of sorted) {
238
+ if (!MSW_METHODS.has(operation.method)) {
239
+ skipped.push(`${operation.method.toUpperCase()} ${operation.path}`);
240
+ continue;
241
+ }
242
+ const response = pickResponse(operation);
243
+ const status = response && /^\d+$/.test(response.status) ? Number(response.status) : 200;
244
+ const kind = response?.mediaType
245
+ ? mediaKind(response.mediaType)
246
+ : undefined;
247
+ const hasBody = response?.schema !== undefined &&
248
+ operation.method !== "head" &&
249
+ !NULL_BODY_STATUSES.has(status) &&
250
+ (kind === "json" || kind === "text") &&
251
+ // A body typed `unknown` has nothing for a mock to follow.
252
+ renderSchema(response.schema, readCtx) !== "unknown";
253
+ const name = `${operation.functionName}Handler`;
254
+ handlerNames.push(name);
255
+ const path = mswPath(operation.path);
256
+ const call = `http.${operation.method}`;
257
+ if (!response || !hasBody) {
258
+ helpers.add("empty");
259
+ handlerBlocks.push(`export const ${name} = (override?: HttpResponseResolver) =>\n ${call}(${path}, override ?? empty(${status}));`);
260
+ continue;
261
+ }
262
+ const statusIndex = /^\d+$/.test(response.status)
263
+ ? response.status
264
+ : JSON.stringify(response.status);
265
+ const type = `Types.${operation.typeNames.responses}[${statusIndex}]`;
266
+ const mockName = uniqueName(`${operation.functionName}ResponseMock`, used);
267
+ const value = (response.example === undefined
268
+ ? undefined
269
+ : exampleValue(response.schema, response.example, valueCtx, " ")) ??
270
+ mockValue(response.schema, valueCtx, " ");
271
+ dataBlocks.push(declareFunction(mockName, "", type, value ?? noValue(type)));
272
+ usesTypes = true;
273
+ helpers.add("answer");
274
+ helpers.add(kind === "text" ? "text" : "json");
275
+ handlerBlocks.push(`export const ${name} = (override?: ${type} | HttpResponseResolver) =>\n ${call}(\n ${path},\n answer(override, mocks.${mockName}, ${kind === "text" ? "text" : "json"}(${status})),\n );`);
276
+ }
277
+ if (skipped.length > 0) {
278
+ warnings.push(`--mock: MSW has no handler for these methods, so the operations are left out:\n${skipped
279
+ .map((where) => ` - ${where}`)
280
+ .join("\n")}`);
281
+ }
282
+ const { ext } = options;
283
+ const typesImport = `import type * as Types from "../requests/types.gen${ext}";`;
284
+ const data = [
285
+ HEADER.trimEnd(),
286
+ DATA_INTRO,
287
+ // With nothing to mock the file still has to be a module.
288
+ ...(dataBlocks.length > 0 ? [typesImport, ...dataBlocks] : ["export {};"]),
289
+ ].join("\n\n");
290
+ const mswModule = options.mswMajor === 2 ? "msw" : "msw/http";
291
+ const hasHandlers = handlerBlocks.length > 0;
292
+ const mswImport = hasHandlers
293
+ ? `import {\n type HttpHandler,\n HttpResponse,\n type HttpResponseResolver,\n http,\n} from "${mswModule}";`
294
+ : `import type { HttpHandler } from "${mswModule}";`;
295
+ const imports = [
296
+ mswImport,
297
+ ...(usesTypes
298
+ ? [typesImport, `import * as mocks from "./data${ext}";`]
299
+ : []),
300
+ ].join("\n");
301
+ const helperBlocks = [];
302
+ if (helpers.has("answer")) {
303
+ helperBlocks.push(`/** Answers with \`override\` when it is a body, and lets it answer when it is a resolver. */
304
+ const answer = <T>(
305
+ override: T | HttpResponseResolver | undefined,
306
+ mock: () => T,
307
+ respond: (body: T) => Response,
308
+ ): HttpResponseResolver =>
309
+ typeof override === "function"
310
+ ? (override as HttpResponseResolver)
311
+ : () => respond(override === undefined ? mock() : (override as T));`);
312
+ }
313
+ if (helpers.has("json")) {
314
+ helperBlocks.push(`const json = (status: number) => (body: unknown) =>
315
+ HttpResponse.json(body as Parameters<typeof HttpResponse.json>[0], {
316
+ status,
317
+ });`);
318
+ }
319
+ if (helpers.has("text")) {
320
+ helperBlocks.push(`const text = (status: number) => (body: unknown) =>
321
+ HttpResponse.text(String(body), { status });`);
322
+ }
323
+ if (helpers.has("empty")) {
324
+ helperBlocks.push(`const empty =
325
+ (status: number): HttpResponseResolver =>
326
+ () =>
327
+ new HttpResponse(null, { status });`);
328
+ }
329
+ const list = hasHandlers
330
+ ? `export const handlers: HttpHandler[] = [\n${handlerNames
331
+ .map((name) => ` ${name}(),`)
332
+ .join("\n")}\n];`
333
+ : "export const handlers: HttpHandler[] = [];";
334
+ const handlers = [
335
+ HEADER.trimEnd(),
336
+ HANDLERS_INTRO,
337
+ imports,
338
+ ...helperBlocks,
339
+ ...handlerBlocks,
340
+ list,
341
+ ].join("\n\n");
342
+ return {
343
+ files: [
344
+ { name: "data.ts", content: `${data}\n` },
345
+ { name: "handlers.ts", content: `${handlers}\n` },
346
+ {
347
+ name: "index.ts",
348
+ content: `${HEADER}\nexport * from "./data${ext}";\nexport * from "./handlers${ext}";\n`,
349
+ },
350
+ ],
351
+ warnings,
352
+ };
353
+ }
@@ -196,9 +196,14 @@ export function emitSdk(doc, operations, options) {
196
196
  blocks.push(code);
197
197
  }
198
198
  const typeImports = [...used].sort().join(", ");
199
+ // Only the operations use `client` and `RequestResult`, and an import that
200
+ // nothing uses is an error under `noUnusedLocals`.
201
+ const hasOperations = blocks.length > 0;
199
202
  const imports = [
200
- `import { client } from "./client.gen${options.ext}";`,
201
- `import type { Client, Options as Options2, RequestResult, TDataShape } from "./runtime.gen${options.ext}";`,
203
+ ...(hasOperations
204
+ ? [`import { client } from "./client.gen${options.ext}";`]
205
+ : []),
206
+ `import type { Client, Options as Options2, ${hasOperations ? "RequestResult, " : ""}TDataShape } from "./runtime.gen${options.ext}";`,
202
207
  ];
203
208
  const transformers = [...(options.transformers?.values() ?? [])].sort();
204
209
  if (transformers.length > 0) {
@@ -214,7 +219,7 @@ export function emitSdk(doc, operations, options) {
214
219
  ${docComment({ description: "You can provide a client instance returned by `createClient()` instead of\nindividual options. This might be also useful if you want to implement a\ncustom client." }, " ")} client?: Client;
215
220
  ${docComment({ description: "You can pass arbitrary values through the `meta` object. This can be\nused to access values that aren't defined as part of the SDK function." }, " ")} meta?: Record<string, unknown>;
216
221
  };`;
217
- return `${HEADER}\n${imports.join("\n")}\n\n${optionsType}\n\n${blocks.join("\n\n")}\n`;
222
+ return `${HEADER}\n${[imports.join("\n"), optionsType, ...blocks].join("\n\n")}\n`;
218
223
  }
219
224
  /** The option that holds the base URL, spelled the way each client does. */
220
225
  export function baseUrlKey(kind) {
@@ -1,7 +1,7 @@
1
1
  import { type ClientKind } from "./emitSdk.mjs";
2
2
  import { type OperationIR } from "./operations.mjs";
3
3
  import { type SchemaCtx } from "./schema.mjs";
4
- import type { Doc } from "./spec.mjs";
4
+ import type { Doc, Json } from "./spec.mjs";
5
5
  export type EnumsMode = "javascript" | "typescript" | false | undefined;
6
6
  export type EmittedTypes = {
7
7
  content: string;
@@ -10,6 +10,11 @@ export type EmittedTypes = {
10
10
  };
11
11
  /** First server URL with its variables replaced by their defaults. */
12
12
  export declare function getBaseUrl(doc: Doc): string | undefined;
13
+ /**
14
+ * Whether a component schema is declared as an enum of its own (`--enums`): a
15
+ * TypeScript enum, or an object of its values with the type of them.
16
+ */
17
+ export declare function isEnumDeclaration(schema: Json, enumsMode: EnumsMode): boolean;
13
18
  export declare function emitTypes(operations: OperationIR[], ctx: SchemaCtx, options: {
14
19
  enums?: EnumsMode;
15
20
  clientKind: ClientKind;
@@ -103,19 +103,28 @@ function enumKey(name) {
103
103
  // `01` would be an octal literal, which TypeScript rejects.
104
104
  return /^(0|[1-9]\d*)$/.test(name) ? name : propertyKey(name);
105
105
  }
106
+ /**
107
+ * Whether a component schema is declared as an enum of its own (`--enums`): a
108
+ * TypeScript enum, or an object of its values with the type of them.
109
+ */
110
+ export function isEnumDeclaration(schema, enumsMode) {
111
+ if (!enumsMode)
112
+ return false;
113
+ const values = Array.isArray(schema?.enum) ? schema.enum : [];
114
+ const isMember = (value) => typeof value === "string" || typeof value === "number";
115
+ // A TypeScript enum can only hold strings and numbers, an object anything.
116
+ return (values.some((value) => value !== null) &&
117
+ values.every((value) => isMember(value) ||
118
+ (enumsMode === "javascript" &&
119
+ (value === null || typeof value === "boolean"))));
120
+ }
106
121
  function emitComponentSchema(schema, key, name, ctx, enumsMode) {
107
122
  const comment = docComment({
108
123
  description: schemaDescription(schema),
109
124
  deprecated: schema?.deprecated,
110
125
  });
111
126
  const values = Array.isArray(schema?.enum) ? schema.enum : [];
112
- const isMember = (value) => typeof value === "string" || typeof value === "number";
113
- // A TypeScript enum can only hold strings and numbers, an object anything.
114
- const isLiteralEnum = values.some((value) => value !== null) &&
115
- values.every((value) => isMember(value) ||
116
- (enumsMode === "javascript" &&
117
- (value === null || typeof value === "boolean")));
118
- if (enumsMode && isLiteralEnum) {
127
+ if (isEnumDeclaration(schema, enumsMode)) {
119
128
  const used = new Set();
120
129
  const memberNames = schema["x-enum-varnames"] ?? schema["x-enumNames"];
121
130
  const descriptions = schema["x-enum-descriptions"];
@@ -1,10 +1,13 @@
1
1
  import type { GeneratedFile, OperationInfo } from "../types.mjs";
2
+ import { type MswMajor } from "./emitMocks.mjs";
2
3
  import { type SchemasMode } from "./emitSchemas.mjs";
3
4
  import { type ClientKind } from "./emitSdk.mjs";
4
5
  import { type EnumsMode } from "./emitTypes.mjs";
6
+ export type { MswMajor } from "./emitMocks.mjs";
5
7
  export type { SchemasMode } from "./emitSchemas.mjs";
6
8
  export type { ClientKind } from "./emitSdk.mjs";
7
9
  export type { EnumsMode } from "./emitTypes.mjs";
10
+ export { detectMswMajor } from "./msw.mjs";
8
11
  export { SpecError } from "./spec.mjs";
9
12
  export { detectImportExtension, findNearestTsConfigPath } from "./tsconfig.mjs";
10
13
  export interface ClientGenOptions {
@@ -14,6 +17,13 @@ export interface ClientGenOptions {
14
17
  enums?: EnumsMode;
15
18
  /** `.js` for Node16/NodeNext module resolution, otherwise empty. */
16
19
  importExtension: "" | ".js";
20
+ /**
21
+ * Also generate mock data and MSW request handlers, written for this major
22
+ * version of MSW. Off when not set.
23
+ */
24
+ mocks?: {
25
+ mswMajor: MswMajor;
26
+ };
17
27
  /** Name operations after the HTTP method and path instead of operationId. */
18
28
  noOperationId?: boolean;
19
29
  /** Query parameter used for pagination. */
@@ -31,6 +41,8 @@ export interface ClientGenOptions {
31
41
  }
32
42
  export interface GeneratedClient {
33
43
  files: GeneratedFile[];
44
+ /** The files of the mocks directory, when `mocks` is set. */
45
+ mockFiles?: GeneratedFile[];
34
46
  operations: OperationInfo[];
35
47
  /** Type names exported from `types.gen.ts`. */
36
48
  modelNames: string[];
@@ -1,5 +1,6 @@
1
1
  import { mkdir, readFile, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import { emitMocks } from "./emitMocks.mjs";
3
4
  import { emitSchemas } from "./emitSchemas.mjs";
4
5
  import { emitClientFile, emitIndexFile, emitSdk, emitServicesShim, optionsAreOptional, } from "./emitSdk.mjs";
5
6
  import { emitTransformers } from "./emitTransformers.mjs";
@@ -8,6 +9,7 @@ import { capitalizeFirst } from "./naming.mjs";
8
9
  import { buildSchemaNames, buildWritableNames, collectOperations, schemaPrimitiveKind, } from "./operations.mjs";
9
10
  import { renderSchema } from "./schema.mjs";
10
11
  import { bundleExternalRefs, loadSpec } from "./spec.mjs";
12
+ export { detectMswMajor } from "./msw.mjs";
11
13
  export { SpecError } from "./spec.mjs";
12
14
  export { detectImportExtension, findNearestTsConfigPath } from "./tsconfig.mjs";
13
15
  const RUNTIME_FILES = {
@@ -119,9 +121,19 @@ export async function generateClient(options) {
119
121
  if (schemas !== undefined) {
120
122
  files.push({ name: "schemas.gen.ts", content: schemas });
121
123
  }
124
+ const mocks = options.mocks
125
+ ? emitMocks(operations, ctx, {
126
+ mswMajor: options.mocks.mswMajor,
127
+ enums: options.enums,
128
+ ext,
129
+ })
130
+ : undefined;
131
+ if (mocks)
132
+ warnings.push(...mocks.warnings);
122
133
  const emittedTypes = new Set(types.exportedNames);
123
134
  return {
124
135
  files,
136
+ mockFiles: mocks?.files,
125
137
  operations: operations.map((operation) => toOperationInfo(operation, ctx, options.pageParam, emittedTypes)),
126
138
  modelNames: types.exportedNames,
127
139
  serviceNames: operations.map((operation) => operation.functionName),
@@ -0,0 +1,34 @@
1
+ import { type SchemaCtx } from "./schema.mjs";
2
+ import { type Json } from "./spec.mjs";
3
+ /**
4
+ * What the values of a mock are built with. A value is a TypeScript expression
5
+ * of the type `renderSchema` gives the same schema, so the two read a schema
6
+ * the same way.
7
+ */
8
+ export interface MockValueCtx {
9
+ /** The context the response types are rendered with (`read` mode). */
10
+ schema: SchemaCtx;
11
+ /**
12
+ * The call of a component schema's mock function. Undefined while that mock
13
+ * is being built: a value that held itself would never end.
14
+ */
15
+ callMock: (key: string) => string | undefined;
16
+ /**
17
+ * The type to assert a literal of a component schema to, when the schema is
18
+ * a TypeScript enum (which no literal is assignable to).
19
+ */
20
+ enumCast: (key: string) => string | undefined;
21
+ }
22
+ /**
23
+ * An expression for a value of the schema, written for a place at `indent`.
24
+ * Undefined when no value ends: the schema allows none, or holds itself
25
+ * through a mock that is still being built.
26
+ */
27
+ export declare function mockValue(schema: Json, ctx: MockValueCtx, indent?: string, seen?: ReadonlySet<string>): string | undefined;
28
+ /**
29
+ * An example from the specification as an expression of the schema's type, or
30
+ * undefined when it is not a value of that type. Examples drift from their
31
+ * schemas, and one that did would not compile. A composed schema is not
32
+ * checked: its example is passed over, and the value is made up instead.
33
+ */
34
+ export declare function exampleValue(schema: Json, value: Json, ctx: MockValueCtx, indent?: string, depth?: number): string | undefined;