@7nohe/openapi-react-query-codegen 4.0.0-beta.7 → 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.
package/AGENTS.md CHANGED
@@ -11,6 +11,7 @@ This file has two parts:
11
11
 
12
12
  1. a TypeScript HTTP client (types, one function per operation and a small fetch or axios runtime) in `<output>/requests/`
13
13
  2. TanStack Query v5 hooks and helpers on top of that client in `<output>/queries/`
14
+ 3. with `--mock msw`, mock data and MSW request handlers in `<output>/mocks/`
14
15
 
15
16
  Docs: https://orqc.7nohe.dev (summary for LLMs: https://orqc.7nohe.dev/llms.txt)
16
17
 
@@ -40,8 +41,9 @@ Add a script and run it whenever the spec changes:
40
41
  | `-i, --input <path\|url\|content>` | (required) | OpenAPI 3.0/3.1 spec |
41
42
  | `-o, --output <dir>` | `openapi` | `requests/` and `queries/` are created inside |
42
43
  | `-c, --client <name>` | `fetch` | or `axios` |
43
- | `--format <biome\|prettier>` | none | formats `queries/` only |
44
- | `--lint <biome\|eslint>` | none | lints/fixes `queries/` only |
44
+ | `--format <biome\|prettier>` | none | formats `queries/` (and `mocks/`) only |
45
+ | `--lint <biome\|eslint>` | none | lints/fixes `queries/` (and `mocks/`) only |
46
+ | `--mock <msw>` | off | also generate mock data and MSW handlers into `mocks/` (see below) |
45
47
  | `--enums <javascript\|typescript>` | none | emit enum objects |
46
48
  | `--useDateType` | off | `Date` for `date`/`date-time`, converted in successful responses |
47
49
  | `--noOperationId` | off | derive names from paths instead of `operationId` |
@@ -78,6 +80,8 @@ Pass the **same flags** every time (keep them in the package.json script). Diffe
78
80
  └── transformers.gen.ts # date conversion (only with --useDateType)
79
81
  ```
80
82
 
83
+ With `--mock msw` there is also `<output>/mocks/`: `data.ts` (mock functions), `handlers.ts` (MSW handlers) and `index.ts`.
84
+
81
85
  Never edit generated files; change the spec or the flags and regenerate. Whether to commit the output is the project's choice. If it is committed, add the `--check` step below to CI.
82
86
 
83
87
  ### Using the generated code
@@ -123,6 +127,28 @@ mutate({ body: { name: "Fluffy" } });
123
127
 
124
128
  Wrap the app in TanStack Query's `QueryClientProvider` as usual.
125
129
 
130
+ ### Mocks: `--mock msw`
131
+
132
+ ```bash
133
+ orqc -i ./openapi.yaml -o ./src/openapi --mock msw
134
+ ```
135
+
136
+ Writes `<output>/mocks/` and needs `msw` (2 or 3) in the project. For an operation `findPets` and a schema `Pet` it exports:
137
+
138
+ - `findPetsHandler(override?)`: an MSW handler that answers with the operation's lowest successful status. `override` is a body of the response type, or an MSW resolver for anything else (an error, a body that depends on the request).
139
+ - `handlers`: every handler, ordered so that `/pets/mine` matches before `/pets/{id}`.
140
+ - `findPetsResponseMock()` and `petMock(overrides?)`: the mock data, typed by `requests/types.gen.ts`. `overrides` exists for object schemas only.
141
+
142
+ ```ts
143
+ import { setupServer } from "msw/node"; // or setupWorker from "msw/browser"
144
+ import { findPetsHandler, handlers, petMock } from "./openapi/mocks";
145
+
146
+ const server = setupServer(...handlers);
147
+ server.use(findPetsHandler([petMock({ name: "Momo" })])); // own handlers win: MSW takes the first match
148
+ ```
149
+
150
+ The values are fixed, not random: the specification's `example`/`default`, else the first `enum` value, else a value made up from the type. To change the data everywhere, add `example`s to the specification and regenerate; do not edit `mocks/`. The handlers keep no state and ignore the request, so pagination, errors and "created items show up in the list" need a handler of your own.
151
+
126
152
  ### Looking an operation up: `--agentsMd`
127
153
 
128
154
  The generated files can be very large. Do not read them whole: an operation's function, hook and types each start a line, so `grep` finds them.
@@ -144,7 +170,7 @@ With `--agentsMd` in the codegen script, the generator keeps these instructions,
144
170
  orqc -i ./openapi.yaml -o ./src/openapi --check
145
171
  ```
146
172
 
147
- Generates into a temporary directory (`.openapi-rq-check-*` inside `<output>/queries`, removed afterwards), compares it with `<output>/requests` and `<output>/queries`, and changes no existing file. `--format`/`--lint` rules that target the output directory by path also apply to the temporary copy; a rule that names an exact file or depth from the project root (`src/openapi/queries/*.ts`) does not, so write such rules as `src/openapi/queries/**`. Each file is `added` (would be created), `modified` or `removed` (no longer generated).
173
+ Generates into a temporary directory (`.openapi-rq-check-*` inside `<output>/queries`, removed afterwards), compares it with `<output>/requests` and `<output>/queries` (and `<output>/mocks` with `--mock`), and changes no existing file. `--format`/`--lint` rules that target the output directory by path also apply to the temporary copy; a rule that names an exact file or depth from the project root (`src/openapi/queries/*.ts`) does not, so write such rules as `src/openapi/queries/**`. Each file is `added` (would be created), `modified` or `removed` (no longer generated).
148
174
 
149
175
  The `queries/` headers include the package version, so after upgrading this package `--check` fails until you regenerate. Upgrade and regenerate in the same change.
150
176
 
@@ -219,10 +245,12 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
219
245
  - A hook builder takes the names it declares and refers to from `hookNames(op)` (`src/hooks/hookNames.mts`), never from the operation's name directly: `settleHookNames` numbers a name that its file already imports or declares, and the files are then built again with those names.
220
246
  - A hook builder declares what its statement needs from the generated client: `service` (the SDK function) and `models` (types from `types.gen`). The fixed names (TanStack Query, `Options`, `Common`, `AxiosError`) are imported when the code mentions them, which is only safe because the client generator reserves them. When hook code starts using a new name, add it to `RESERVED_TYPE_NAMES` or `RESERVED_FUNCTION_NAMES` and to the list in `tests/hooks/imports.test.ts`.
221
247
  - The generated hooks rely on a small SDK contract: `Options<XData, ThrowOnError>` exported from `sdk.gen`, calls returning `{ data }` and rejecting when `throwOnError` is set, and the `XData` / `XError` type names. Keep it in sync with `src/client/emitSdk.mts` and the runtimes in `src/client/runtime/`.
248
+ - The mocks (`src/client/emitMocks.mts`, `mockValue.mts`) are typed by `types.gen.ts`, so a value has to be one `renderSchema` gives a type for: `mockValue` reads a schema with the same helpers (`componentSchemaView`, `inheritedRequired`, `discriminatorValues`). When the type of a schema changes, change its value with it; `tests/client/mocksCompile.test.ts` compiles the mocks of every specification under `tests/inputs` and fails when the two disagree. An `example` is only used after `exampleValue` has checked it against the schema.
222
249
  - The runtimes (`src/client/runtime/*.runtime.ts`) are plain TypeScript that is copied verbatim into users' projects. Keep them dependency-free (axios aside), strict-mode clean, and free of syntax that needs a newer TypeScript than the generated code supports. `scripts/copy-runtime.mjs` ships them next to the compiled generator.
223
250
 
224
251
  ### Dependencies
225
252
  - Runtime dependencies are deliberately few (`cross-spawn`, `yaml`). Adding one needs a reason; the generator replaced `@hey-api/openapi-ts` to cut the supply-chain surface.
253
+ - `msw` is a devDependency only, for the tests that compile and run the generated handlers. The generated code imports it from the user's project, so it is neither a dependency nor a peer dependency of this package.
226
254
 
227
255
  ### Agent-Specific Notes
228
256
  - The generators build source text as strings. After changing one, run the tests that compile the generated output (`tests/createSource.test.ts`, `tests/client/`) to confirm it is still valid TypeScript.
package/README.md CHANGED
@@ -1,10 +1,18 @@
1
- # OpenAPI React Query Codegen
1
+ # OpenAPI React Query Codegen (orqc)
2
2
 
3
- > Code generator for [TanStack Query (React Query)](https://tanstack.com/query) based on your OpenAPI schema — `queryOptions` factories following the official TanStack Query v5 pattern, plus ready-to-use hooks, prefetch, ensure, suspense, and infinite query helpers.
3
+ > Generate [TanStack Query (React Query)](https://tanstack.com/query) code from your OpenAPI spec: `queryOptions` factories following the official TanStack Query v5 pattern, ready-to-use hooks, prefetch, ensure, suspense and infinite query helpers, and the typed fetch or axios client they call.
4
4
 
5
- [![npm version](https://badge.fury.io/js/%407nohe%2Fopenapi-react-query-codegen.svg)](https://badge.fury.io/js/%407nohe%2Fopenapi-react-query-codegen)
5
+ [![npm](https://img.shields.io/npm/v/%407nohe%2Fopenapi-react-query-codegen?label=npm)](https://www.npmjs.com/package/@7nohe/openapi-react-query-codegen)
6
+ [![npm beta](https://img.shields.io/npm/v/%407nohe%2Fopenapi-react-query-codegen/beta?label=beta)](https://www.npmjs.com/package/@7nohe/openapi-react-query-codegen?activeTab=versions)
7
+ [![npm downloads](https://img.shields.io/npm/dm/%407nohe%2Fopenapi-react-query-codegen)](https://www.npmjs.com/package/@7nohe/openapi-react-query-codegen)
8
+ [![license](https://img.shields.io/npm/l/%407nohe%2Fopenapi-react-query-codegen)](./LICENSE)
6
9
 
7
- 📖 **[Documentation](https://orqc.7nohe.dev)** · [Migrating to v3](https://orqc.7nohe.dev/guides/migrating-to-v3/) · [Coming from openapi-react-query](https://orqc.7nohe.dev/guides/migrating-from-openapi-react-query/)
10
+ 📖 **[Documentation](https://orqc.7nohe.dev)** · [Getting started](https://orqc.7nohe.dev/guides/introduction/) · [Migrating to v4](https://orqc.7nohe.dev/guides/migrating-to-v4/) · [Coming from openapi-react-query](https://orqc.7nohe.dev/guides/migrating-from-openapi-react-query/) · [Benchmarks](https://orqc.7nohe.dev/guides/benchmarks/)
11
+
12
+ <picture>
13
+ <source media="(prefers-color-scheme: dark)" srcset="./.github/assets/how-it-works-dark.svg">
14
+ <img alt="The findPets operation of an OpenAPI document. Running npx @7nohe/orqc@beta -i openapi.yaml generates useFindPets, findPetsOptions, useFindPetsSuspense, prefetchUseFindPets and UseFindPetsKeyFn in openapi/queries, plus a typed client in openapi/requests. An app then calls useFindPets." src="./.github/assets/how-it-works-light.svg" width="880">
15
+ </picture>
8
16
 
9
17
  ## Features
10
18
 
@@ -13,6 +21,7 @@
13
21
  - **SSR helpers**: `prefetchQuery`, `prefetchInfiniteQuery`, and `ensureQueryData` functions per operation — ready for Next.js App Router hydration
14
22
  - **Hierarchical query keys** with exported key constants and functions: invalidate one exact query, all infinite pages of an operation, or every cache entry of an operation with a single prefix
15
23
  - **Pure TypeScript client** (types, SDK functions and a small fetch or axios runtime) generated from the same OpenAPI 3.0/3.1 document — no separate client generator to install
24
+ - **MSW mocks from the same spec** (`--mock msw`): typed mock data and a request handler per operation, with fixed values taken from the spec's examples — build the frontend before the backend exists, and reuse the handlers in tests
16
25
  - **CI- and agent-friendly**: `--check` fails CI when committed output is out of date, `--json` prints errors as machine-readable JSON, `--agentsMd` keeps a guide in your `AGENTS.md` that lets a coding agent look one operation up instead of reading the generated files, and the package ships an [`AGENTS.md`](./AGENTS.md) for coding agents
17
26
 
18
27
  ## Quick start
@@ -20,11 +29,31 @@
20
29
  > [!NOTE]
21
30
  > v4 is in beta, and this README describes it. Install it with `@beta`; a plain `npm install` still gets v3, whose README and docs are in the [`v3` branch](https://github.com/7nohe/openapi-react-query-codegen/tree/v3). What changes from v3 is in [Migrating to v4](https://orqc.7nohe.dev/guides/migrating-to-v4/).
22
31
 
32
+ Try it without installing:
33
+
34
+ ```bash
35
+ npx @7nohe/orqc@beta -i ./petstore.yaml
36
+ ```
37
+
38
+ Then add it to your project, next to TanStack Query:
39
+
23
40
  ```bash
24
41
  npm install -D @7nohe/openapi-react-query-codegen@beta
25
- npx orqc -i ./petstore.yaml
42
+ npm install @tanstack/react-query
43
+ ```
44
+
45
+ Keep the command in a `package.json` script. A script only runs the version installed in the project, so the output always matches your lockfile:
46
+
47
+ ```json
48
+ { "scripts": { "codegen": "orqc -i ./petstore.yaml" } }
26
49
  ```
27
50
 
51
+ ```bash
52
+ npm run codegen
53
+ ```
54
+
55
+ This writes the client to `openapi/requests/` and the TanStack Query code to `openapi/queries/` (change the folder with `-o`):
56
+
28
57
  ```tsx
29
58
  import { useQuery } from "@tanstack/react-query";
30
59
  import { findPetsOptions } from "./openapi/queries";
@@ -35,7 +64,16 @@ function Pets() {
35
64
  }
36
65
  ```
37
66
 
38
- See the [documentation](https://orqc.7nohe.dev) for CLI options, SSR recipes, and infinite query usage.
67
+ See the [documentation](https://orqc.7nohe.dev) for [CLI options](https://orqc.7nohe.dev/guides/cli-options/), [usage](https://orqc.7nohe.dev/guides/usage/) (SSR, infinite queries, mutations), [mocking with MSW](https://orqc.7nohe.dev/guides/mocking/) and [CI and coding agents](https://orqc.7nohe.dev/guides/ci-and-agents/).
68
+
69
+ ## Examples
70
+
71
+ | Example | Folder |
72
+ |---|---|
73
+ | [Vite + React](https://orqc.7nohe.dev/examples/vite-react/) | [`examples/react-app`](./examples/react-app) |
74
+ | [Next.js (App Router)](https://orqc.7nohe.dev/examples/nextjs/) | [`examples/nextjs-app`](./examples/nextjs-app) |
75
+ | [TanStack Router](https://orqc.7nohe.dev/examples/tanstack-router/) | [`examples/tanstack-router-app`](./examples/tanstack-router-app) |
76
+ | [React Router](https://orqc.7nohe.dev/examples/react-router/) | [`examples/react-router-app`](./examples/react-router-app) |
39
77
 
40
78
  > [!IMPORTANT]
41
79
  > This project publishes only the scoped **`@7nohe/openapi-react-query-codegen`** and its short name **`@7nohe/orqc`**. The unscoped `openapi-react-query-codegen` and `openapi-rq` and the copies under other scopes on npm are published by third parties, not by this project.
@@ -49,10 +87,15 @@ See the [documentation](https://orqc.7nohe.dev) for CLI options, SSR recipes, an
49
87
  | SSR helpers (`prefetchQuery` / `prefetchInfiniteQuery` / `ensureQueryData`) | ✅ | ❌ | Partial (`usePrefetch`) | Not provided (use `queryOptions`) |
50
88
  | Hierarchical query keys for granular invalidation | ✅ | ✅ (tags) | Partial | Not documented |
51
89
  | Stable release line | ✅ SemVer | pre-1.0, frequent breaking changes | ✅ | ⚠️ upstream openapi-typescript is in [maintenance mode](https://github.com/openapi-ts/openapi-typescript/issues/2874) |
52
- | MSW mock generation | ❌ (out of scope) | ❌ | ✅ | ❌ |
90
+ | MSW mock generation | ✅ (`--mock msw`, fixed values) | ❌ | ✅ (random values with Faker) | ❌ |
53
91
  | Vue / Solid / Svelte / Angular | ❌ React-focused | ✅ | ✅ | ❌ |
92
+ | Generation time, GitHub REST API (1,272 operations)¹ | **0.46 s** | 2.98 s | 4.31 s | 2.10 s |
93
+ | Packages added by installing the generator¹ | **9** (2.1 MB) | 51 (10.8 MB) | 89 (101.5 MB) | 35 (20.5 MB) |
94
+ | Type errors in the generated code, Stripe / GitHub APIs¹ | **0 / 0** | 274 / 0 | 219 / 1 | 0 / 0 |
95
+
96
+ ¹ Measured on 2026-11-13 on an Apple M2 with Node.js 24 (generation time is the median wall-clock time of the CLI), with 4.0.0-beta.4, `@hey-api/openapi-ts` 0.99.0, Orval 8.46.0 and openapi-typescript 7.13.0 + openapi-react-query 0.5.4. Methods, the other specifications and type-checking times are on the [Benchmarks](https://orqc.7nohe.dev/guides/benchmarks/) page; the scripts are in [`benchmarks/`](./benchmarks).
54
97
 
55
- **Scope**: this library is deliberately React-focused and does not generate API mocks — use Orval if MSW mocks are your priority, or the hey-api plugin if you need non-React frameworks.
98
+ **Scope**: this library is deliberately React-focused — use the hey-api plugin if you need non-React frameworks. Its [MSW mocks](https://orqc.7nohe.dev/guides/mocking/) answer with fixed values taken from the spec and keep no state; use Orval if you want randomly generated mock data.
56
99
 
57
100
  **Coming from openapi-typescript / openapi-fetch / openapi-react-query?** See the [migration guide](https://orqc.7nohe.dev/guides/migrating-from-openapi-react-query/).
58
101
 
@@ -67,6 +110,10 @@ The client generator is part of this package, so the generated `requests/` direc
67
110
  - `commander` 12–15 (peer dependency)
68
111
  - TypeScript 5.x, 6.x or 7.x to compile the generated code. It is not a peer dependency: the generator does not use the `typescript` package.
69
112
 
113
+ ## Contributing
114
+
115
+ Issues and pull requests are welcome. See the [contributing guide](https://orqc.7nohe.dev/contributing/) for the development setup.
116
+
70
117
  ## License
71
118
 
72
- MIT
119
+ [MIT](./LICENSE)
package/dist/check.mjs CHANGED
@@ -3,11 +3,21 @@ import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
5
  import { agentsFilePath, checkAgentsBlock } from "./agentsMd.mjs";
6
- import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
6
+ import { mocksOutputPath, queriesOutputPath, requestsOutputPath, } from "./constants.mjs";
7
7
  import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs";
8
8
  import { generate } from "./generate.mjs";
9
- /** The generator owns exactly these subdirectories of the output path. */
10
- const checkedSubdirectories = [requestsOutputPath, queriesOutputPath];
9
+ /**
10
+ * The generator owns exactly these subdirectories of the output path. The
11
+ * mocks are only its own when it is asked for them: without `--mock` a
12
+ * `mocks/` directory is somebody else's and is left alone.
13
+ */
14
+ function checkedSubdirectories(options) {
15
+ return [
16
+ requestsOutputPath,
17
+ queriesOutputPath,
18
+ ...(options.mock ? [mocksOutputPath] : []),
19
+ ];
20
+ }
11
21
  /** Name prefix of the throwaway directory `check` generates into. */
12
22
  export const scratchPrefix = ".openapi-rq-check-";
13
23
  function isDirectory(target) {
@@ -132,7 +142,7 @@ async function runCheck(options, version) {
132
142
  // The agent guide is not part of the output directory: it is compared
133
143
  // below, against the file the real run would write.
134
144
  await generate({ ...options, output: scratchOutput, agentsMd: undefined }, version, { silent: true });
135
- const changesPerDir = await Promise.all(checkedSubdirectories.map((subdirectory) => diffDirectories({
145
+ const changesPerDir = await Promise.all(checkedSubdirectories(options).map((subdirectory) => diffDirectories({
136
146
  expectedRoot: path.join(scratchOutput, subdirectory),
137
147
  actualRoot: path.join(options.output, subdirectory),
138
148
  // Reported paths are cwd-relative even for an absolute output.
package/dist/cli.d.mts CHANGED
@@ -20,6 +20,8 @@ export type LimitedUserConfig = {
20
20
  nextPageParam: string;
21
21
  initialPageParam: string | number;
22
22
  omitInitialPageParam?: boolean;
23
+ /** `--mock`: also generate mock data and request handlers for this library. */
24
+ mock?: "msw";
23
25
  /** `--agentsMd`: the file to keep the agent guide in, or `true` for `AGENTS.md`. */
24
26
  agentsMd?: string | boolean;
25
27
  };
@@ -0,0 +1,23 @@
1
+ import type { GeneratedFile } from "../types.mjs";
2
+ import { type EnumsMode } from "./emitTypes.mjs";
3
+ import { type OperationIR } from "./operations.mjs";
4
+ import { type SchemaCtx } from "./schema.mjs";
5
+ /**
6
+ * The major version of MSW the handlers are written for. Version 3 moved
7
+ * `http` and `HttpResponse` from `msw` to `msw/http`; nothing else differs in
8
+ * what is generated.
9
+ */
10
+ export type MswMajor = 2 | 3;
11
+ export interface MocksOptions {
12
+ mswMajor: MswMajor;
13
+ enums?: EnumsMode;
14
+ /** `.js` for Node16/NodeNext module resolution, otherwise empty. */
15
+ ext: "" | ".js";
16
+ }
17
+ export interface EmittedMocks {
18
+ files: GeneratedFile[];
19
+ /** What could not be mocked as the specification describes it. */
20
+ warnings: string[];
21
+ }
22
+ /** Emit the files of `<output>/mocks`: the mock data and the MSW handlers. */
23
+ export declare function emitMocks(operations: OperationIR[], ctx: SchemaCtx, options: MocksOptions): EmittedMocks;
@@ -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) {