diff --git a/AGENTS.md b/AGENTS.md index 08e03e1..1f7b131 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,7 @@ This file has two parts: 1. a TypeScript HTTP client (types, one function per operation and a small fetch or axios runtime) in `/requests/` 2. TanStack Query v5 hooks and helpers on top of that client in `/queries/` +3. with `--mock msw`, mock data and MSW request handlers in `/mocks/` Docs: https://orqc.7nohe.dev (summary for LLMs: https://orqc.7nohe.dev/llms.txt) @@ -40,8 +41,9 @@ Add a script and run it whenever the spec changes: | `-i, --input ` | (required) | OpenAPI 3.0/3.1 spec | | `-o, --output ` | `openapi` | `requests/` and `queries/` are created inside | | `-c, --client ` | `fetch` | or `axios` | -| `--format ` | none | formats `queries/` only | -| `--lint ` | none | lints/fixes `queries/` only | +| `--format ` | none | formats `queries/` (and `mocks/`) only | +| `--lint ` | none | lints/fixes `queries/` (and `mocks/`) only | +| `--mock ` | off | also generate mock data and MSW handlers into `mocks/` (see below) | | `--enums ` | none | emit enum objects | | `--useDateType` | off | `Date` for `date`/`date-time`, converted in successful responses | | `--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 └── transformers.gen.ts # date conversion (only with --useDateType) ``` +With `--mock msw` there is also `/mocks/`: `data.ts` (mock functions), `handlers.ts` (MSW handlers) and `index.ts`. + 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. ### Using the generated code @@ -123,6 +127,28 @@ mutate({ body: { name: "Fluffy" } }); Wrap the app in TanStack Query's `QueryClientProvider` as usual. +### Mocks: `--mock msw` + +```bash +orqc -i ./openapi.yaml -o ./src/openapi --mock msw +``` + +Writes `/mocks/` and needs `msw` (2 or 3) in the project. For an operation `findPets` and a schema `Pet` it exports: + +- `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). +- `handlers`: every handler, ordered so that `/pets/mine` matches before `/pets/{id}`. +- `findPetsResponseMock()` and `petMock(overrides?)`: the mock data, typed by `requests/types.gen.ts`. `overrides` exists for object schemas only. + +```ts +import { setupServer } from "msw/node"; // or setupWorker from "msw/browser" +import { findPetsHandler, handlers, petMock } from "./openapi/mocks"; + +const server = setupServer(...handlers); +server.use(findPetsHandler([petMock({ name: "Momo" })])); // own handlers win: MSW takes the first match +``` + +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. + ### Looking an operation up: `--agentsMd` 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, orqc -i ./openapi.yaml -o ./src/openapi --check ``` -Generates into a temporary directory (`.openapi-rq-check-*` inside `/queries`, removed afterwards), compares it with `/requests` and `/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). +Generates into a temporary directory (`.openapi-rq-check-*` inside `/queries`, removed afterwards), compares it with `/requests` and `/queries` (and `/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). The `queries/` headers include the package version, so after upgrading this package `--check` fails until you regenerate. Upgrade and regenerate in the same change. @@ -219,10 +245,12 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen"; - 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. - 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`. - The generated hooks rely on a small SDK contract: `Options` 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/`. +- 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. - 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. ### Dependencies - 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. +- `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. ### Agent-Specific Notes - 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. diff --git a/CLAUDE.md b/CLAUDE.md index d11dac4..9a59eaa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,7 +39,8 @@ npm run preview:tanstack-router 2. **Generate** (`src/generate.mts`): Orchestrates the generation process: - Calls `generateClient()` (`src/client/index.mts`) to build the client in `openapi/requests/` and the normalized operations - Calls `createSource()` to generate React Query hooks in `openapi/queries/` -3. **Client Generator** (`src/client/`): `spec.mts` loads/bundles the document, `operations.mts` normalizes operations, `schema.mts` renders types, `emitTypes.mts` / `emitSdk.mts` write the files, and `runtime/*.runtime.ts` are the fetch/axios runtimes copied into the output + - With `--mock msw`, writes the mock data and MSW handlers that `generateClient()` returns to `openapi/mocks/` +3. **Client Generator** (`src/client/`): `spec.mts` loads/bundles the document, `operations.mts` normalizes operations, `schema.mts` renders types, `emitTypes.mts` / `emitSdk.mts` write the files, `emitMocks.mts` / `mockValue.mts` write the mocks, and `runtime/*.runtime.ts` are the fetch/axios runtimes copied into the output 4. **Hook Generators** (`src/hooks/`): `generateFiles.mts` routes operations by HTTP method (GET → queries, suspense, infinite, prefetch, ensure; POST/PUT/PATCH/DELETE → mutations) to the `build*.mts` builders, which return statements as strings; `statement.mts` and `imports.mts` print them and the imports each file needs 5. **Write**: `writeGeneratedFiles()` (`src/client/index.mts`) writes both directories @@ -54,10 +55,13 @@ The tool generates files in `openapi/queries/`: - `ensureQueryData.ts`: `ensureQueryData` functions - `index.ts`: Re-exports +With `--mock msw` it also generates `openapi/mocks/`: `data.ts` (mock functions typed by `types.gen.ts`), `handlers.ts` (MSW handlers) and `index.ts`. + ### Key Dependencies - **typescript** (dev only): building this package and compiling generated output in tests - **yaml**: parsing YAML specifications +- **msw** (dev only): compiling and running the generated handlers in tests; generated code imports it from the user's project ## Testing diff --git a/README.md b/README.md index 3ce7cba..950f5bc 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ - **SSR helpers**: `prefetchQuery`, `prefetchInfiniteQuery`, and `ensureQueryData` functions per operation — ready for Next.js App Router hydration - **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 - **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 +- **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 - **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 ## Quick start @@ -63,7 +64,7 @@ function Pets() { } ``` -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) and [CI and coding agents](https://orqc.7nohe.dev/guides/ci-and-agents/). +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/). ## Examples @@ -86,7 +87,7 @@ See the [documentation](https://orqc.7nohe.dev) for [CLI options](https://orqc.7 | SSR helpers (`prefetchQuery` / `prefetchInfiniteQuery` / `ensureQueryData`) | ✅ | ❌ | Partial (`usePrefetch`) | Not provided (use `queryOptions`) | | Hierarchical query keys for granular invalidation | ✅ | ✅ (tags) | Partial | Not documented | | 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) | -| MSW mock generation | ❌ (out of scope) | ❌ | ✅ | ❌ | +| MSW mock generation | ✅ (`--mock msw`, fixed values) | ❌ | ✅ (random values with Faker) | ❌ | | Vue / Solid / Svelte / Angular | ❌ React-focused | ✅ | ✅ | ❌ | | Generation time, GitHub REST API (1,272 operations)¹ | **0.46 s** | 2.98 s | 4.31 s | 2.10 s | | Packages added by installing the generator¹ | **9** (2.1 MB) | 51 (10.8 MB) | 89 (101.5 MB) | 35 (20.5 MB) | @@ -94,7 +95,7 @@ See the [documentation](https://orqc.7nohe.dev) for [CLI options](https://orqc.7 ¹ 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). -**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. +**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. **Coming from openapi-typescript / openapi-fetch / openapi-react-query?** See the [migration guide](https://orqc.7nohe.dev/guides/migrating-from-openapi-react-query/). diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index cdb5fab..da05b6a 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -56,6 +56,7 @@ export default defineConfig({ { slug: "guides/introduction" }, { slug: "guides/usage" }, { slug: "guides/cli-options" }, + { slug: "guides/mocking" }, { slug: "guides/ci-and-agents" }, { slug: "guides/benchmarks" }, { slug: "guides/migrating-to-v3" }, diff --git a/docs/public/llms.txt b/docs/public/llms.txt index 6f2bf0d..d525062 100644 --- a/docs/public/llms.txt +++ b/docs/public/llms.txt @@ -16,6 +16,7 @@ Key facts for agents: - [Introduction](https://orqc.7nohe.dev/guides/introduction/): install, first run, generated layout, client setup - [Usage](https://orqc.7nohe.dev/guides/usage/): using the generated query, suspense, mutation, infinite, prefetch and ensureQueryData exports - [CLI Options](https://orqc.7nohe.dev/guides/cli-options/): every flag with defaults +- [Mocking with MSW](https://orqc.7nohe.dev/guides/mocking/): `--mock msw`, generated mock data and request handlers, overriding a response, how the values are chosen - [CI and Coding Agents](https://orqc.7nohe.dev/guides/ci-and-agents/): `--check`, `--json`, exit codes, error codes, AGENTS.md - [AGENTS.md](https://github.com/7nohe/openapi-react-query-codegen/blob/main/AGENTS.md): agent guide, also at `node_modules/@7nohe/openapi-react-query-codegen/AGENTS.md` diff --git a/docs/src/content/docs/guides/ci-and-agents.mdx b/docs/src/content/docs/guides/ci-and-agents.mdx index bab5627..5a96851 100644 --- a/docs/src/content/docs/guides/ci-and-agents.mdx +++ b/docs/src/content/docs/guides/ci-and-agents.mdx @@ -25,7 +25,7 @@ Use exactly the same options as your normal codegen script. Different options pr `--check`: - generates into a temporary directory inside `/queries` (`.openapi-rq-check-*`) and deletes it afterwards. `--format` and `--lint` run on that copy with the same configuration files, and overrides or ignore rules that target the output directory by path (`src/openapi/**`, a folder named `openapi`) apply to it as well -- compares only the directories the generator owns: `/requests` and `/queries` +- compares only the directories the generator owns: `/requests` and `/queries`, and `/mocks` when `--mock` is passed - never changes an existing file in the output directory - exits with `0` when everything matches, and with `1` when files differ diff --git a/docs/src/content/docs/guides/cli-options.mdx b/docs/src/content/docs/guides/cli-options.mdx index bc2780a..1d84957 100644 --- a/docs/src/content/docs/guides/cli-options.mdx +++ b/docs/src/content/docs/guides/cli-options.mdx @@ -47,7 +47,7 @@ The v3 spellings `@hey-api/client-fetch` and `@hey-api/client-axios` are still a ### --format \ -Process the generated queries output folder (`openapi/queries`) with a formatter. The `openapi/requests` directory is not affected by this option. The default value is `false`. +Process the generated queries output folder (`openapi/queries`) with a formatter, and `openapi/mocks` when `--mock` is set. The `openapi/requests` directory is not affected by this option. The default value is `false`. The available options are: - `biome` @@ -55,7 +55,7 @@ The available options are: ### --lint \ -Process the generated queries output folder (`openapi/queries`) with a linter. The `openapi/requests` directory is not affected by this option. The default value is `false`. +Process the generated queries output folder (`openapi/queries`) with a linter, and `openapi/mocks` when `--mock` is set. The `openapi/requests` directory is not affected by this option. The default value is `false`. The available options are: - `biome` @@ -101,6 +101,17 @@ The available options are: - `json`: the schemas as the specification writes them - `form`: without `title`, `description` and the `x-enum-*` names, for use in form libraries +## Mock Options + +### --mock \ + +Also generate mock data and request handlers from the specification, into `openapi/mocks`. Nothing is generated by default. +The available options are: + +- `msw`: [MSW](https://mswjs.io) request handlers (version 2 or 3; install `msw` in your project) + +See [Mocking with MSW](/guides/mocking/) for how to use them. + ## CI and Automation Options See [CI and Coding Agents](/guides/ci-and-agents/) for details and examples. diff --git a/docs/src/content/docs/guides/mocking.mdx b/docs/src/content/docs/guides/mocking.mdx new file mode 100644 index 0000000..61b59fa --- /dev/null +++ b/docs/src/content/docs/guides/mocking.mdx @@ -0,0 +1,138 @@ +--- +title: Mocking with MSW +description: Generate mock data and MSW request handlers from the OpenAPI specification, to build the frontend before the backend exists and to test without one. +--- + +With `--mock msw` the generator also writes mock data and [MSW](https://mswjs.io) request handlers for every operation. The frontend can then be built against the specification before the backend exists, and the same handlers serve tests and Storybook. + +```bash +npm install -D msw +orqc -i ./openapi.yaml -o ./src/openapi --mock msw +``` + +This adds a third directory next to `requests/` and `queries/`, here under `src/openapi` as the examples below import it: + +``` +src/openapi/mocks/ +├── data.ts # one mock function per schema and per response +├── handlers.ts # one MSW handler per operation, and `handlers` with all of them +└── index.ts # re-exports both +``` + +The mocks are typed by the generated types, so they stay in step with the specification: regenerate after it changes, and anything of your own that no longer fits is a compile error. + +## In the browser + +Copy MSW's worker script into the folder your app serves static files from, once: + +```bash +npx msw init public/ --save +``` + +Create the worker from the generated handlers: + +```ts +// src/mocks/browser.ts +import { setupWorker } from "msw/browser"; +import { handlers } from "../openapi/mocks"; + +export const worker = setupWorker(...handlers); +``` + +Start it before the app renders, in development only: + +```tsx +// src/main.tsx +async function enableMocking() { + if (!import.meta.env.DEV) return; + const { worker } = await import("./mocks/browser"); + await worker.start(); +} + +enableMocking().then(() => { + createRoot(document.getElementById("root")!).render(); +}); +``` + +The handlers match the path under any base URL (`*/pets/:petId`), so they answer whatever the client's `baseUrl` is. The generated hooks need no change. + +## In tests + +```ts +import { setupServer } from "msw/node"; +import { handlers } from "../openapi/mocks"; + +const server = setupServer(...handlers); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); +``` + +## Answering with something else + +By default a handler answers with the mock of its operation's successful response. Each handler is also exported as a function that takes what to answer with instead: a body, or a resolver of your own. + +```ts +import { HttpResponse } from "msw/http"; // "msw" with MSW 2 +import { findPetsHandler, findPetByIdHandler, petMock } from "../openapi/mocks"; + +server.use( + // Another body, typed as the operation's response + findPetsHandler([petMock({ name: "Momo" }), petMock({ id: 2 })]), + // A resolver, for an error or anything that depends on the request + findPetByIdHandler(({ params }) => + HttpResponse.json({ message: `No pet ${params.id}` }, { status: 404 }), + ), +); +``` + +MSW uses the first handler that matches, so put your own before the generated ones: + +```ts +setupWorker(findPetsHandler([]), ...handlers); +``` + +The mock of an object schema takes the properties to replace (`petMock({ name: "Momo" })`). The mocks of other schemas (arrays, unions, enums) take nothing. + +## What the values are + +The values are fixed, never random, so a test or a snapshot sees the same data on every run. For each schema the first of these that applies is used: + +1. the `example` of the response's media type, or the first of its `examples` +2. the schema's `example`, the first of its `examples`, or its `default` +3. its `const`, or the first value of its `enum` +4. a value made up from the type: `"string"` or a fixed value for the `format` (`date-time`, `uuid`, `email`, ...), `1` moved into `minimum` and `maximum`, `true`, an array of one item, an object with all of its properties + +So the quickest way to better mock data is to write examples in the specification. They are also what the backend has agreed to return. + +```yaml +Pet: + type: object + properties: + name: + type: string + example: Momo +``` + +An example is only used when it is a value of its schema. One that has drifted from it (a missing required property, a string where the schema says integer) is passed over and the value is made up instead, because the mock would not compile otherwise. The same goes for an example of a schema composed with `oneOf`, `anyOf` or several `allOf` members, which is not checked. + +Of a `oneOf` or `anyOf` the first member is used. With `--useDateType` the dates are `Date` objects, as the types say, and travel as text. `writeOnly` properties are left out, as they are in the response types. + +A schema that refers to itself would never end, so a reference back to a schema that is still being built is cut: an optional property is left out, an array is empty, a nullable value is `null`. A schema that *requires* itself has no value at all; its mock returns an empty object and the generator says which schema it is. + +## What is not generated + +The handlers hold no state and do not look at the request. That is enough to build and test most screens, and these need a handler of your own, written with the generated types and mocks: + +- **A change that shows up later.** Creating a pet does not add it to the list. Keep the list in a variable and answer both operations from it. +- **Pagination.** Every page is the same response, so an infinite query never reaches the end. +- **Errors and empty states.** Only the successful response is mocked. Answer with a resolver that returns the error. + +Operations whose successful response has no JSON or text body (a `204`, a file, a `HEAD`) are answered with the status and an empty body. + +## MSW versions + +MSW 2 and 3 are supported. Version 3 moved `http` and `HttpResponse` from `msw` to `msw/http`, so the generator looks at the MSW installed in your project and imports from where that version exports them. Without MSW installed it writes the imports for version 3. After upgrading MSW, generate again. + +`--check` compares `mocks/` as well when `--mock` is passed, and `--format` and `--lint` run on it with `queries/`. diff --git a/package.json b/package.json index 0d59536..aaa2534 100644 --- a/package.json +++ b/package.json @@ -71,6 +71,7 @@ "axios": "1.20.0", "commander": "^15.1.0", "lefthook": "^2.1.10", + "msw": "^3.0.4", "typescript": "^6.0.3", "vite": "^8.3.6", "vitest": "^5.1.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d609a27..311ffb8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -65,6 +65,9 @@ importers: lefthook: specifier: ^2.1.10 version: 2.2.2 + msw: + specifier: ^3.0.4 + version: 3.0.4(@types/node@22.20.5)(typescript@6.0.3)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)) typescript: specifier: ^6.0.3 version: 6.0.3 @@ -73,7 +76,7 @@ importers: version: 8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1) vitest: specifier: ^5.1.0 - version: 5.1.0(@types/node@22.20.5)(@vitest/coverage-v8@5.1.0)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)) + version: 5.1.0(@types/node@22.20.5)(@vitest/coverage-v8@5.1.0)(msw@3.0.4(@types/node@22.20.5)(typescript@6.0.3)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)))(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)) docs: dependencies: @@ -1049,6 +1052,41 @@ packages: cpu: [x64] os: [win32] + '@inquirer/ansi@2.0.10': + resolution: {integrity: sha512-dwrc+1aqVZpHNkNDswXGtn1typ+Pxpo5FHZRyBw1le7onEJUkPUkYOY1FIFC1LvFMYUqqLuWBwElhAmencL7MQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + + '@inquirer/confirm@6.3.5': + resolution: {integrity: sha512-BJ59BOyURiZiAxdr9AuRu38/k+rV+DcTIM2fUF/c/BXrab6H8zMZTTOl3LgkSJH96Xob2vOJxDiBkHiz32Xx2w==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/core@12.0.6': + resolution: {integrity: sha512-5yxn2LsJ8Tu4ei2a+yNkmFRhM/cb+JMEsEs/AW6CCOnBnpMy4IjYiPMFyHtYq8weOmlTyqqCx40y0DsD7OsEPw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/figures@2.0.10': + resolution: {integrity: sha512-51elrUJV3jZpvD0ygz8+U10Kc6+Lzqln+/tYmnbhy6jo5oXpE6hMCcv+OTBC0enwJXsb3JIuT3VtEinRNCSK2A==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + + '@inquirer/type@4.2.1': + resolution: {integrity: sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + '@internationalized/number@3.6.9': resolution: {integrity: sha512-GgWy2caO/+hV9sT/oCTWGHvbjmJMPT9kkXzoKRLnkEq7adghhR7UprhvY9sXrKfrp3NcDfhF6QQHXR1KfQbB8g==} @@ -1084,6 +1122,13 @@ packages: peerDependencies: solid-js: ^1.8.8 + '@msw/url@0.1.2': + resolution: {integrity: sha512-DdeBLQxQ+ZrtmwEmaj7GQ7lbzPCgbbbyAqOz/I4ulo68hwBpfdNvQJ5bmihJUkAAKOeCmqCIG3OFZGosqFN4mA==} + + '@mswjs/interceptors@0.45.11': + resolution: {integrity: sha512-+ISPERIRIHhSVnFQRGCP9jDJXxn0/z2+pWWbXUym6JUfpUCRW2Pvro4P9RBKGYUKTKAULszKurKMTQIsaJUIgQ==} + engines: {node: '>=22'} + '@napi-rs/wasm-runtime@1.2.4': resolution: {integrity: sha512-AJxoUD2/15ESHbvpcyjU274nsAPLuOtPHCk0vKJM5pj//Fg/B1FXNWjPnXTT9PymCYYiHo4zPj0ZomXBKhoy7g==} engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} @@ -1149,6 +1194,9 @@ packages: cpu: [x64] os: [win32] + '@open-draft/until@3.0.1': + resolution: {integrity: sha512-s7/9ELP4aP9YZtW7RJaa0Xf3RISaRH9+EFN18FtykJYRHGNrl8f9ymvoNXzjhrjmftFvkQudtuDU9RYhk0xs3A==} + '@oslojs/encoding@1.1.0': resolution: {integrity: sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ==} @@ -1802,8 +1850,8 @@ packages: '@types/cross-spawn@6.0.6': resolution: {integrity: sha512-fXRhhUkG4H3TQk5dBhQ7m/JDdSNHKwR2BBia62lhwEIq9xGiQKLxd6LymNhn47SjXhsUEPmxi+PKw2OkW4LLjA==} - '@types/debug@4.1.12': - resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==} + '@types/debug@4.1.13': + resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==} '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} @@ -1852,6 +1900,9 @@ packages: '@types/semver@7.8.0': resolution: {integrity: sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==} + '@types/set-cookie-parser@2.4.10': + resolution: {integrity: sha512-GGmQVGpQWUe5qglJozEjZV/5dyxbOOZ0LHe/lqyWssB88Y4svNfst0uqBVscdDeIKl5Jy5+aPSvy7mI9tYRguw==} + '@types/unist@2.0.11': resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==} @@ -2120,6 +2171,10 @@ packages: resolution: {integrity: sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==} engines: {node: '>=8'} + cli-width@4.1.0: + resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} + engines: {node: '>= 12'} + client-only@0.0.1: resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} @@ -2580,6 +2635,9 @@ packages: hastscript@9.0.1: resolution: {integrity: sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==} + headers-polyfill@5.0.1: + resolution: {integrity: sha512-1TJ6Fih/b8h5TIcv+1+Hw0PDQWJTKDKzFZzcKOiW1wJza3XoAQlkCuXLbymPYB8+ZQyw8mHvdw560e8zVFIWyA==} + html-escaper@3.0.3: resolution: {integrity: sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==} @@ -2639,6 +2697,9 @@ packages: is-hexadecimal@2.0.1: resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==} + is-node-process@1.2.0: + resolution: {integrity: sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==} + is-plain-obj@4.1.0: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} @@ -2986,9 +3047,29 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + msw@3.0.4: + resolution: {integrity: sha512-lrILj+WEoJ4pp3SZHdEDnnZvP6jfWrNua+v2jgXz82RAaATAVqOqMNMxj2n2TUMNR9JP/eWG5tBry3mKnxPNbA==} + engines: {node: '>=22.12.0'} + hasBin: true + peerDependencies: + graphql: '>=16' + typescript: '>=5.9.x' + vite: '>=6' + peerDependenciesMeta: + graphql: + optional: true + typescript: + optional: true + vite: + optional: true + muggle-string@0.4.1: resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==} + mute-stream@3.0.0: + resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==} + engines: {node: ^20.17.0 || >=22.9.0} + nanoid@3.3.20: resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -3084,6 +3165,9 @@ packages: oniguruma-to-es@4.3.6: resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==} + outvariant@1.4.3: + resolution: {integrity: sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==} + p-limit@7.3.3: resolution: {integrity: sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ==} engines: {node: '>=20'} @@ -3269,6 +3353,9 @@ packages: retext-smartypants@6.2.0: resolution: {integrity: sha512-kk0jOU7+zGv//kfjXEBjdIryL1Acl4i9XNkHxtM7Tm5lFiCog576fjNC9hjoR7LTKQ0DsPWy09JummSsH1uqfQ==} + rettime@0.11.12: + resolution: {integrity: sha512-5ExtR1ppiDBQkVoPw5NAqdbfH4Iq2VOmQKHMtUoaFxA9bo2krzFYBtyq6K40xxbYp+2w/YOr6D+1ToF6tTN53A==} + rolldown@1.2.16: resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3342,6 +3429,9 @@ packages: resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==} engines: {node: '>= 18'} + set-cookie-parser@3.2.2: + resolution: {integrity: sha512-df017qMeYuXo4emL09nlyMpi2i2MtEIKS/6jtXH3vmjFgIRsOi852/5RmhJ4EkvN3ZF8jXadM/EkTPXgc8yPIw==} + setprototypeof@1.2.0: resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} @@ -3386,6 +3476,10 @@ packages: resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} engines: {node: '>= 0.4'} + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + sisteransi@1.0.5: resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} @@ -3475,6 +3569,10 @@ packages: engines: {node: '>=16'} hasBin: true + tagged-tag@1.0.0: + resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==} + engines: {node: '>=20'} + tailwindcss@4.3.5: resolution: {integrity: sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==} @@ -3513,10 +3611,22 @@ packages: resolution: {integrity: sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==} engines: {node: '>=14.0.0'} + tldts-core@7.4.20: + resolution: {integrity: sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==} + deprecated: Partial release, see https://github.com/remusao/tldts/issues/2735. Use >=7.4.22. + + tldts@7.4.19: + resolution: {integrity: sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==} + hasBin: true + toidentifier@1.0.1: resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} engines: {node: '>=0.6'} + tough-cookie@6.1.0: + resolution: {integrity: sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==} + engines: {node: '>=16'} + trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -3531,6 +3641,10 @@ packages: engines: {node: '>=18.0.0'} hasBin: true + type-fest@5.10.0: + resolution: {integrity: sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==} + engines: {node: '>=20'} + type-is@2.1.0: resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} engines: {node: '>= 18'} @@ -3701,6 +3815,9 @@ packages: uploadthing: optional: true + until-async@3.0.2: + resolution: {integrity: sha512-IiSk4HlzAMqTUseHHe3VhIGyuFmN90zMTpD3Z3y8jeQbzLIq500MVM7Jq2vUAnTKAFPJrqwkzr6PoTcPhGcOiw==} + update-browserslist-db@1.3.4: resolution: {integrity: sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==} hasBin: true @@ -3808,7 +3925,7 @@ packages: '@vitest/ui': 5.1.0 happy-dom: '*' jsdom: '*' - vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + vite: 8.3.6 peerDependenciesMeta: '@edge-runtime/vm': optional: true @@ -4691,6 +4808,33 @@ snapshots: '@img/sharp-win32-x64@0.35.5': optional: true + '@inquirer/ansi@2.0.10': {} + + '@inquirer/confirm@6.3.5(@types/node@22.20.5)': + dependencies: + '@inquirer/core': 12.0.6(@types/node@22.20.5) + '@inquirer/type': 4.2.1(@types/node@22.20.5) + optionalDependencies: + '@types/node': 22.20.5 + + '@inquirer/core@12.0.6(@types/node@22.20.5)': + dependencies: + '@inquirer/ansi': 2.0.10 + '@inquirer/figures': 2.0.10 + '@inquirer/type': 4.2.1(@types/node@22.20.5) + cli-width: 4.1.0 + fast-wrap-ansi: 0.2.2 + mute-stream: 3.0.0 + signal-exit: 4.1.0 + optionalDependencies: + '@types/node': 22.20.5 + + '@inquirer/figures@2.0.10': {} + + '@inquirer/type@4.2.1(@types/node@22.20.5)': + optionalDependencies: + '@types/node': 22.20.5 + '@internationalized/number@3.6.9': dependencies: '@swc/helpers': 0.5.23 @@ -4744,6 +4888,19 @@ snapshots: '@solid-primitives/utils': 6.4.1(solid-js@1.9.18) solid-js: 1.9.18 + '@msw/url@0.1.2': {} + + '@mswjs/interceptors@0.45.11': + dependencies: + '@open-draft/until': 3.0.1 + '@types/debug': 4.1.13 + debug: 4.4.3 + is-node-process: 1.2.0 + outvariant: 1.4.3 + rettime: 0.11.12 + transitivePeerDependencies: + - supports-color + '@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': dependencies: '@emnapi/core': 1.11.3 @@ -4790,6 +4947,8 @@ snapshots: '@next/swc-win32-x64-msvc@16.4.5': optional: true + '@open-draft/until@3.0.1': {} + '@oslojs/encoding@1.1.0': {} '@oxc-project/types@0.156.0': {} @@ -5364,7 +5523,7 @@ snapshots: dependencies: '@types/node': 22.20.5 - '@types/debug@4.1.12': + '@types/debug@4.1.13': dependencies: '@types/ms': 0.7.34 @@ -5419,6 +5578,10 @@ snapshots: '@types/semver@7.8.0': {} + '@types/set-cookie-parser@2.4.10': + dependencies: + '@types/node': 22.20.5 + '@types/unist@2.0.11': {} '@types/unist@3.0.3': {} @@ -5440,7 +5603,7 @@ snapshots: obug: 3.0.0 std-env: 4.3.0 tinyrainbow: 3.2.0 - vitest: 5.1.0(@types/node@22.20.5)(@vitest/coverage-v8@5.1.0)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)) + vitest: 5.1.0(@types/node@22.20.5)(@vitest/coverage-v8@5.1.0)(msw@3.0.4(@types/node@22.20.5)(typescript@6.0.3)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)))(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)) '@vitest/istanbul-lib-coverage@2.1.0': {} @@ -5448,13 +5611,14 @@ snapshots: dependencies: '@vitest/istanbul-lib-coverage': 2.1.0 - '@vitest/mocker@5.1.0(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1))': + '@vitest/mocker@5.1.0(msw@3.0.4(@types/node@22.20.5)(typescript@6.0.3)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)))(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1))': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@vitest/spy': 5.1.0 estree-walker: 3.0.3 magic-string: 1.4.5 optionalDependencies: + msw: 3.0.4(@types/node@22.20.5)(typescript@6.0.3)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)) vite: 8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1) '@vitest/spy@5.1.0': {} @@ -5766,6 +5930,8 @@ snapshots: ci-info@4.4.0: {} + cli-width@4.1.0: {} + client-only@0.0.1: {} cliui@9.0.1: @@ -6283,6 +6449,11 @@ snapshots: property-information: 7.2.0 space-separated-tokens: 2.0.2 + headers-polyfill@5.0.1: + dependencies: + '@types/set-cookie-parser': 2.4.10 + set-cookie-parser: 3.2.2 + html-escaper@3.0.3: {} html-void-elements@3.0.0: {} @@ -6333,6 +6504,8 @@ snapshots: is-hexadecimal@2.0.1: {} + is-node-process@1.2.0: {} + is-plain-obj@4.1.0: {} is-promise@4.0.0: {} @@ -6684,7 +6857,7 @@ snapshots: micromark@4.0.0: dependencies: - '@types/debug': 4.1.12 + '@types/debug': 4.1.13 debug: 4.4.3 decode-named-character-reference: 1.0.2 devlop: 1.1.0 @@ -6732,8 +6905,31 @@ snapshots: ms@2.1.3: {} + msw@3.0.4(@types/node@22.20.5)(typescript@6.0.3)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)): + dependencies: + '@inquirer/confirm': 6.3.5(@types/node@22.20.5) + '@msw/url': 0.1.2 + '@mswjs/interceptors': 0.45.11 + cookie: 2.0.1 + headers-polyfill: 5.0.1 + is-node-process: 1.2.0 + outvariant: 1.4.3 + rettime: 0.11.12 + tough-cookie: 6.1.0 + type-fest: 5.10.0 + until-async: 3.0.2 + yargs: 18.2.0 + optionalDependencies: + typescript: 6.0.3 + vite: 8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1) + transitivePeerDependencies: + - '@types/node' + - supports-color + muggle-string@0.4.1: {} + mute-stream@3.0.0: {} + nanoid@3.3.20: {} negotiator@0.6.4: {} @@ -6826,6 +7022,8 @@ snapshots: regex: 6.1.0 regex-recursion: 6.0.2 + outvariant@1.4.3: {} + p-limit@7.3.3: dependencies: yocto-queue: 1.2.2 @@ -6995,6 +7193,8 @@ snapshots: nlcst-to-string: 4.0.0 unist-util-visit: 5.1.0 + rettime@0.11.12: {} + rolldown@1.2.16: dependencies: '@oxc-project/types': 0.156.0 @@ -7145,6 +7345,8 @@ snapshots: transitivePeerDependencies: - supports-color + set-cookie-parser@3.2.2: {} + setprototypeof@1.2.0: {} sharp@0.35.5(@types/node@20.19.43): @@ -7261,6 +7463,8 @@ snapshots: side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 + signal-exit@4.1.0: {} + sisteransi@1.0.5: {} sitemap@9.0.1: @@ -7348,6 +7552,8 @@ snapshots: picocolors: 1.1.1 sax: 1.6.1 + tagged-tag@1.0.0: {} + tailwindcss@4.3.5: {} tapable@2.3.3: {} @@ -7377,8 +7583,18 @@ snapshots: tinyrainbow@3.2.0: {} + tldts-core@7.4.20: {} + + tldts@7.4.19: + dependencies: + tldts-core: 7.4.20 + toidentifier@1.0.1: {} + tough-cookie@6.1.0: + dependencies: + tldts: 7.4.19 + trim-lines@3.0.1: {} trough@2.2.0: {} @@ -7392,6 +7608,10 @@ snapshots: fsevents: 2.3.3 optional: true + type-fest@5.10.0: + dependencies: + tagged-tag: 1.0.0 + type-is@2.1.0: dependencies: content-type: 2.1.0 @@ -7492,6 +7712,8 @@ snapshots: ofetch: 1.5.1 ufo: 1.6.4 + until-async@3.0.2: {} + update-browserslist-db@1.3.4(browserslist@4.29.5): dependencies: browserslist: 4.29.5 @@ -7560,10 +7782,10 @@ snapshots: optionalDependencies: vite: 8.3.6(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1) - vitest@5.1.0(@types/node@22.20.5)(@vitest/coverage-v8@5.1.0)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)): + vitest@5.1.0(@types/node@22.20.5)(@vitest/coverage-v8@5.1.0)(msw@3.0.4(@types/node@22.20.5)(typescript@6.0.3)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)))(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 - '@vitest/mocker': 5.1.0(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)) + '@vitest/mocker': 5.1.0(msw@3.0.4(@types/node@22.20.5)(typescript@6.0.3)(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)))(vite@8.3.6(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1)) chai: 6.3.0 es-module-lexer: 2.3.2 expect-type: 1.4.0 diff --git a/src/check.mts b/src/check.mts index c0bbf8f..02829d0 100644 --- a/src/check.mts +++ b/src/check.mts @@ -4,7 +4,11 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { agentsFilePath, checkAgentsBlock } from "./agentsMd.mjs"; import type { LimitedUserConfig } from "./cli.mjs"; -import { queriesOutputPath, requestsOutputPath } from "./constants.mjs"; +import { + mocksOutputPath, + queriesOutputPath, + requestsOutputPath, +} from "./constants.mjs"; import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs"; import { generate } from "./generate.mjs"; @@ -26,8 +30,18 @@ export type CheckResult = { files: FileChange[]; }; -/** The generator owns exactly these subdirectories of the output path. */ -const checkedSubdirectories = [requestsOutputPath, queriesOutputPath]; +/** + * The generator owns exactly these subdirectories of the output path. The + * mocks are only its own when it is asked for them: without `--mock` a + * `mocks/` directory is somebody else's and is left alone. + */ +function checkedSubdirectories(options: LimitedUserConfig): string[] { + return [ + requestsOutputPath, + queriesOutputPath, + ...(options.mock ? [mocksOutputPath] : []), + ]; +} /** Name prefix of the throwaway directory `check` generates into. */ export const scratchPrefix = ".openapi-rq-check-"; @@ -183,7 +197,7 @@ async function runCheck( { silent: true }, ); const changesPerDir = await Promise.all( - checkedSubdirectories.map((subdirectory) => + checkedSubdirectories(options).map((subdirectory) => diffDirectories({ expectedRoot: path.join(scratchOutput, subdirectory), actualRoot: path.join(options.output, subdirectory), diff --git a/src/cli.mts b/src/cli.mts index 87b2280..a056301 100644 --- a/src/cli.mts +++ b/src/cli.mts @@ -30,6 +30,8 @@ export type LimitedUserConfig = { nextPageParam: string; initialPageParam: string | number; omitInitialPageParam?: boolean; + /** `--mock`: also generate mock data and request handlers for this library. */ + mock?: "msw"; /** `--agentsMd`: the file to keep the agent guide in, or `true` for `AGENTS.md`. */ agentsMd?: string | boolean; }; diff --git a/src/client/emitMocks.mts b/src/client/emitMocks.mts new file mode 100644 index 0000000..4407f03 --- /dev/null +++ b/src/client/emitMocks.mts @@ -0,0 +1,457 @@ +import type { GeneratedFile } from "../types.mjs"; +import { HEADER } from "./emitSdk.mjs"; +import { type EnumsMode, isEnumDeclaration } from "./emitTypes.mjs"; +import { exampleValue, type MockValueCtx, mockValue } from "./mockValue.mjs"; +import { uniqueName } from "./naming.mjs"; +import { + classifyResponses, + mediaKind, + type OperationIR, + type ResponseIR, +} from "./operations.mjs"; +import { + componentSchemaView, + hasObjectKeywords, + isNullableSchema, + isRequiredOnly, + renderSchema, + type SchemaCtx, +} from "./schema.mjs"; +import { type Doc, type Json, resolveRef } from "./spec.mjs"; + +/** + * The major version of MSW the handlers are written for. Version 3 moved + * `http` and `HttpResponse` from `msw` to `msw/http`; nothing else differs in + * what is generated. + */ +export type MswMajor = 2 | 3; + +export interface MocksOptions { + mswMajor: MswMajor; + enums?: EnumsMode; + /** `.js` for Node16/NodeNext module resolution, otherwise empty. */ + ext: "" | ".js"; +} + +export interface EmittedMocks { + files: GeneratedFile[]; + /** What could not be mocked as the specification describes it. */ + warnings: string[]; +} + +/** Statuses whose response cannot have a body. */ +const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]); + +/** The methods `http` of MSW has a handler for. */ +const MSW_METHODS = new Set([ + "get", + "post", + "put", + "delete", + "patch", + "head", + "options", +]); + +function lowerFirst(name: string): string { + return name.charAt(0).toLowerCase() + name.slice(1); +} + +/** + * Whether the schema is one object type, which `Partial` of it can override + * property by property. A union is not: a part of one member spread over + * another member is a value of neither. + */ +function isPlainObject(doc: Doc, schema: Json, depth = 0): boolean { + const resolved = resolveRef(doc, schema); + if (!resolved || typeof resolved !== "object" || depth > 16) return false; + if ( + resolved.oneOf !== undefined || + resolved.anyOf !== undefined || + resolved.enum !== undefined || + resolved.const !== undefined || + isNullableSchema(resolved) + ) { + return false; + } + const members: Json[] = Array.isArray(resolved.allOf) + ? resolved.allOf.filter((member: Json) => !isRequiredOnly(member)) + : []; + if (resolved.type !== undefined && resolved.type !== "object") return false; + if ( + resolved.type === undefined && + !hasObjectKeywords(resolved) && + members.length === 0 + ) { + return false; + } + return members.every((member) => isPlainObject(doc, member, depth + 1)); +} + +const PATH_PARAMETER = /\{([^{}]+)\}/g; + +const REGEXP_SYNTAX = /[.*+?^${}()|[\]\\]/; + +/** + * A regular expression for the fixed text of a path as a request carries it. + * A URL percent-encodes what is not ASCII (`/café` is requested as + * `/caf%C3%A9`); what is encoded already stays as it is. A few ASCII + * characters are encoded by some URL parsers and not by others (`^` is by + * Node.js 24 and not by 22), so both spellings match. The parser is not + * asked: the output must not depend on what runs the generator. + */ +function pathTextPattern(text: string): string { + return text.replace(/[^\x21-\x7e]|[.*+?^${}()|[\]\\"<>`]/gu, (char) => { + const literal = REGEXP_SYNTAX.test(char) ? `\\${char}` : char; + if (/["<>^`{}]/.test(char)) { + return `(?:${literal}|${encodeURIComponent(char)})`; + } + if (char >= "!" && char <= "~") return literal; + // A lone surrogate is sent as the replacement character. + return encodeURIComponent(char.isWellFormed() ? char : "\uFFFD"); + }); +} + +/** + * What a handler matches the path with, as an expression. `*` stands for the + * base URL, so the handlers match wherever the API is. + * + * MSW reads `:` and a few other characters in a path as its own syntax, so a + * path that has one outside its parameters (`/pets:count`) is matched with a + * regular expression instead, which gives the resolver no named parameters. + * So is a path whose parameter is followed by another one or by a letter + * (`/files/{name}{extension}`, `/v{major}beta`): MSW 2 rejects the first, and + * would take the letters for the rest of the parameter's name. + */ +function mswPath(path: string): string { + const fixed = path.replace(PATH_PARAMETER, ""); + if (/^[\w/.~-]*$/.test(fixed) && !/\}[\w{]/.test(path)) { + return JSON.stringify( + `*${path.replace(PATH_PARAMETER, (_match, name: string) => { + // A parameter name is made of word characters and starts with none + // of the digits. + const safe = name.replace(/\W/g, "_"); + return `:${/^\d/.test(safe) ? "_" : ""}${safe}`; + })}`, + ); + } + const source = path + .split(PATH_PARAMETER) + // Every other part is the name of a parameter. + .map((part, index) => (index % 2 === 1 ? "([^/]+)" : pathTextPattern(part))) + .join(""); + // As in a path given as text, a trailing slash is only required when the + // path has one. + return `new RegExp(${JSON.stringify(`${source}${path.endsWith("/") ? "" : "/?"}$`)})`; +} + +/** + * Where a path sorts among the handlers. MSW answers with the first handler + * that matches, so a segment has to come before a looser one in its place: + * `/pets/mine` and `/pets/{id}:archive` before `/pets/{id}`. + */ +function specificity(path: string): string { + return path + .split("/") + .map((segment) => + /^\{[^{}]+\}$/.test(segment) ? "2" : segment.includes("{") ? "1" : "0", + ) + .join(""); +} + +/** The response a handler answers with: the lowest of the successful ones. */ +function pickResponse(operation: OperationIR): ResponseIR | undefined { + // A range (`2XX`) comes after the statuses it stands for. `default` is only + // ever here alone. + const rank = (status: string) => + /^\d+$/.test(status) ? Number(status) : 999; + return [...classifyResponses(operation).responses].sort( + (a, b) => rank(a.status) - rank(b.status), + )[0]; +} + +/** The body of a mock that no value can be written for. */ +function noValue(type: string): string { + return `{} as unknown as ${type}`; +} + +function declareFunction( + name: string, + parameters: string, + type: string, + body: string, +): string { + return `export function ${name}(${parameters}): ${type} {\n return ${body};\n}`; +} + +const DATA_INTRO = `/** + * Mock data for the schemas and the responses of the API. The values are fixed: + * an \`example\` or a \`default\` from the specification where it has one, and + * otherwise the first \`enum\` value or a value made up from the type. + */`; + +const HANDLERS_INTRO = `/** + * MSW request handlers for the API. Each answers with the mock of its + * operation's successful response. Pass a handler another body, or a resolver + * of your own, to answer with something else: + * + * setupWorker(findPetsHandler([]), ...handlers) + * + * MSW uses the first handler that matches, so yours go before \`handlers\`. + */`; + +/** Emit the files of `/mocks`: the mock data and the MSW handlers. */ +export function emitMocks( + operations: OperationIR[], + ctx: SchemaCtx, + options: MocksOptions, +): EmittedMocks { + const { doc } = ctx; + const readCtx: SchemaCtx = { ...ctx, mode: "read", onRef: undefined }; + const schemas = (doc.components?.schemas ?? {}) as Record; + const warnings: string[] = []; + const used = new Set(); + + const typeOf = (key: string) => `Types.${ctx.names.get(key) as string}`; + const mockNames = new Map(); + for (const key of Object.keys(schemas)) { + mockNames.set( + key, + uniqueName(`${lowerFirst(ctx.names.get(key) as string)}Mock`, used), + ); + } + + // The mocks call each other, so a schema that holds itself would never + // return. Schemas are built depth first, and a reference back to one that is + // still being built is cut: left out, an empty array or `null`, whichever the + // schema allows there. A mock only ever calls mocks finished before it. + const bodies = new Map(); + const building = new Set(); + const unbuildable: string[] = []; + let attempts = 0; + const valueCtx: MockValueCtx = { + schema: readCtx, + callMock: (key) => + buildComponent(key) === undefined + ? undefined + : `${mockNames.get(key) as string}()`, + enumCast: (key) => + options.enums === "typescript" && + isEnumDeclaration(schemas[key], options.enums) + ? typeOf(key) + : undefined, + }; + + function buildComponent(key: string): string | undefined { + const done = bodies.get(key); + if (done !== undefined) return done; + if (building.has(key)) return undefined; + building.add(key); + attempts += 1; + const view = componentSchemaView(schemas[key], key, readCtx); + let body = mockValue(view, valueCtx, " "); + building.delete(key); + if (body === undefined) { + // Under another schema the cut can fall where this one cannot take it, + // so it is tried again from the top. The limit keeps a specification + // that is full of such schemas from being built over and over. + const retry = attempts <= Object.keys(schemas).length * 20; + if (building.size > 0 && retry) return undefined; + unbuildable.push(key); + body = noValue(typeOf(key)); + } else { + const cast = valueCtx.enumCast(key); + if (cast !== undefined) body = `${body} as ${cast}`; + } + bodies.set(key, body); + return body; + } + + const dataBlocks: string[] = []; + for (const key of Object.keys(schemas)) { + const body = buildComponent(key) as string; + const name = mockNames.get(key) as string; + const type = typeOf(key); + const view = componentSchemaView(schemas[key], key, readCtx); + if (!unbuildable.includes(key) && isPlainObject(doc, view)) { + const base = + body === "{}" + ? "" + : body.startsWith("{\n") + ? body.slice(2, body.lastIndexOf("\n")) + : ` ...${body},`; + const literal = `{\n${base === "" ? "" : `${base}\n`} ...overrides,\n }`; + dataBlocks.push( + declareFunction(name, `overrides?: Partial<${type}>`, type, literal), + ); + } else { + dataBlocks.push(declareFunction(name, "", type, body)); + } + } + if (unbuildable.length > 0) { + 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 + .map((key) => ` - ${key}`) + .join("\n")}`, + ); + } + + const sorted = operations + .map((operation, index) => ({ operation, index })) + .sort((a, b) => { + const [left, right] = [a, b].map((entry) => + specificity(entry.operation.path), + ); + return left < right ? -1 : left > right ? 1 : a.index - b.index; + }) + .map((entry) => entry.operation); + + const helpers = new Set<"answer" | "json" | "text" | "empty">(); + const handlerBlocks: string[] = []; + const handlerNames: string[] = []; + const skipped: string[] = []; + let usesTypes = false; + + for (const operation of sorted) { + if (!MSW_METHODS.has(operation.method)) { + skipped.push(`${operation.method.toUpperCase()} ${operation.path}`); + continue; + } + const response = pickResponse(operation); + const status = + response && /^\d+$/.test(response.status) ? Number(response.status) : 200; + const kind = response?.mediaType + ? mediaKind(response.mediaType) + : undefined; + const hasBody = + response?.schema !== undefined && + operation.method !== "head" && + !NULL_BODY_STATUSES.has(status) && + (kind === "json" || kind === "text") && + // A body typed `unknown` has nothing for a mock to follow. + renderSchema(response.schema, readCtx) !== "unknown"; + + const name = `${operation.functionName}Handler`; + handlerNames.push(name); + const path = mswPath(operation.path); + const call = `http.${operation.method}`; + + if (!response || !hasBody) { + helpers.add("empty"); + handlerBlocks.push( + `export const ${name} = (override?: HttpResponseResolver) =>\n ${call}(${path}, override ?? empty(${status}));`, + ); + continue; + } + + const statusIndex = /^\d+$/.test(response.status) + ? response.status + : JSON.stringify(response.status); + const type = `Types.${operation.typeNames.responses}[${statusIndex}]`; + const mockName = uniqueName(`${operation.functionName}ResponseMock`, used); + const value = + (response.example === undefined + ? undefined + : exampleValue(response.schema, response.example, valueCtx, " ")) ?? + mockValue(response.schema, valueCtx, " "); + dataBlocks.push( + declareFunction(mockName, "", type, value ?? noValue(type)), + ); + + usesTypes = true; + helpers.add("answer"); + helpers.add(kind === "text" ? "text" : "json"); + handlerBlocks.push( + `export const ${name} = (override?: ${type} | HttpResponseResolver) =>\n ${call}(\n ${path},\n answer(override, mocks.${mockName}, ${kind === "text" ? "text" : "json"}(${status})),\n );`, + ); + } + if (skipped.length > 0) { + warnings.push( + `--mock: MSW has no handler for these methods, so the operations are left out:\n${skipped + .map((where) => ` - ${where}`) + .join("\n")}`, + ); + } + + const { ext } = options; + const typesImport = `import type * as Types from "../requests/types.gen${ext}";`; + const data = [ + HEADER.trimEnd(), + DATA_INTRO, + // With nothing to mock the file still has to be a module. + ...(dataBlocks.length > 0 ? [typesImport, ...dataBlocks] : ["export {};"]), + ].join("\n\n"); + + const mswModule = options.mswMajor === 2 ? "msw" : "msw/http"; + const hasHandlers = handlerBlocks.length > 0; + const mswImport = hasHandlers + ? `import {\n type HttpHandler,\n HttpResponse,\n type HttpResponseResolver,\n http,\n} from "${mswModule}";` + : `import type { HttpHandler } from "${mswModule}";`; + const imports = [ + mswImport, + ...(usesTypes + ? [typesImport, `import * as mocks from "./data${ext}";`] + : []), + ].join("\n"); + const helperBlocks: string[] = []; + if (helpers.has("answer")) { + helperBlocks.push( + `/** Answers with \`override\` when it is a body, and lets it answer when it is a resolver. */ +const answer = ( + override: T | HttpResponseResolver | undefined, + mock: () => T, + respond: (body: T) => Response, +): HttpResponseResolver => + typeof override === "function" + ? (override as HttpResponseResolver) + : () => respond(override === undefined ? mock() : (override as T));`, + ); + } + if (helpers.has("json")) { + helperBlocks.push( + `const json = (status: number) => (body: unknown) => + HttpResponse.json(body as Parameters[0], { + status, + });`, + ); + } + if (helpers.has("text")) { + helperBlocks.push( + `const text = (status: number) => (body: unknown) => + HttpResponse.text(String(body), { status });`, + ); + } + if (helpers.has("empty")) { + helperBlocks.push( + `const empty = + (status: number): HttpResponseResolver => + () => + new HttpResponse(null, { status });`, + ); + } + const list = hasHandlers + ? `export const handlers: HttpHandler[] = [\n${handlerNames + .map((name) => ` ${name}(),`) + .join("\n")}\n];` + : "export const handlers: HttpHandler[] = [];"; + const handlers = [ + HEADER.trimEnd(), + HANDLERS_INTRO, + imports, + ...helperBlocks, + ...handlerBlocks, + list, + ].join("\n\n"); + + return { + files: [ + { name: "data.ts", content: `${data}\n` }, + { name: "handlers.ts", content: `${handlers}\n` }, + { + name: "index.ts", + content: `${HEADER}\nexport * from "./data${ext}";\nexport * from "./handlers${ext}";\n`, + }, + ], + warnings, + }; +} diff --git a/src/client/emitSdk.mts b/src/client/emitSdk.mts index b06bbc9..6197ab9 100644 --- a/src/client/emitSdk.mts +++ b/src/client/emitSdk.mts @@ -254,9 +254,14 @@ export function emitSdk( blocks.push(code); } const typeImports = [...used].sort().join(", "); + // Only the operations use `client` and `RequestResult`, and an import that + // nothing uses is an error under `noUnusedLocals`. + const hasOperations = blocks.length > 0; const imports = [ - `import { client } from "./client.gen${options.ext}";`, - `import type { Client, Options as Options2, RequestResult, TDataShape } from "./runtime.gen${options.ext}";`, + ...(hasOperations + ? [`import { client } from "./client.gen${options.ext}";`] + : []), + `import type { Client, Options as Options2, ${hasOperations ? "RequestResult, " : ""}TDataShape } from "./runtime.gen${options.ext}";`, ]; const transformers = [...(options.transformers?.values() ?? [])].sort(); if (transformers.length > 0) { @@ -278,7 +283,7 @@ ${docComment({ description: "You can provide a client instance returned by `crea ${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; };`; - return `${HEADER}\n${imports.join("\n")}\n\n${optionsType}\n\n${blocks.join("\n\n")}\n`; + return `${HEADER}\n${[imports.join("\n"), optionsType, ...blocks].join("\n\n")}\n`; } /** The option that holds the base URL, spelled the way each client does. */ diff --git a/src/client/emitTypes.mts b/src/client/emitTypes.mts index aa4343a..092505b 100644 --- a/src/client/emitTypes.mts +++ b/src/client/emitTypes.mts @@ -157,6 +157,27 @@ function enumKey(name: string): string { return /^(0|[1-9]\d*)$/.test(name) ? name : propertyKey(name); } +/** + * Whether a component schema is declared as an enum of its own (`--enums`): a + * TypeScript enum, or an object of its values with the type of them. + */ +export function isEnumDeclaration(schema: Json, enumsMode: EnumsMode): boolean { + if (!enumsMode) return false; + const values: unknown[] = Array.isArray(schema?.enum) ? schema.enum : []; + const isMember = (value: unknown) => + typeof value === "string" || typeof value === "number"; + // A TypeScript enum can only hold strings and numbers, an object anything. + return ( + values.some((value) => value !== null) && + values.every( + (value) => + isMember(value) || + (enumsMode === "javascript" && + (value === null || typeof value === "boolean")), + ) + ); +} + function emitComponentSchema( schema: Json, key: string, @@ -169,19 +190,8 @@ function emitComponentSchema( deprecated: schema?.deprecated, }); const values: unknown[] = Array.isArray(schema?.enum) ? schema.enum : []; - const isMember = (value: unknown) => - typeof value === "string" || typeof value === "number"; - // A TypeScript enum can only hold strings and numbers, an object anything. - const isLiteralEnum = - values.some((value) => value !== null) && - values.every( - (value) => - isMember(value) || - (enumsMode === "javascript" && - (value === null || typeof value === "boolean")), - ); - if (enumsMode && isLiteralEnum) { + if (isEnumDeclaration(schema, enumsMode)) { const used = new Set(); const memberNames = schema["x-enum-varnames"] ?? schema["x-enumNames"]; const descriptions = schema["x-enum-descriptions"]; diff --git a/src/client/index.mts b/src/client/index.mts index b5759bc..7f6a3c8 100644 --- a/src/client/index.mts +++ b/src/client/index.mts @@ -1,6 +1,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import type { GeneratedFile, OperationInfo } from "../types.mjs"; +import { emitMocks, type MswMajor } from "./emitMocks.mjs"; import { emitSchemas, type SchemasMode } from "./emitSchemas.mjs"; import { type ClientKind, @@ -23,9 +24,11 @@ import { import { renderSchema, type SchemaCtx } from "./schema.mjs"; import { bundleExternalRefs, type Doc, loadSpec } from "./spec.mjs"; +export type { MswMajor } from "./emitMocks.mjs"; export type { SchemasMode } from "./emitSchemas.mjs"; export type { ClientKind } from "./emitSdk.mjs"; export type { EnumsMode } from "./emitTypes.mjs"; +export { detectMswMajor } from "./msw.mjs"; export { SpecError } from "./spec.mjs"; export { detectImportExtension, findNearestTsConfigPath } from "./tsconfig.mjs"; @@ -36,6 +39,11 @@ export interface ClientGenOptions { enums?: EnumsMode; /** `.js` for Node16/NodeNext module resolution, otherwise empty. */ importExtension: "" | ".js"; + /** + * Also generate mock data and MSW request handlers, written for this major + * version of MSW. Off when not set. + */ + mocks?: { mswMajor: MswMajor }; /** Name operations after the HTTP method and path instead of operationId. */ noOperationId?: boolean; /** Query parameter used for pagination. */ @@ -54,6 +62,8 @@ export interface ClientGenOptions { export interface GeneratedClient { files: GeneratedFile[]; + /** The files of the mocks directory, when `mocks` is set. */ + mockFiles?: GeneratedFile[]; operations: OperationInfo[]; /** Type names exported from `types.gen.ts`. */ modelNames: string[]; @@ -199,9 +209,19 @@ export async function generateClient( files.push({ name: "schemas.gen.ts", content: schemas }); } + const mocks = options.mocks + ? emitMocks(operations, ctx, { + mswMajor: options.mocks.mswMajor, + enums: options.enums, + ext, + }) + : undefined; + if (mocks) warnings.push(...mocks.warnings); + const emittedTypes = new Set(types.exportedNames); return { files, + mockFiles: mocks?.files, operations: operations.map((operation) => toOperationInfo(operation, ctx, options.pageParam, emittedTypes), ), diff --git a/src/client/mockValue.mts b/src/client/mockValue.mts new file mode 100644 index 0000000..73fa549 --- /dev/null +++ b/src/client/mockValue.mts @@ -0,0 +1,1002 @@ +import { propertyKey } from "./naming.mjs"; +import { + componentSchemaKey, + componentSchemaView, + discriminatorValues, + hasBinaryContent, + hasFlag, + hasObjectKeywords, + impliedType, + inheritedRequired, + isDateString, + isNullableSchema, + isRequiredOnly, + OMITTED_PROPERTY, + renderSchema, + requiresProperty, + type SchemaCtx, + schemaKinds, +} from "./schema.mjs"; +import { + getByPointer, + type Json, + refSiblingSchema, + resolveRef, +} from "./spec.mjs"; + +/** + * What the values of a mock are built with. A value is a TypeScript expression + * of the type `renderSchema` gives the same schema, so the two read a schema + * the same way. + */ +export interface MockValueCtx { + /** The context the response types are rendered with (`read` mode). */ + schema: SchemaCtx; + /** + * The call of a component schema's mock function. Undefined while that mock + * is being built: a value that held itself would never end. + */ + callMock: (key: string) => string | undefined; + /** + * The type to assert a literal of a component schema to, when the schema is + * a TypeScript enum (which no literal is assignable to). + */ + enumCast: (key: string) => string | undefined; +} + +/** What stands for a value of the type `unknown`. */ +const ANY_VALUE = "{}"; + +const DATE_TIME = "2024-01-01T00:00:00.000Z"; + +/** A fixed value for each `format` of a string. */ +const STRING_FORMATS: Record = { + "date-time": DATE_TIME, + date: "2024-01-01", + time: "00:00:00Z", + uuid: "00000000-0000-4000-8000-000000000000", + email: "user@example.com", + uri: "https://example.com", + url: "https://example.com", + hostname: "example.com", + ipv4: "192.0.2.1", + ipv6: "2001:db8::1", + byte: "c3RyaW5n", +}; + +type Entry = { spread: string } | { key: string; value: string }; + +/** An object literal's entries, or any other expression. */ +type Built = { entries: Entry[] } | { expr: string }; + +const SIMPLE_TYPES = ["string", "number", "integer", "boolean"]; + +function literalKey(name: string): string { + // `{ __proto__: … }` would set the prototype instead of a property. + return name === "__proto__" ? '["__proto__"]' : propertyKey(name); +} + +function objectLiteral(entries: Entry[], indent: string): string { + if (entries.length === 0) return "{}"; + const lines = entries.map((entry) => + "spread" in entry + ? `${indent} ...${entry.spread},` + : `${indent} ${literalKey(entry.key)}: ${entry.value},`, + ); + return `{\n${lines.join("\n")}\n${indent}}`; +} + +/** `items` are written for an array that sits at `indent`. */ +function arrayLiteral(items: string[], indent: string): string { + if (items.every((item) => !item.includes("\n"))) { + return `[${items.join(", ")}]`; + } + const lines = items.map((item) => `${indent} ${item},`); + return `[\n${lines.join("\n")}\n${indent}]`; +} + +/** Any JSON value as an expression, for a place whose type takes anything. */ +function jsonLiteral(value: Json, indent: string): string { + if (Array.isArray(value)) { + return arrayLiteral( + value.map((item) => jsonLiteral(item, `${indent} `)), + indent, + ); + } + if (value && typeof value === "object") { + return objectLiteral( + Object.entries(value).map(([key, item]) => ({ + key, + value: jsonLiteral(item, `${indent} `), + })), + indent, + ); + } + return JSON.stringify(value); +} + +function print(built: Built, indent: string): string { + return "expr" in built ? built.expr : objectLiteral(built.entries, indent); +} + +/** + * One object out of the parts of an intersection. What is spread comes first + * and a property wins over it, as the literal a discriminator pins has to; of + * two properties with one name the later one stays. A property that several + * members declare is not left to that: `buildComposed` gives it a part of its + * own, with a value of all of its declarations. + */ +function mergeObjects(parts: Built[], indent: string): Built { + const spreads: Entry[] = []; + const properties = new Map(); + for (const part of parts) { + if ("expr" in part) { + // Nothing to add, or what is spread already. + const repeated = spreads.some( + (entry) => "spread" in entry && entry.spread === part.expr, + ); + if (part.expr !== ANY_VALUE && !repeated) { + spreads.push({ spread: part.expr }); + } + continue; + } + for (const entry of part.entries) { + if ("spread" in entry) { + spreads.push(entry); + } else { + properties.delete(entry.key); + properties.set(entry.key, entry.value); + } + } + } + const entries: Entry[] = [ + ...spreads, + ...[...properties].map(([key, value]) => ({ key, value })), + ]; + // A lone spread is the value itself. + if (entries.length === 1 && "spread" in entries[0]) { + return { expr: entries[0].spread }; + } + return { expr: objectLiteral(entries, indent) }; +} + +function stringSample(schema: Json): string { + const fixed = STRING_FORMATS[schema.format]; + if (fixed !== undefined) return fixed; + let text = "string"; + if (typeof schema.maxLength === "number" && schema.maxLength < text.length) { + text = text.slice(0, Math.max(schema.maxLength, 0)); + } + if (typeof schema.minLength === "number" && schema.minLength > text.length) { + text = text.padEnd(schema.minLength, "x"); + } + return text; +} + +/** + * The first whole number a fraction goes into: 3 for 0.3, and 3 for 3e-21. + * An integer that is a multiple of the fraction is a multiple of it. Read off + * the digits and the exponent of the fraction, so that it is exact however + * small the fraction is; undefined when the whole number is too large to be + * one a mock can hold. + */ +function wholeMultiple(fraction: number): number | undefined { + const [mantissa, exponent = "0"] = fraction.toString().split("e"); + const [whole, decimals = ""] = mantissa.split("."); + // The fraction is `numerator / denominator`, with a power of ten for one + // of them. + const shift = decimals.length - Number(exponent); + const power = 10n ** BigInt(Math.abs(shift)); + const numerator = BigInt(whole + decimals) * (shift < 0 ? power : 1n); + const denominator = shift > 0 ? power : 1n; + let [a, b] = [numerator, denominator]; + while (b !== 0n) [a, b] = [b, a % b]; + const multiple = numerator / a; + return multiple <= BigInt(Number.MAX_SAFE_INTEGER) + ? Number(multiple) + : undefined; +} + +/** + * `1`, or where the schema does not allow it, a value in the range it gives + * that is a multiple of its `multipleOf`. + */ +function numberSample(schema: Json): number { + // OpenAPI 3.0 writes an exclusive bound as a flag, 3.1 as the bound itself. + let min = Number.NEGATIVE_INFINITY; + let minOpen = false; + if (typeof schema.minimum === "number") { + min = schema.minimum; + minOpen = schema.exclusiveMinimum === true; + } + if ( + typeof schema.exclusiveMinimum === "number" && + schema.exclusiveMinimum >= min + ) { + min = schema.exclusiveMinimum; + minOpen = true; + } + let max = Number.POSITIVE_INFINITY; + let maxOpen = false; + if (typeof schema.maximum === "number") { + max = schema.maximum; + maxOpen = schema.exclusiveMaximum === true; + } + if ( + typeof schema.exclusiveMaximum === "number" && + schema.exclusiveMaximum <= max + ) { + max = schema.exclusiveMaximum; + maxOpen = true; + } + const inRange = (value: number) => + (minOpen ? value > min : value >= min) && + (maxOpen ? value < max : value <= max); + + const integer = schema.type === "integer"; + let step: number | undefined = + typeof schema.multipleOf === "number" && schema.multipleOf > 0 + ? schema.multipleOf + : integer + ? 1 + : undefined; + if (integer && step !== undefined && !Number.isInteger(step)) { + const whole = wholeMultiple(step); + // With no whole multiple a mock can hold, zero is the only one left. + // Outside the range, the value is at least an integer inside it. + if (whole === undefined && inRange(0)) return 0; + step = whole ?? 1; + } + if (step !== undefined) { + const size = step; + // How many steps a bound is. Dividing by a fraction can miss a whole + // number by the rounding of the division (0.3 / 0.1), which is put + // right. The allowance is that error and no more: a bound that is not a + // whole number of steps (1000000000.75) must not become one. + const steps = (bound: number) => { + const exact = bound / size; + if (Number.isInteger(size)) return exact; + const whole = Math.round(exact); + const error = 8 * Number.EPSILON * Math.max(1, Math.abs(exact)); + return Math.abs(exact - whole) <= Math.min(error, 1e-3) ? whole : exact; + }; + const lowest = Math.ceil(steps(min)); + const highest = Math.floor(steps(max)); + // The multiple at or above 1, else the lowest in the range, else the + // highest. With no multiple in the range there is nothing better than the + // first. + const candidates = [ + Math.ceil(steps(1)), + ...(Number.isFinite(min) + ? [lowest + (minOpen && lowest === steps(min) ? 1 : 0)] + : []), + ...(Number.isFinite(max) + ? [highest - (maxOpen && highest === steps(max) ? 1 : 0)] + : []), + ].map((count) => { + // A whole step gives the number as it is. A fraction leaves the dust + // of its multiplication behind (0.1 * 3), which is rounded away, unless + // that would take a number out of the range it was in. + const exact = count * size; + if (Number.isInteger(size)) return exact; + const rounded = Number(exact.toPrecision(15)); + return inRange(rounded) || !inRange(exact) ? rounded : exact; + }); + return candidates.find(inRange) ?? candidates[0]; + } + + if (inRange(1)) return 1; + if (Number.isFinite(min) && Number.isFinite(max)) { + return minOpen || maxOpen ? (min + max) / 2 : min; + } + if (Number.isFinite(min)) return minOpen ? min + 1 : min; + return maxOpen ? max - 1 : max; +} + +function buildRef( + ref: string, + ctx: MockValueCtx, + indent: string, + seen: ReadonlySet, +): Built | undefined { + const { doc } = ctx.schema; + const key = componentSchemaKey(ref); + if (key !== undefined) { + // A reference to a schema that is not there is typed `unknown`. + if (!Object.hasOwn(doc.components?.schemas ?? {}, key)) { + return { expr: ANY_VALUE }; + } + const call = ctx.callMock(key); + return call === undefined ? undefined : { expr: call }; + } + if (seen.has(ref)) return { expr: ANY_VALUE }; + return build(getByPointer(doc, ref), ctx, indent, new Set(seen).add(ref)); +} + +function buildObject( + schema: Json, + ctx: MockValueCtx, + indent: string, + seen: ReadonlySet, +): Built | undefined { + const properties: Record = schema.properties ?? {}; + const required = new Set( + Array.isArray(schema.required) ? schema.required : [], + ); + const entries: Entry[] = []; + for (const [name, property] of Object.entries(properties)) { + if (hasFlag(ctx.schema.doc, property, "writeOnly")) continue; + const value = mockValue(property, ctx, `${indent} `, seen); + if (value === undefined) { + // Nothing ends here. A property that may be absent is left out. + if (required.has(name)) return undefined; + continue; + } + entries.push({ key: name, value }); + } + return { entries }; +} + +function buildArray( + schema: Json, + ctx: MockValueCtx, + indent: string, + seen: ReadonlySet, +): Built | undefined { + const inner = `${indent} `; + const itemOf = (item: Json) => mockValue(item, ctx, inner, seen); + const tuple = (schemas: Json[]): Built | undefined => { + const items = schemas.map(itemOf); + return items.some((item) => item === undefined) + ? undefined + : { expr: arrayLiteral(items as string[], indent) }; + }; + + if (Array.isArray(schema.prefixItems)) return tuple(schema.prefixItems); + const length = schema.maxItems; + if ( + schema.items && + typeof length === "number" && + length > 0 && + length === schema.minItems + ) { + return tuple(Array.from({ length }, () => schema.items)); + } + // An empty array is a value of any array type, and it ends a cycle. + const item = + schema.items === undefined || length === 0 + ? undefined + : itemOf(schema.items); + if (item === undefined) return { expr: "[]" }; + const count = + typeof schema.minItems === "number" + ? Math.min(Math.max(schema.minItems, 1), 10) + : 1; + return { + expr: arrayLiteral( + Array.from({ length: count }, () => item), + indent, + ), + }; +} + +/** + * Every declaration of each property in a schema and in what its `allOf` is + * made of. A member whose discriminator property is replaced + * (`Omit`) does not declare that one. + */ +function collectDeclarations( + ctx: MockValueCtx, + schema: Json, + into: Map, + omitted: ReadonlySet = new Set(), + visited: Set = new Set(), +): void { + const { doc } = ctx.schema; + const resolved = resolveRef(doc, schema); + if (!resolved || typeof resolved !== "object" || visited.has(resolved)) { + return; + } + visited.add(resolved); + const properties: Record = resolved.properties ?? {}; + for (const [name, property] of Object.entries(properties)) { + if (omitted.has(name) || hasFlag(doc, property, "writeOnly")) continue; + into.set(name, [...(into.get(name) ?? []), property]); + } + for (const member of Array.isArray(resolved.allOf) ? resolved.allOf : []) { + const marker = member?.[OMITTED_PROPERTY]; + collectDeclarations( + ctx, + member, + into, + typeof marker === "string" ? new Set(omitted).add(marker) : omitted, + visited, + ); + } +} + +/** + * A part of an intersection without the properties in `names`. A property the + * part writes out is dropped; one that comes with what it spreads (the mock of + * a referenced schema) is taken out of that. + */ +function withoutProperties( + part: Built, + source: Json, + names: ReadonlySet, + ctx: MockValueCtx, +): Built { + if ("entries" in part) { + return { + entries: part.entries.filter( + (entry) => "spread" in entry || !names.has(entry.key), + ), + }; + } + const declared = new Map(); + collectDeclarations(ctx, source, declared); + const present = [...names].filter((name) => declared.has(name)); + if (present.length === 0) return part; + const bindings = present.map( + (name, index) => `${literalKey(name)}: _${index}`, + ); + return { + expr: `(({ ${bindings.join(", ")}, ...rest }) => rest)(${part.expr})`, + }; +} + +/** The values a schema is limited to by its `const` or `enum`, if it is. */ +function pinnedValues( + ctx: MockValueCtx, + schema: Json, + depth = 0, +): Json[] | undefined { + const resolved = resolveRef(ctx.schema.doc, schema); + if (!resolved || typeof resolved !== "object" || depth > 16) return undefined; + if (resolved.const !== undefined) return [resolved.const]; + if (Array.isArray(resolved.enum)) return resolved.enum; + for (const member of Array.isArray(resolved.allOf) ? resolved.allOf : []) { + const pinned = pinnedValues(ctx, member, depth + 1); + if (pinned) return pinned; + } + return undefined; +} + +/** + * The value of an intersection that is not an object, from the values of its + * members (`parts`). Where a member limits the values (`string & "ok"`), only + * one of those that every member takes is a value of the type. Otherwise it + * is the value of a member that only allows the kinds every member does: of + * `(string | number) & number` the number, and of `string & number` nothing. + * Undefined when there is no value. + */ +function buildScalarIntersection( + members: Json[], + parts: Built[], + ctx: MockValueCtx, + indent: string, +): Built | undefined { + const { doc } = ctx.schema; + const pinned = members + .map((member) => pinnedValues(ctx, member)) + .find((values) => values !== undefined); + if (pinned === undefined) { + const shared = schemaKinds(doc, { allOf: members }); + const fitting = members.findIndex((member) => + [...schemaKinds(doc, member)].every((kind) => shared.has(kind)), + ); + if (fitting !== -1) return parts[fitting]; + // Every member allows more than they share. Only of `null` is the value + // known without a member to take it from. + return shared.size === 1 && shared.has("null") + ? { expr: "null" } + : undefined; + } + for (const candidate of pinned) { + const rendered = members.map((member) => + exampleValue(member, candidate, ctx, indent), + ); + if (rendered.some((value) => value === undefined)) continue; + // A member that is a TypeScript enum takes the value asserted to it + // (`("a" as Status)`). No literal is a value of an enum and of another + // enum or literal at once, so such an intersection has none. + const values = rendered as string[]; + const isAsserted = (value: string) => value.endsWith(")"); + const asserted = values.filter(isAsserted); + if (asserted.length === 0) return { expr: values[0] }; + const pinnedElsewhere = members.some( + (member, index) => + !isAsserted(values[index]) && pinnedValues(ctx, member) !== undefined, + ); + return asserted.length > 1 || pinnedElsewhere + ? undefined + : { expr: asserted[0] }; + } + return undefined; +} + +/** + * A schema composed of others. `allOf` and the schema's own properties make + * one object; of a `oneOf` or `anyOf` the first member that ends is taken. + */ +function buildComposed( + schema: Json, + ctx: MockValueCtx, + indent: string, + seen: ReadonlySet, +): Built | undefined { + const { doc } = ctx.schema; + const parts: Built[] = []; + + const members: Json[] = Array.isArray(schema.allOf) ? schema.allOf : []; + if (members.length > 0) { + // What the `allOf` makes required is written out, as the type repeats it: + // the member that declares it may leave it out. It goes first, so that a + // member with a value of its own for the property keeps it. + const required = inheritedRequired(doc, schema); + const names = Object.keys(required); + if (names.length > 0) { + const part = buildObject( + { properties: required, required: names }, + ctx, + indent, + seen, + ); + if (part === undefined) return undefined; + parts.push(part); + } + } + const typed: Json[] = []; + const firstTyped = parts.length; + for (const member of members) { + // A member that says nothing about the type adds nothing to the value. + if (isRequiredOnly(member)) continue; + if (renderSchema(member, ctx.schema) === "unknown") continue; + const part = buildNullable(member, ctx, indent, seen); + if (part === undefined) return undefined; + typed.push(member); + parts.push(part); + } + + if (hasObjectKeywords(schema)) { + const own = buildObject(schema, ctx, indent, seen); + if (own === undefined) return undefined; + parts.push(own); + } + + const isObject = schemaKinds(doc, schema).has("object"); + if (isObject) { + // A property that several members declare has to be a value of every + // declaration (`{ a: { x } } & { a: { y } }`), which neither member's own + // value of it is. It is built from all of them, and goes after the + // members so that it replaces theirs. + const declarations = new Map(); + collectDeclarations(ctx, schema, declarations); + const shared: Entry[] = []; + const impossible = new Set(); + for (const [name, schemas] of declarations) { + if (schemas.length < 2) continue; + const value = mockValue({ allOf: schemas }, ctx, `${indent} `, seen); + if (value !== undefined) { + shared.push({ key: name, value }); + } else if (requiresProperty(doc, schema, name)) { + return undefined; + } else { + // No value is one of every declaration, and the property may be + // absent: it is taken out of what the members give. + impossible.add(name); + } + } + if (impossible.size > 0) { + const sources: Json[] = [ + ...typed, + ...(parts.length > firstTyped + typed.length ? [schema] : []), + ]; + sources.forEach((source, index) => { + const at = firstTyped + index; + parts[at] = withoutProperties(parts[at], source, impossible, ctx); + }); + } + if (shared.length > 0) parts.push({ entries: shared }); + } else if (typed.length > 1) { + const scalar = buildScalarIntersection( + typed, + parts.slice(firstTyped, firstTyped + typed.length), + ctx, + indent, + ); + if (scalar === undefined) return undefined; + // It stands for every `allOf` member. + parts.splice(firstTyped, typed.length, scalar); + } + + for (const key of ["oneOf", "anyOf"] as const) { + const options: Json[] = Array.isArray(schema[key]) ? schema[key] : []; + if (options.length === 0) continue; + let chosen: Built | undefined; + for (const option of options) { + const part = buildNullable(option, ctx, indent, seen); + if (part === undefined) continue; + const values = discriminatorValues( + option, + schema.discriminator, + ctx.schema, + ); + chosen = values + ? { + entries: [ + { spread: print(part, indent) }, + { + key: schema.discriminator.propertyName, + value: jsonLiteral(values[0], `${indent} `), + }, + ], + } + : part; + break; + } + if (chosen === undefined) return undefined; + parts.push(chosen); + } + + if (parts.length === 0) return { expr: ANY_VALUE }; + if (parts.length === 1) return parts[0]; + // Only objects can be put together. Of anything else the first part stands + // for the whole. + return isObject ? mergeObjects(parts, indent) : parts[0]; +} + +function build( + schema: Json, + ctx: MockValueCtx, + indent: string, + seen: ReadonlySet, +): Built | undefined { + if (schema === false) return undefined; + if (!schema || typeof schema !== "object") return { expr: ANY_VALUE }; + + if (typeof schema.$ref === "string") { + if (typeof schema[OMITTED_PROPERTY] !== "string") { + const siblings = refSiblingSchema(ctx.schema.doc, schema); + if (siblings) { + return build( + { allOf: [{ $ref: schema.$ref }, siblings] }, + ctx, + indent, + seen, + ); + } + } + return buildRef(schema.$ref, ctx, indent, seen); + } + + // What the specification gives as a value comes before anything made up. + const examples = [ + schema.example, + ...(Array.isArray(schema.examples) ? schema.examples.slice(0, 1) : []), + schema.default, + ]; + for (const example of examples) { + if (example === undefined) continue; + const value = exampleValue(schema, example, ctx, indent); + if (value !== undefined) return { expr: value }; + } + + if (schema.const !== undefined) { + return { expr: jsonLiteral(schema.const, indent) }; + } + if (Array.isArray(schema.enum)) { + return schema.enum.length === 0 + ? undefined + : { expr: jsonLiteral(schema.enum[0], indent) }; + } + + if ( + (Array.isArray(schema.allOf) && schema.allOf.length > 0) || + (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) || + (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) + ) { + return buildComposed(schema, ctx, indent, seen); + } + + if (Array.isArray(schema.type)) { + const types: string[] = schema.type.filter( + (type: string) => type !== "null", + ); + for (const type of types) { + const built = build({ ...schema, type }, ctx, indent, seen); + if (built !== undefined) return built; + } + return schema.type.includes("null") ? { expr: "null" } : undefined; + } + + switch (schema.type) { + case "string": + if (schema.format === "binary" || hasBinaryContent(schema)) { + return { expr: "new Blob()" }; + } + return ctx.schema.dates && isDateString(schema) + ? { expr: `new Date(${JSON.stringify(DATE_TIME)})` } + : { expr: JSON.stringify(stringSample(schema)) }; + case "number": + case "integer": + return { expr: String(numberSample(schema)) }; + case "boolean": + return { expr: "true" }; + case "null": + return { expr: "null" }; + case "array": + return buildArray(schema, ctx, indent, seen); + case "object": + return buildObject(schema, ctx, indent, seen); + default: + if (impliedType(schema) === "object") { + return buildObject(schema, ctx, indent, seen); + } + if (impliedType(schema) === "array") { + return buildArray(schema, ctx, indent, seen); + } + return { expr: hasBinaryContent(schema) ? "new Blob()" : ANY_VALUE }; + } +} + +/** `build`, with `null` where the schema allows it and nothing else ends. */ +function buildNullable( + schema: Json, + ctx: MockValueCtx, + indent: string, + seen: ReadonlySet, +): Built | undefined { + const built = build(schema, ctx, indent, seen); + if (built !== undefined) return built; + // `renderSchema` ignores `nullable` next to a `$ref` and on an `enum`. + const nullable = + schema && + typeof schema === "object" && + typeof schema.$ref !== "string" && + !Array.isArray(schema.enum) && + isNullableSchema(schema); + return nullable ? { expr: "null" } : undefined; +} + +/** + * An expression for a value of the schema, written for a place at `indent`. + * Undefined when no value ends: the schema allows none, or holds itself + * through a mock that is still being built. + */ +export function mockValue( + schema: Json, + ctx: MockValueCtx, + indent = "", + seen: ReadonlySet = new Set(), +): string | undefined { + const built = buildNullable(schema, ctx, indent, seen); + return built === undefined ? undefined : print(built, indent); +} + +function sameJson(a: Json, b: Json): boolean { + return a === b || JSON.stringify(a) === JSON.stringify(b); +} + +function exampleArray( + schema: Json, + value: Json, + ctx: MockValueCtx, + indent: string, + depth: number, +): string | undefined { + if (!Array.isArray(value)) return undefined; + const prefix: Json[] = Array.isArray(schema.prefixItems) + ? schema.prefixItems + : []; + const open = schema.items !== undefined && schema.items !== false; + if (Array.isArray(schema.prefixItems)) { + // A tuple has every one of its items, and no more unless it is open. + if (value.length < prefix.length) return undefined; + if (!open && value.length > prefix.length) return undefined; + } else if ( + schema.items && + typeof schema.maxItems === "number" && + schema.maxItems > 0 && + schema.maxItems === schema.minItems && + value.length !== schema.maxItems + ) { + return undefined; + } + const items = value.map((item, index) => + exampleValue( + index < prefix.length ? prefix[index] : schema.items, + item, + ctx, + `${indent} `, + depth + 1, + ), + ); + return items.some((item) => item === undefined) + ? undefined + : arrayLiteral(items as string[], indent); +} + +function exampleObject( + schema: Json, + value: Json, + ctx: MockValueCtx, + indent: string, + depth: number, +): string | undefined { + if (typeof value !== "object" || Array.isArray(value)) return undefined; + const inner = `${indent} `; + const properties: Record = schema.properties ?? {}; + const required = new Set( + Array.isArray(schema.required) ? schema.required : [], + ); + const entries: Entry[] = []; + for (const [name, property] of Object.entries(properties)) { + if (hasFlag(ctx.schema.doc, property, "writeOnly")) continue; + if (!Object.hasOwn(value, name)) { + if (required.has(name)) return undefined; + continue; + } + const rendered = exampleValue(property, value[name], ctx, inner, depth + 1); + if (rendered === undefined) return undefined; + entries.push({ key: name, value: rendered }); + } + + // The type only takes other keys where it has an index signature. + const additional = schema.additionalProperties; + const typed = additional && typeof additional === "object"; + const open = + Object.keys(properties).length === 0 + ? additional !== false + : additional === true || typed; + if (open) { + for (const [name, extra] of Object.entries(value as Record)) { + if (Object.hasOwn(properties, name)) continue; + const rendered = typed + ? exampleValue(additional, extra, ctx, inner, depth + 1) + : jsonLiteral(extra, inner); + if (rendered === undefined) return undefined; + entries.push({ key: name, value: rendered }); + } + } + return objectLiteral(entries, indent); +} + +function exampleOfType( + schema: Json, + value: Json, + ctx: MockValueCtx, + indent: string, + depth: number, +): string | undefined { + const type = + SIMPLE_TYPES.includes(schema.type) || + schema.type === "array" || + schema.type === "object" + ? schema.type + : impliedType(schema); + switch (type) { + case "string": + if (typeof value !== "string") return undefined; + if (schema.format === "binary" || hasBinaryContent(schema)) { + return undefined; + } + if (ctx.schema.dates && isDateString(schema)) { + return Number.isNaN(Date.parse(value)) + ? undefined + : `new Date(${JSON.stringify(value)})`; + } + return JSON.stringify(value); + case "number": + case "integer": + return typeof value === "number" && + Number.isFinite(value) && + (type === "number" || Number.isInteger(value)) + ? String(value) + : undefined; + case "boolean": + return typeof value === "boolean" ? String(value) : undefined; + case "array": + return exampleArray(schema, value, ctx, indent, depth); + case "object": + return exampleObject(schema, value, ctx, indent, depth); + default: + // The type is `unknown`, which takes any value. + return hasBinaryContent(schema) ? undefined : jsonLiteral(value, indent); + } +} + +/** + * An example from the specification as an expression of the schema's type, or + * undefined when it is not a value of that type. Examples drift from their + * schemas, and one that did would not compile. A composed schema is not + * checked: its example is passed over, and the value is made up instead. + */ +export function exampleValue( + schema: Json, + value: Json, + ctx: MockValueCtx, + indent = "", + depth = 0, +): string | undefined { + if (schema === false || value === undefined || depth > 32) return undefined; + if (!schema || typeof schema !== "object") return jsonLiteral(value, indent); + const { doc } = ctx.schema; + + if (typeof schema.$ref === "string") { + if (refSiblingSchema(doc, schema)) return undefined; + const target = getByPointer(doc, schema.$ref); + if (target === undefined) return undefined; + const key = componentSchemaKey(schema.$ref); + if (key === undefined) { + return exampleValue(target, value, ctx, indent, depth + 1); + } + const rendered = exampleValue( + componentSchemaView(target, key, ctx.schema), + value, + ctx, + indent, + depth + 1, + ); + const cast = ctx.enumCast(key); + return rendered !== undefined && cast !== undefined + ? `(${rendered} as ${cast})` + : rendered; + } + + if ( + schema.oneOf !== undefined || + schema.anyOf !== undefined || + schema.not !== undefined || + schema.discriminator !== undefined || + schema.patternProperties !== undefined + ) { + return undefined; + } + if (Array.isArray(schema.allOf)) { + // `allOf` around one schema is how OpenAPI 3.0 documents a reference or + // makes it nullable. + // What the wrapper adds, the value would have to be checked against too. + if ( + schema.allOf.length !== 1 || + hasObjectKeywords(schema) || + (Array.isArray(schema.required) && schema.required.length > 0) + ) { + return undefined; + } + if (value === null) return isNullableSchema(schema) ? "null" : undefined; + return exampleValue(schema.allOf[0], value, ctx, indent, depth + 1); + } + + if (schema.const !== undefined) { + if (sameJson(schema.const, value)) return jsonLiteral(value, indent); + return value === null && isNullableSchema(schema) ? "null" : undefined; + } + if (Array.isArray(schema.enum)) { + return schema.enum.some((member: Json) => sameJson(member, value)) + ? jsonLiteral(value, indent) + : undefined; + } + + const types: unknown[] = Array.isArray(schema.type) + ? schema.type + : [schema.type]; + if (value === null) { + const untyped = schema.type === undefined && !impliedType(schema); + return isNullableSchema(schema) || types.includes("null") || untyped + ? "null" + : undefined; + } + for (const type of types) { + if (type === "null") continue; + const rendered = exampleOfType( + { ...schema, type }, + value, + ctx, + indent, + depth, + ); + if (rendered !== undefined) return rendered; + } + return undefined; +} diff --git a/src/client/msw.mts b/src/client/msw.mts new file mode 100644 index 0000000..69bc9ca --- /dev/null +++ b/src/client/msw.mts @@ -0,0 +1,32 @@ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import type { MswMajor } from "./emitMocks.mjs"; + +/** + * The major version of MSW the project in `cwd` has installed, which decides + * where the generated handlers import `http` from. Version 3 when MSW is not + * installed yet: that is what installing it now gives. + */ +export function detectMswMajor(cwd: string): { + major: MswMajor; + /** Set when the installed version cannot run the handlers. */ + warning?: string; +} { + let version: unknown; + try { + const require = createRequire(path.join(cwd, "package.json")); + version = JSON.parse( + readFileSync(require.resolve("msw/package.json"), "utf-8"), + ).version; + } catch { + return { major: 3 }; + } + const major = Number.parseInt(String(version), 10); + if (major >= 3) return { major: 3 }; + if (major === 2) return { major: 2 }; + return { + major: 2, + warning: `--mock: the handlers need MSW 2 or later, and version ${String(version)} is installed.`, + }; +} diff --git a/src/client/operations.mts b/src/client/operations.mts index 1f3638d..9dcf3a7 100644 --- a/src/client/operations.mts +++ b/src/client/operations.mts @@ -96,6 +96,10 @@ export interface ResponseIR { schema?: Json; /** Every media type the response declares. */ mediaTypes: string[]; + /** The media type `schema` and `example` are taken from. */ + mediaType?: string; + /** The body the media type gives as its `example`, or as the first of its `examples`. */ + example?: Json; } export interface SecurityIR { @@ -180,6 +184,27 @@ export function pickContent( return { mediaType, media }; } +/** The example of a media type: its `example`, or the first of its `examples`. */ +function mediaExample(doc: Doc, media: Json): Json { + if (!media || typeof media !== "object") return undefined; + if (media.example !== undefined) return media.example; + const examples = + media.examples && typeof media.examples === "object" + ? Object.values(media.examples as Record) + : []; + for (const raw of examples) { + let example: Json; + try { + example = deref(doc, raw); + } catch { + // An example that is not there is no example. + continue; + } + if (example?.value !== undefined) return example.value; + } + return undefined; +} + function buildJsDoc( summary: string | undefined, description: string | undefined, @@ -356,6 +381,8 @@ export function collectOperations( description: response.description, schema: content?.media?.schema, mediaTypes: Object.keys(response.content ?? {}), + mediaType: content?.mediaType, + example: mediaExample(doc, content?.media), }); } diff --git a/src/client/schema.mts b/src/client/schema.mts index ef13b8c..5b98630 100644 --- a/src/client/schema.mts +++ b/src/client/schema.mts @@ -153,7 +153,7 @@ function intersection(types: string[]): string { .join(" & "); } -function isNullableSchema(schema: Json): boolean { +export function isNullableSchema(schema: Json): boolean { return ( schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes("null")) @@ -176,7 +176,7 @@ function globalTypeRef(name: string, ctx: SchemaCtx): string { } /** Marks a `$ref` member of an `allOf` whose discriminator literal is replaced. */ -const OMITTED_PROPERTY = "x-orqc-omit"; +export const OMITTED_PROPERTY = "x-orqc-omit"; /** The discriminator of what an `allOf` builds on, if any. */ function findInheritedDiscriminator( @@ -201,7 +201,7 @@ function findInheritedDiscriminator( } /** True when a schema or what it is composed of requires `name`. */ -function requiresProperty( +export function requiresProperty( doc: Doc, schema: Json, name: string, @@ -220,27 +220,27 @@ function requiresProperty( } /** - * Render a component schema. A subtype that builds on a schema with a - * discriminator gets its own value of the discriminator property, from the - * mapping or else its name, so that a union of subtypes narrows on it. + * A component schema as it is rendered. A subtype that builds on a schema with + * a discriminator gets its own value of the discriminator property, from the + * mapping or else its name, so that a union of subtypes narrows on it. Any + * other schema is returned as it is. */ -export function renderComponentSchema( +export function componentSchemaView( schema: Json, key: string, ctx: SchemaCtx, -): string { +): Json { const discriminator = schema?.discriminator ? undefined : findInheritedDiscriminator(ctx.doc, schema); - if (!discriminator) return renderSchema(schema, ctx); + if (!discriminator) return schema; const property: string = discriminator.propertyName; const pinned = pinnedValues(schema, property, ctx); const allowed = valuesNaming(discriminator, key, pinned, (target) => isMappingTarget(target, key), ); - if (allowed.length === 0 || pinned?.length === 1) - return renderSchema(schema, ctx); + if (allowed.length === 0 || pinned?.length === 1) return schema; const members = schema.allOf.map((member: Json) => // A parent that is a subtype itself has a value of its own to replace. @@ -254,7 +254,16 @@ export function renderComponentSchema( required: requiresProperty(ctx.doc, schema, property) ? [property] : [], properties: { [property]: { enum: allowed } }, }; - return renderSchema({ ...schema, allOf: [...members, tag] }, ctx); + return { ...schema, allOf: [...members, tag] }; +} + +/** Render a component schema, as {@link componentSchemaView} shows it. */ +export function renderComponentSchema( + schema: Json, + key: string, + ctx: SchemaCtx, +): string { + return renderSchema(componentSchemaView(schema, key, ctx), ctx); } /** @@ -270,7 +279,7 @@ export function hasObjectKeywords(schema: Json): boolean { } /** What a schema without a `type` is taken for, going by its keywords. */ -function impliedType(schema: Json): "object" | "array" | undefined { +export function impliedType(schema: Json): "object" | "array" | undefined { if ( schema.properties || schema.patternProperties || @@ -523,7 +532,7 @@ const TEXT_MEDIA_TYPE = * Whether the schema is a file the way OpenAPI 3.1 writes one: a media type * that is not text, and no `contentEncoding` making a string of it. */ -function hasBinaryContent(schema: Json): boolean { +export function hasBinaryContent(schema: Json): boolean { const mediaType = schema.contentMediaType; return ( typeof mediaType === "string" && @@ -546,7 +555,7 @@ const TYPE_KEYWORDS = [ ]; /** An `allOf` member that declares nothing and only makes properties required. */ -function isRequiredOnly(member: Json): boolean { +export function isRequiredOnly(member: Json): boolean { if ( !member || typeof member !== "object" || @@ -609,40 +618,51 @@ function undeclaredRequired( } /** - * The properties an `allOf` requires while another of its members declares them. - * They are repeated with their own type, because an optional property - * intersected with `unknown` would stay `undefined`-able. The result is `{}` - * when there are none. + * The properties an `allOf` requires while another of its members declares + * them, each with its declaration. */ -function renderInheritedRequired( +export function inheritedRequired( + doc: Doc, schema: Json, - ctx: SchemaCtx, - indent: string, - seen: Seen, -): string { +): Record { const own: string[] = Array.isArray(schema.required) ? schema.required : []; const names = new Set([ ...own.filter((name) => !Object.hasOwn(schema.properties ?? {}, name)), ...schema.allOf.flatMap((member: Json) => { - const required = undeclaredRequired(ctx.doc, member); + const required = undeclaredRequired(doc, member); // A named schema drops what it requires and nobody declares, so an // `allOf` around it does too. return member?.$ref ? required.filter( - (name) => findDeclaredProperty(ctx.doc, schema, name) !== undefined, + (name) => findDeclaredProperty(doc, schema, name) !== undefined, ) : required; }), ]); - const properties = Object.fromEntries( + return Object.fromEntries( [...names].map((name) => [ name, - findDeclaredProperty(ctx.doc, schema, name) ?? {}, + findDeclaredProperty(doc, schema, name) ?? {}, ]), ); - return names.size === 0 +} + +/** + * {@link inheritedRequired} as an object type. The properties are repeated + * with their own type, because an optional property intersected with `unknown` + * would stay `undefined`-able. The result is `{}` when there are none. + */ +function renderInheritedRequired( + schema: Json, + ctx: SchemaCtx, + indent: string, + seen: Seen, +): string { + const properties = inheritedRequired(ctx.doc, schema); + const names = Object.keys(properties); + return names.length === 0 ? "{}" - : renderObject({ properties, required: [...names] }, ctx, indent, seen); + : renderObject({ properties, required: names }, ctx, indent, seen); } function renderRef( diff --git a/src/common.mts b/src/common.mts index cebb460..829cd64 100644 --- a/src/common.mts +++ b/src/common.mts @@ -1,6 +1,10 @@ import path from "node:path"; import type { LimitedUserConfig } from "./cli.mjs"; -import { queriesOutputPath, requestsOutputPath } from "./constants.mjs"; +import { + mocksOutputPath, + queriesOutputPath, + requestsOutputPath, +} from "./constants.mjs"; /** * Safely parse a value into a number. Checks for NaN and Infinity. @@ -59,3 +63,7 @@ export function buildRequestsOutputPath(outputPath: string) { export function buildQueriesOutputPath(outputPath: string) { return path.join(outputPath, queriesOutputPath); } + +export function buildMocksOutputPath(outputPath: string) { + return path.join(outputPath, mocksOutputPath); +} diff --git a/src/constants.mts b/src/constants.mts index ba36dd7..f7c36bb 100644 --- a/src/constants.mts +++ b/src/constants.mts @@ -1,6 +1,7 @@ export const defaultOutputPath = "openapi"; export const queriesOutputPath = "queries"; export const requestsOutputPath = "requests"; +export const mocksOutputPath = "mocks"; export const OpenApiRqFiles = { queries: "queries", diff --git a/src/format.mts b/src/format.mts index f04788e..1701918 100644 --- a/src/format.mts +++ b/src/format.mts @@ -52,20 +52,23 @@ export const processOutput = async ({ output, format, lint, + label = "queries", }: { output: string; + /** What `output` holds, for the progress message. */ + label?: string; format?: "prettier" | "biome"; lint?: "biome" | "eslint"; }) => { if (format) { const module = formatters[format]; - console.log(`✨ Running ${module.name} on queries`); + console.log(`✨ Running ${module.name} on ${label}`); sync(module.command, module.args(output)); } if (lint) { const module = linters[lint]; - console.log(`✨ Running ${module.name} on queries`); + console.log(`✨ Running ${module.name} on ${label}`); sync(module.command, module.args(output)); } }; diff --git a/src/generate.mts b/src/generate.mts index a4ae241..4237097 100644 --- a/src/generate.mts +++ b/src/generate.mts @@ -7,6 +7,7 @@ import type { ClientChoice, LimitedUserConfig } from "./cli.mjs"; import { type ClientKind, detectImportExtension, + detectMswMajor, findNearestTsConfigPath, type GeneratedClient, generateClient, @@ -14,6 +15,7 @@ import { writeGeneratedFiles, } from "./client/index.mjs"; import { + buildMocksOutputPath, buildQueriesOutputPath, buildRequestsOutputPath, formatOptions, @@ -102,6 +104,9 @@ async function runGenerate( // One answer for both directories: the queries import the requests. const importExtension = detectImportExtension(process.cwd()); + // The handlers import MSW the way the installed version exports it. + const msw = formattedOptions.mock ? detectMswMajor(process.cwd()) : undefined; + let generated: GeneratedClient; try { generated = await generateClient({ @@ -109,6 +114,7 @@ async function runGenerate( client, enums: formattedOptions.enums, importExtension, + mocks: msw ? { mswMajor: msw.major } : undefined, noOperationId: formattedOptions.noOperationId, pageParam: formattedOptions.pageParam, schemas: formattedOptions.noSchemas @@ -120,9 +126,14 @@ async function runGenerate( throw mapClientError(error, formattedOptions.input); } if (!runtime.silent) { + if (msw?.warning) console.warn(msw.warning); for (const warning of generated.warnings) console.warn(warning); } await writeGeneratedFiles(openApiOutputPath, generated.files); + const mocksOutputPath = buildMocksOutputPath(options.output); + if (generated.mockFiles) { + await writeGeneratedFiles(mocksOutputPath, generated.mockFiles); + } const source = createSource({ generated, @@ -141,6 +152,14 @@ async function runGenerate( format: formattedOptions.format, lint: formattedOptions.lint, }); + if (generated.mockFiles) { + await processOutput({ + output: mocksOutputPath, + format: formattedOptions.format, + lint: formattedOptions.lint, + label: "mocks", + }); + } if (options.agentsMd) { const file = agentsFilePath(options.agentsMd); diff --git a/src/runCli.mts b/src/runCli.mts index 151b019..fa8f8c5 100644 --- a/src/runCli.mts +++ b/src/runCli.mts @@ -117,6 +117,12 @@ export function buildProgram( "--omitInitialPageParam", "Send no initial page parameter at all (overrides --initialPageParam)", ) + .addOption( + new Option( + "--mock ", + "Also generate mock data and request handlers from the specification, into /mocks", + ).choices(["msw"]), + ) .option( "--agentsMd [file]", "Also keep a short guide for coding agents (how to look operations up in the output) in AGENTS.md, or in the file named", diff --git a/tests/client/__snapshots__/mocks.test.ts.snap b/tests/client/__snapshots__/mocks.test.ts.snap new file mode 100644 index 0000000..6e828e6 --- /dev/null +++ b/tests/client/__snapshots__/mocks.test.ts.snap @@ -0,0 +1,1122 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`emitMocks > the mock data and the handlers of a specification > data.ts 1`] = ` +"// This file is auto-generated by @7nohe/openapi-react-query-codegen + +/** + * Mock data for the schemas and the responses of the API. The values are fixed: + * an \`example\` or a \`default\` from the specification where it has one, and + * otherwise the first \`enum\` value or a value made up from the type. + */ + +import type * as Types from "../requests/types.gen"; + +export function petMock(overrides?: Partial): Types.Pet { + return { + id: 1, + name: "Pochi", + status: statusMock(), + tags: ["string"], + bornAt: "2024-01-01T00:00:00.000Z", + owner: ownerMock(), + ...overrides, + }; +} + +export function statusMock(): Types.Status { + return "available"; +} + +export function priorityMock(): Types.Priority { + return 2; +} + +export function ownerMock(overrides?: Partial): Types.Owner { + return { + name: "string", + pets: [], + partner: null, + ...overrides, + }; +} + +export function nodeMock(): Types.Node { + return {} as unknown as Types.Node; +} + +export function ringMock(): Types.Ring { + return {} as unknown as Types.Ring; +} + +export function danglingMock(): Types.Dangling { + return { + id: 1, + }; +} + +export function exampledMock(overrides?: Partial): Types.Exampled { + return { + ratio: 0.5, + fixed: "x", + nullableFixed: null, + status: "pending", + noStatus: null, + maybeText: null, + textOrNumber: "text", + unknownNull: null, + anyItems: [1, "a"], + nested: { + tags: ["a", "b"], + }, + ...overrides, + }; +} + +export function clashAMock(overrides?: Partial): Types.ClashA { + return { + k: "a", + "odd key": "a", + a: "string", + ...overrides, + }; +} + +export function clashBMock(overrides?: Partial): Types.ClashB { + return { + b: "string", + ...overrides, + }; +} + +export function clashMock(overrides?: Partial): Types.Clash { + return { + ...(({ k: _0, "odd key": _1, ...rest }) => rest)(clashAMock()), + ...clashBMock(), + id: 1, + ...overrides, + }; +} + +export function withMetaMock(overrides?: Partial): Types.WithMeta { + return { + meta: { + x: "string", + }, + ...overrides, + }; +} + +export function moreMetaMock(overrides?: Partial): Types.MoreMeta { + return { + ...withMetaMock(), + meta: { + x: "string", + y: 1, + }, + ...overrides, + }; +} + +export function maybeMock(): Types.Maybe { + return null; +} + +export function animalMock(): Types.Animal { + return { + ...catMock(), + kind: "cat", + }; +} + +export function catMock(overrides?: Partial): Types.Cat { + return { + kind: "string", + lives: 9, + ...overrides, + }; +} + +export function dogMock(overrides?: Partial): Types.Dog { + return { + kind: "string", + goodBoy: true, + ...overrides, + }; +} + +export function vehicleMock(overrides?: Partial): Types.Vehicle { + return { + type: "string", + wheels: 4, + ...overrides, + }; +} + +export function carMock(overrides?: Partial): Types.Car { + return { + ...vehicleMock(), + doors: 0, + type: "Car", + ...overrides, + }; +} + +export function sportsCarMock(overrides?: Partial): Types.SportsCar { + return { + ...carMock(), + doors: 0, + turbo: true, + type: "SportsCar", + ...overrides, + }; +} + +export function settingsMock(overrides?: Partial): Types.Settings { + return { + theme: "dark", + limits: { + daily: 10, + }, + flags: { + beta: true, + }, + point: [1, "two"], + pair: [1, 2], + anything: { + nested: [1, null], + }, + ...overrides, + }; +} + +export function driftedMock(overrides?: Partial): Types.Drifted { + return { + number: 1, + text: "string", + flag: true, + choice: "a", + fixed: "x", + list: [1], + notList: [1], + short: [1, 1], + long: [1], + sized: [1, 1], + object: { + id: 1, + }, + notObject: { + id: 1, + }, + nulled: "string", + typedExtra: {}, + when: "not a date", + file: new Blob(), + union: "string", + merged: { + a: "string", + b: "string", + }, + closed: {}, + nullType: null, + referenced: statusMock(), + nullableRef: statusMock(), + picture: new Blob(), + noItems: [], + siblings: { + dog: { + ...dogMock(), + name: "string", + }, + }, + missing: { + gone: {}, + }, + fixedNull: "x", + ...overrides, + }; +} + +export function shapesMock(overrides?: Partial): Types.Shapes { + return { + date: "2024-01-01", + uuid: "00000000-0000-4000-8000-000000000000", + email: "user@example.com", + short: "str", + long: "stringxx", + atLeast: 5, + above: 6, + aboveFlag: 6, + atMost: -3, + below: -1, + belowFlag: -1, + even: 4, + flag: true, + nothing: null, + fixed: "fixed", + fixedObject: { + a: [1, 2], + }, + choice: null, + nullableNever: null, + defaulted: 20, + firstExample: "first", + severalTypes: "string", + onlyNull: null, + untyped: { + a: "string", + }, + untypedList: ["string"], + blob: new Blob(), + file: new Blob(), + three: ["string", "string", "string"], + none: [], + anyItems: [], + pair: [1, 1], + tuple: ["string", statusMock()], + dictionary: {}, + nullableStatus: statusMock(), + narrowed: "string", + withSiblings: { + ...dogMock(), + name: "string", + }, + anything: {}, + aliasWithNothing: dogMock(), + aliasOrAnything: dogMock(), + taggedWithMore: { + ...catMock(), + more: "string", + kind: "cat", + }, + onlyDocumented: {}, + twice: "string", + halfOpen: 0.25, + negativeEven: -4, + tenths: 0.3, + openSteps: 3, + openStepsBelow: -3, + noMultiple: 2, + between: 2, + betweenOpen: 2.5, + looserExclusive: 5, + wholeOfFraction: 3, + smallFraction: 3, + farWholeMultiple: 62831853, + exponentFraction: 1, + tinyFraction: 3, + everyInteger: 1, + noWholeMultiple: 0, + noWholeMultipleAboveZero: 2, + betweenFractions: 1000000001, + betweenFractionsOfTenths: 100000000.1, + bigTenths: 170000000000.1, + bigInteger: 1700000000001, + clash: clashMock(), + overlap: { + a: { + x: "string", + y: 1, + }, + }, + conflicting: {}, + moreMeta: moreMetaMock(), + petPlus: { + ...dogMock(), + extra: "string", + }, + stringAndOk: "ok", + okAndString: "ok", + numberOfEither: 1, + nullOfBoth: null, + statusAndSold: "sold", + statusAndText: "available", + wrapperRequired: { + ...dogMock(), + goodBoy: true, + }, + oneOfPrimitives: 1, + animal: animalMock(), + car: sportsCarMock(), + missing: {}, + inlined: ["string"], + loop: {}, + priority: priorityMock(), + "odd key": "string", + requiredLoop: { + node: nodeMock(), + }, + readOnly: "string", + ...overrides, + }; +} + +export function listPetsResponseMock(): Types.ListPetsResponses[200] { + return [ + { + id: 7, + name: "Momo", + status: "sold", + bornAt: "2020-05-17T09:00:00Z", + }, + ]; +} + +export function createPetResponseMock(): Types.CreatePetResponses[201] { + return { + id: 8, + name: "Kuro", + tags: ["black", "small"], + }; +} + +export function countPetsResponseMock(): Types.CountPetsResponses[200] { + return 3; +} + +export function listAnimalsResponseMock(): Types.ListAnimalsResponses["default"] { + return [animalMock()]; +} + +export function getStatusResponseMock(): Types.GetStatusResponses[200] { + return "ok"; +} + +export function getRangedResponseMock(): Types.GetRangedResponses[206] { + return 1; +} + +export function getImpossibleResponseMock(): Types.GetImpossibleResponses[200] { + return {} as unknown as Types.GetImpossibleResponses[200]; +} + +export function getShapesResponseMock(): Types.GetShapesResponses[200] { + return shapesMock(); +} + +export function listMyPetsResponseMock(): Types.ListMyPetsResponses["2XX"] { + return [petMock()]; +} + +export function getArchiveResponseMock(): Types.GetArchiveResponses[200] { + return "string"; +} + +export function getFileResponseMock(): Types.GetFileResponses[200] { + return "string"; +} + +export function getPetResponseMock(): Types.GetPetResponses[200] { + return petMock(); +} + +export function getCafeResponseMock(): Types.GetCafeResponses[200] { + return "string"; +} + +export function getTagResponseMock(): Types.GetTagResponses[200] { + return "string"; +} + +export function pingBetaResponseMock(): Types.PingBetaResponses[200] { + return "string"; +} +" +`; + +exports[`emitMocks > the mock data and the handlers of a specification > handlers.ts 1`] = ` +"// This file is auto-generated by @7nohe/openapi-react-query-codegen + +/** + * MSW request handlers for the API. Each answers with the mock of its + * operation's successful response. Pass a handler another body, or a resolver + * of your own, to answer with something else: + * + * setupWorker(findPetsHandler([]), ...handlers) + * + * MSW uses the first handler that matches, so yours go before \`handlers\`. + */ + +import { + type HttpHandler, + HttpResponse, + type HttpResponseResolver, + http, +} from "msw/http"; +import type * as Types from "../requests/types.gen"; +import * as mocks from "./data"; + +/** Answers with \`override\` when it is a body, and lets it answer when it is a resolver. */ +const answer = ( + override: T | HttpResponseResolver | undefined, + mock: () => T, + respond: (body: T) => Response, +): HttpResponseResolver => + typeof override === "function" + ? (override as HttpResponseResolver) + : () => respond(override === undefined ? mock() : (override as T)); + +const json = (status: number) => (body: unknown) => + HttpResponse.json(body as Parameters[0], { + status, + }); + +const text = (status: number) => (body: unknown) => + HttpResponse.text(String(body), { status }); + +const empty = + (status: number): HttpResponseResolver => + () => + new HttpResponse(null, { status }); + +export const listPetsHandler = (override?: Types.ListPetsResponses[200] | HttpResponseResolver) => + http.get( + "*/pets", + answer(override, mocks.listPetsResponseMock, json(200)), + ); + +export const createPetHandler = (override?: Types.CreatePetResponses[201] | HttpResponseResolver) => + http.post( + "*/pets", + answer(override, mocks.createPetResponseMock, json(201)), + ); + +export const headPetsHandler = (override?: HttpResponseResolver) => + http.head("*/pets", override ?? empty(200)); + +export const countPetsHandler = (override?: Types.CountPetsResponses[200] | HttpResponseResolver) => + http.get( + new RegExp("/pets:count/?$"), + answer(override, mocks.countPetsResponseMock, json(200)), + ); + +export const listAnimalsHandler = (override?: Types.ListAnimalsResponses["default"] | HttpResponseResolver) => + http.get( + "*/animals", + answer(override, mocks.listAnimalsResponseMock, json(200)), + ); + +export const getStatusHandler = (override?: Types.GetStatusResponses[200] | HttpResponseResolver) => + http.get( + "*/status", + answer(override, mocks.getStatusResponseMock, text(200)), + ); + +export const exportPetsHandler = (override?: HttpResponseResolver) => + http.get("*/export", override ?? empty(200)); + +export const getAnythingHandler = (override?: HttpResponseResolver) => + http.get("*/anything", override ?? empty(200)); + +export const getNothingHandler = (override?: HttpResponseResolver) => + http.get("*/nothing", override ?? empty(200)); + +export const getRangedHandler = (override?: Types.GetRangedResponses[206] | HttpResponseResolver) => + http.get( + "*/ranged", + answer(override, mocks.getRangedResponseMock, json(206)), + ); + +export const getImpossibleHandler = (override?: Types.GetImpossibleResponses[200] | HttpResponseResolver) => + http.get( + "*/impossible", + answer(override, mocks.getImpossibleResponseMock, json(200)), + ); + +export const getShapesHandler = (override?: Types.GetShapesResponses[200] | HttpResponseResolver) => + http.get( + "*/shapes", + answer(override, mocks.getShapesResponseMock, json(200)), + ); + +export const listMyPetsHandler = (override?: Types.ListMyPetsResponses["2XX"] | HttpResponseResolver) => + http.get( + "*/pets/mine", + answer(override, mocks.listMyPetsResponseMock, json(200)), + ); + +export const archivePetHandler = (override?: HttpResponseResolver) => + http.delete(new RegExp("/pets/([^/]+):archive/?$"), override ?? empty(202)); + +export const getArchiveHandler = (override?: Types.GetArchiveResponses[200] | HttpResponseResolver) => + http.get( + new RegExp("/archives/([^/]+)([^/]+)/?$"), + answer(override, mocks.getArchiveResponseMock, json(200)), + ); + +export const getFileHandler = (override?: Types.GetFileResponses[200] | HttpResponseResolver) => + http.get( + new RegExp("/files/([^/]+)\\\\.\\\\(json\\\\|yaml\\\\)/$"), + answer(override, mocks.getFileResponseMock, json(200)), + ); + +export const getPetHandler = (override?: Types.GetPetResponses[200] | HttpResponseResolver) => + http.get( + "*/pets/:pet_id", + answer(override, mocks.getPetResponseMock, json(200)), + ); + +export const deletePetHandler = (override?: HttpResponseResolver) => + http.delete("*/pets/:pet_id", override ?? empty(204)); + +export const getCafeHandler = (override?: Types.GetCafeResponses[200] | HttpResponseResolver) => + http.get( + new RegExp("/caf%C3%A9/([^/]+)/?$"), + answer(override, mocks.getCafeResponseMock, json(200)), + ); + +export const getTagHandler = (override?: Types.GetTagResponses[200] | HttpResponseResolver) => + http.get( + "*/tags/:_1st/", + answer(override, mocks.getTagResponseMock, json(200)), + ); + +export const pingBetaHandler = (override?: Types.PingBetaResponses[200] | HttpResponseResolver) => + http.get( + new RegExp("/v([^/]+)beta/ping/?$"), + answer(override, mocks.pingBetaResponseMock, json(200)), + ); + +export const handlers: HttpHandler[] = [ + listPetsHandler(), + createPetHandler(), + headPetsHandler(), + countPetsHandler(), + listAnimalsHandler(), + getStatusHandler(), + exportPetsHandler(), + getAnythingHandler(), + getNothingHandler(), + getRangedHandler(), + getImpossibleHandler(), + getShapesHandler(), + listMyPetsHandler(), + archivePetHandler(), + getArchiveHandler(), + getFileHandler(), + getPetHandler(), + deletePetHandler(), + getCafeHandler(), + getTagHandler(), + pingBetaHandler(), +]; +" +`; + +exports[`emitMocks > the mock data and the handlers of a specification > index.ts 1`] = ` +"// This file is auto-generated by @7nohe/openapi-react-query-codegen + +export * from "./data"; +export * from "./handlers"; +" +`; + +exports[`emitMocks > the mock data with TypeScript enums and Date objects > data.ts 1`] = ` +"// This file is auto-generated by @7nohe/openapi-react-query-codegen + +/** + * Mock data for the schemas and the responses of the API. The values are fixed: + * an \`example\` or a \`default\` from the specification where it has one, and + * otherwise the first \`enum\` value or a value made up from the type. + */ + +import type * as Types from "../requests/types.gen"; + +export function petMock(overrides?: Partial): Types.Pet { + return { + id: 1, + name: "Pochi", + status: statusMock(), + tags: ["string"], + bornAt: new Date("2024-01-01T00:00:00.000Z"), + owner: ownerMock(), + ...overrides, + }; +} + +export function statusMock(): Types.Status { + return "available" as Types.Status; +} + +export function priorityMock(): Types.Priority { + return 2 as Types.Priority; +} + +export function ownerMock(overrides?: Partial): Types.Owner { + return { + name: "string", + pets: [], + partner: null, + ...overrides, + }; +} + +export function nodeMock(): Types.Node { + return {} as unknown as Types.Node; +} + +export function ringMock(): Types.Ring { + return {} as unknown as Types.Ring; +} + +export function danglingMock(): Types.Dangling { + return { + id: 1, + }; +} + +export function exampledMock(overrides?: Partial): Types.Exampled { + return { + ratio: 0.5, + fixed: "x", + nullableFixed: null, + status: ("pending" as Types.Status), + noStatus: null, + maybeText: null, + textOrNumber: "text", + unknownNull: null, + anyItems: [1, "a"], + nested: { + tags: ["a", "b"], + }, + ...overrides, + }; +} + +export function clashAMock(overrides?: Partial): Types.ClashA { + return { + k: "a", + "odd key": "a", + a: "string", + ...overrides, + }; +} + +export function clashBMock(overrides?: Partial): Types.ClashB { + return { + b: "string", + ...overrides, + }; +} + +export function clashMock(overrides?: Partial): Types.Clash { + return { + ...(({ k: _0, "odd key": _1, ...rest }) => rest)(clashAMock()), + ...clashBMock(), + id: 1, + ...overrides, + }; +} + +export function withMetaMock(overrides?: Partial): Types.WithMeta { + return { + meta: { + x: "string", + }, + ...overrides, + }; +} + +export function moreMetaMock(overrides?: Partial): Types.MoreMeta { + return { + ...withMetaMock(), + meta: { + x: "string", + y: 1, + }, + ...overrides, + }; +} + +export function maybeMock(): Types.Maybe { + return null; +} + +export function animalMock(): Types.Animal { + return { + ...catMock(), + kind: "cat", + }; +} + +export function catMock(overrides?: Partial): Types.Cat { + return { + kind: "string", + lives: 9, + ...overrides, + }; +} + +export function dogMock(overrides?: Partial): Types.Dog { + return { + kind: "string", + goodBoy: true, + ...overrides, + }; +} + +export function vehicleMock(overrides?: Partial): Types.Vehicle { + return { + type: "string", + wheels: 4, + ...overrides, + }; +} + +export function carMock(overrides?: Partial): Types.Car { + return { + ...vehicleMock(), + doors: 0, + type: "Car", + ...overrides, + }; +} + +export function sportsCarMock(overrides?: Partial): Types.SportsCar { + return { + ...carMock(), + doors: 0, + turbo: true, + type: "SportsCar", + ...overrides, + }; +} + +export function settingsMock(overrides?: Partial): Types.Settings { + return { + theme: "dark", + limits: { + daily: 10, + }, + flags: { + beta: true, + }, + point: [1, "two"], + pair: [1, 2], + anything: { + nested: [1, null], + }, + ...overrides, + }; +} + +export function driftedMock(overrides?: Partial): Types.Drifted { + return { + number: 1, + text: "string", + flag: true, + choice: "a", + fixed: "x", + list: [1], + notList: [1], + short: [1, 1], + long: [1], + sized: [1, 1], + object: { + id: 1, + }, + notObject: { + id: 1, + }, + nulled: "string", + typedExtra: {}, + when: new Date("2024-01-01T00:00:00.000Z"), + file: new Blob(), + union: "string", + merged: { + a: "string", + b: "string", + }, + closed: {}, + nullType: null, + referenced: statusMock(), + nullableRef: statusMock(), + picture: new Blob(), + noItems: [], + siblings: { + dog: { + ...dogMock(), + name: "string", + }, + }, + missing: { + gone: {}, + }, + fixedNull: "x", + ...overrides, + }; +} + +export function shapesMock(overrides?: Partial): Types.Shapes { + return { + date: new Date("2024-01-01T00:00:00.000Z"), + uuid: "00000000-0000-4000-8000-000000000000", + email: "user@example.com", + short: "str", + long: "stringxx", + atLeast: 5, + above: 6, + aboveFlag: 6, + atMost: -3, + below: -1, + belowFlag: -1, + even: 4, + flag: true, + nothing: null, + fixed: "fixed", + fixedObject: { + a: [1, 2], + }, + choice: null, + nullableNever: null, + defaulted: 20, + firstExample: "first", + severalTypes: "string", + onlyNull: null, + untyped: { + a: "string", + }, + untypedList: ["string"], + blob: new Blob(), + file: new Blob(), + three: ["string", "string", "string"], + none: [], + anyItems: [], + pair: [1, 1], + tuple: ["string", statusMock()], + dictionary: {}, + nullableStatus: statusMock(), + narrowed: "string", + withSiblings: { + ...dogMock(), + name: "string", + }, + anything: {}, + aliasWithNothing: dogMock(), + aliasOrAnything: dogMock(), + taggedWithMore: { + ...catMock(), + more: "string", + kind: "cat", + }, + onlyDocumented: {}, + twice: "string", + halfOpen: 0.25, + negativeEven: -4, + tenths: 0.3, + openSteps: 3, + openStepsBelow: -3, + noMultiple: 2, + between: 2, + betweenOpen: 2.5, + looserExclusive: 5, + wholeOfFraction: 3, + smallFraction: 3, + farWholeMultiple: 62831853, + exponentFraction: 1, + tinyFraction: 3, + everyInteger: 1, + noWholeMultiple: 0, + noWholeMultipleAboveZero: 2, + betweenFractions: 1000000001, + betweenFractionsOfTenths: 100000000.1, + bigTenths: 170000000000.1, + bigInteger: 1700000000001, + clash: clashMock(), + overlap: { + a: { + x: "string", + y: 1, + }, + }, + conflicting: {}, + moreMeta: moreMetaMock(), + petPlus: { + ...dogMock(), + extra: "string", + }, + stringAndOk: "ok", + okAndString: "ok", + numberOfEither: 1, + nullOfBoth: null, + statusAndText: ("available" as Types.Status), + wrapperRequired: { + ...dogMock(), + goodBoy: true, + }, + oneOfPrimitives: 1, + animal: animalMock(), + car: sportsCarMock(), + missing: {}, + inlined: ["string"], + loop: {}, + priority: priorityMock(), + "odd key": "string", + requiredLoop: { + node: nodeMock(), + }, + readOnly: "string", + ...overrides, + }; +} + +export function listPetsResponseMock(): Types.ListPetsResponses[200] { + return [ + { + id: 7, + name: "Momo", + status: ("sold" as Types.Status), + bornAt: new Date("2020-05-17T09:00:00Z"), + }, + ]; +} + +export function createPetResponseMock(): Types.CreatePetResponses[201] { + return { + id: 8, + name: "Kuro", + tags: ["black", "small"], + }; +} + +export function countPetsResponseMock(): Types.CountPetsResponses[200] { + return 3; +} + +export function listAnimalsResponseMock(): Types.ListAnimalsResponses["default"] { + return [animalMock()]; +} + +export function getStatusResponseMock(): Types.GetStatusResponses[200] { + return "ok"; +} + +export function getRangedResponseMock(): Types.GetRangedResponses[206] { + return 1; +} + +export function getImpossibleResponseMock(): Types.GetImpossibleResponses[200] { + return {} as unknown as Types.GetImpossibleResponses[200]; +} + +export function getShapesResponseMock(): Types.GetShapesResponses[200] { + return shapesMock(); +} + +export function listMyPetsResponseMock(): Types.ListMyPetsResponses["2XX"] { + return [petMock()]; +} + +export function getArchiveResponseMock(): Types.GetArchiveResponses[200] { + return "string"; +} + +export function getFileResponseMock(): Types.GetFileResponses[200] { + return "string"; +} + +export function getPetResponseMock(): Types.GetPetResponses[200] { + return petMock(); +} + +export function getCafeResponseMock(): Types.GetCafeResponses[200] { + return "string"; +} + +export function getTagResponseMock(): Types.GetTagResponses[200] { + return "string"; +} + +export function pingBetaResponseMock(): Types.PingBetaResponses[200] { + return "string"; +} +" +`; + +exports[`emitMocks > values > an example of a schema is used where the schema is 1`] = ` +"export function settingsMock(overrides?: Partial): Types.Settings { + return { + theme: "dark", + limits: { + daily: 10, + }, + flags: { + beta: true, + }, + point: [1, "two"], + pair: [1, 2], + anything: { + nested: [1, null], + }, + ...overrides, + }; +}" +`; + +exports[`emitMocks > values > an example that is a value of the schema is used as it is 1`] = ` +"export function exampledMock(overrides?: Partial): Types.Exampled { + return { + ratio: 0.5, + fixed: "x", + nullableFixed: null, + status: "pending", + noStatus: null, + maybeText: null, + textOrNumber: "text", + unknownNull: null, + anyItems: [1, "a"], + nested: { + tags: ["a", "b"], + }, + ...overrides, + }; +}" +`; + +exports[`emitMocks > values > an example that is not a value of the schema is passed over 1`] = ` +"export function driftedMock(overrides?: Partial): Types.Drifted { + return { + number: 1, + text: "string", + flag: true, + choice: "a", + fixed: "x", + list: [1], + notList: [1], + short: [1, 1], + long: [1], + sized: [1, 1], + object: { + id: 1, + }, + notObject: { + id: 1, + }, + nulled: "string", + typedExtra: {}, + when: "not a date", + file: new Blob(), + union: "string", + merged: { + a: "string", + b: "string", + }, + closed: {}, + nullType: null, + referenced: statusMock(), + nullableRef: statusMock(), + picture: new Blob(), + noItems: [], + siblings: { + dog: { + ...dogMock(), + name: "string", + }, + }, + missing: { + gone: {}, + }, + fixedNull: "x", + ...overrides, + }; +}" +`; diff --git a/tests/client/mocks.test.ts b/tests/client/mocks.test.ts new file mode 100644 index 0000000..9fd628f --- /dev/null +++ b/tests/client/mocks.test.ts @@ -0,0 +1,693 @@ +import { describe, expect, test } from "vitest"; +import { + type ClientGenOptions, + generateClient, +} from "../../src/client/index.mjs"; +import { generateTestClient } from "../utils"; + +async function mocksOf( + inputFile: string, + overrides: Partial = {}, +) { + const generated = await generateTestClient(inputFile, { + mocks: { mswMajor: 3 }, + ...overrides, + }); + const file = (name: string) => + generated.mockFiles?.find((entry) => entry.name === name)?.content ?? ""; + return { + data: file("data.ts"), + handlers: file("handlers.ts"), + index: file("index.ts"), + warnings: generated.warnings, + }; +} + +/** Mocks for a specification written inline, as JSON. */ +async function mocksOfDocument(document: Record) { + const generated = await generateClient({ + input: JSON.stringify({ + openapi: "3.1.0", + info: { title: "Inline", version: "1" }, + paths: {}, + ...document, + }), + client: "fetch", + importExtension: "", + pageParam: "page", + mocks: { mswMajor: 3 }, + }); + const file = (name: string) => + generated.mockFiles?.find((entry) => entry.name === name)?.content ?? ""; + return { + data: file("data.ts"), + handlers: file("handlers.ts"), + warnings: generated.warnings, + }; +} + +/** The body of one generated function. */ +function functionBody(source: string, name: string): string { + const start = source.indexOf(`export function ${name}(`); + expect(start, `${name} is generated`).toBeGreaterThan(-1); + return source.slice(start, source.indexOf("\n}\n", start) + 2); +} + +describe("emitMocks", () => { + test("generates nothing unless asked", async () => { + const generated = await generateTestClient("mocks.yaml"); + expect(generated.mockFiles).toBeUndefined(); + }); + + test("the mock data and the handlers of a specification", async () => { + const mocks = await mocksOf("mocks.yaml"); + expect(mocks.data).toMatchSnapshot("data.ts"); + expect(mocks.handlers).toMatchSnapshot("handlers.ts"); + expect(mocks.index).toMatchSnapshot("index.ts"); + }); + + test("the mock data with TypeScript enums and Date objects", async () => { + const mocks = await mocksOf("mocks.yaml", { + enums: "typescript", + useDateType: true, + }); + expect(mocks.data).toMatchSnapshot("data.ts"); + }); + + test("relative imports take the extension of the project", async () => { + const mocks = await mocksOf("petstore.yaml", { importExtension: ".js" }); + expect(mocks.data).toContain('from "../requests/types.gen.js"'); + expect(mocks.handlers).toContain('from "./data.js"'); + expect(mocks.index).toContain('export * from "./handlers.js"'); + }); + + test("imports http from where the MSW version exports it", async () => { + const v3 = await mocksOf("petstore.yaml"); + expect(v3.handlers).toContain('} from "msw/http";'); + const v2 = await mocksOf("petstore.yaml", { mocks: { mswMajor: 2 } }); + expect(v2.handlers).toContain('} from "msw";'); + expect(v2.handlers.replace('from "msw"', 'from "msw/http"')).toBe( + v3.handlers, + ); + }); + + test("a specification with nothing to mock still gives valid files", async () => { + const mocks = await mocksOfDocument({}); + expect(mocks.data).not.toContain("import"); + expect(mocks.handlers).toContain( + 'import type { HttpHandler } from "msw/http";', + ); + expect(mocks.handlers).toContain( + "export const handlers: HttpHandler[] = [];", + ); + expect(mocks.handlers).not.toContain("const answer"); + }); + + describe("values", () => { + test("an example of the whole body comes first", async () => { + const { data } = await mocksOf("mocks.yaml"); + const body = functionBody(data, "listPetsResponseMock"); + expect(body).toContain('name: "Momo"'); + expect(body).toContain('bornAt: "2020-05-17T09:00:00Z"'); + expect(body).not.toContain("petMock()"); + }); + + test("of several named examples the first with a value is taken", async () => { + const { data } = await mocksOf("mocks.yaml"); + const body = functionBody(data, "createPetResponseMock"); + expect(body).toContain('name: "Kuro"'); + expect(body).toContain('tags: ["black", "small"]'); + // The type has no such property, and a literal with it would not compile. + expect(body).not.toContain("extra"); + }); + + test("an example that is not a value of the schema is passed over", async () => { + const { data } = await mocksOf("mocks.yaml"); + expect(functionBody(data, "getPetResponseMock")).toContain( + "return petMock();", + ); + const drifted = functionBody(data, "driftedMock"); + expect(drifted).toMatchSnapshot(); + for (const wrong of ["1.5", '"yes"', '"c"', '"y"', "two", "no id"]) { + expect(drifted).not.toContain(wrong); + } + }); + + test("an example of a schema is used where the schema is", async () => { + const { data } = await mocksOf("mocks.yaml"); + expect(functionBody(data, "petMock")).toContain('name: "Pochi"'); + expect(functionBody(data, "priorityMock")).toContain("return 2;"); + expect(functionBody(data, "settingsMock")).toMatchSnapshot(); + }); + + test("a value is made up to fit the constraints of the schema", async () => { + const { data } = await mocksOf("mocks.yaml"); + const shapes = functionBody(data, "shapesMock"); + for (const line of [ + 'date: "2024-01-01",', + 'short: "str",', + 'long: "stringxx",', + "atLeast: 5,", + "above: 6,", + "aboveFlag: 6,", + "atMost: -3,", + "below: -1,", + "belowFlag: -1,", + "even: 4,", + "defaulted: 20,", + 'firstExample: "first",', + 'three: ["string", "string", "string"],', + "none: [],", + "pair: [1, 1],", + 'tuple: ["string", statusMock()],', + "nullableNever: null,", + ]) { + expect(shapes).toContain(` ${line}\n`); + } + // No value exists, so the properties are left out. + expect(shapes).not.toContain("impossible"); + expect(shapes).not.toContain("never:"); + // What the API never returns is not in a response either. + expect(shapes).not.toContain("writeOnly"); + expect(shapes).toContain('readOnly: "string"'); + }); + + test("an example that is a value of the schema is used as it is", async () => { + const { data } = await mocksOf("mocks.yaml"); + expect(functionBody(data, "exampledMock")).toMatchSnapshot(); + }); + + test("a reference to a schema that is not there is any value", async () => { + const { data } = await mocksOfDocument({ + paths: { + "/x": { + get: { + operationId: "getX", + responses: { + 200: { + description: "ok", + content: { + "application/json": { + schema: { + type: "object", + properties: { + gone: { $ref: "#/components/schemas/Gone" }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }); + expect(functionBody(data, "getXResponseMock")).toContain("gone: {},"); + }); + + test("what an allOf makes required cannot be cut", async () => { + const { data, warnings } = await mocksOfDocument({ + components: { + schemas: { + Child: { + allOf: [ + { $ref: "#/components/schemas/Base" }, + { required: ["child"] }, + ], + }, + Base: { + type: "object", + properties: { child: { $ref: "#/components/schemas/Child" } }, + }, + }, + }, + }); + expect(functionBody(data, "childMock")).toContain( + "return {} as unknown as Types.Child;", + ); + expect(warnings[0]).toContain(" - Child"); + }); + + test("a number is inside both bounds and a multiple of its step", async () => { + const { data } = await mocksOf("mocks.yaml"); + const shapes = functionBody(data, "shapesMock"); + for (const line of [ + // Half of an interval that is open at one end + "halfOpen: 0.25,", + "betweenOpen: 2.5,", + "between: 2,", + // The multiple inside the range, not the next one up + "negativeEven: -4,", + "tenths: 0.3,", + "openSteps: 3,", + "openStepsBelow: -3,", + // An exclusive bound looser than the inclusive one changes nothing + "looserExclusive: 5,", + // No multiple is in the range + "noMultiple: 2,", + // An integer that is a multiple of a fraction is still an integer + "wholeOfFraction: 3,", + // However small the fraction is, or however far the whole number + "smallFraction: 3,", + "farWholeMultiple: 62831853,", + "exponentFraction: 1,", + "tinyFraction: 3,", + "everyInteger: 1,", + // The whole number is too large to hold, which leaves zero + "noWholeMultiple: 0,", + // Zero is out of the range, so at least an integer inside it + "noWholeMultipleAboveZero: 2,", + // Rounding the dust away must not leave the range + "bigTenths: 170000000000.1,", + // A bound between two steps is not taken for one of them + "betweenFractions: 1000000001,", + "betweenFractionsOfTenths: 100000000.1,", + // A whole step is not rounded to a few digits + "bigInteger: 1700000000001,", + ]) { + expect(shapes).toContain(` ${line}\n`); + } + }); + + test("a property several allOf members declare is a value of all of them", async () => { + const { data } = await mocksOf("mocks.yaml"); + const shapes = functionBody(data, "shapesMock"); + expect(shapes).toContain( + ' overlap: {\n a: {\n x: "string",\n y: 1,\n },\n },', + ); + // Also when one of the declarations is in a referenced schema. + expect(functionBody(data, "moreMetaMock")).toContain( + ' ...withMetaMock(),\n meta: {\n x: "string",\n y: 1,\n },', + ); + // No value of `k` is both, and it may be absent: it is left out. + expect(shapes).toContain(" conflicting: {},\n"); + // The same schema twice is spread once. + expect(shapes).toContain( + ' petPlus: {\n ...dogMock(),\n extra: "string",\n },', + ); + }); + + test("an optional property no value fits is taken out, a required one ends the object", async () => { + const { data, warnings } = await mocksOf("mocks.yaml"); + // `k` and "odd key" come with ClashA's mock and are taken out of it. + // The rest of the object stays, with what it requires. + expect(functionBody(data, "clashMock")).toContain( + ' ...(({ k: _0, "odd key": _1, ...rest }) => rest)(clashAMock()),\n ...clashBMock(),\n id: 1,\n ...overrides,', + ); + expect(warnings.join("\n")).not.toContain("Clash"); + // Required, so there is no object at all. + expect(functionBody(data, "shapesMock")).not.toContain("requiredClash"); + }); + + test("an intersection that limits the values takes one every member allows", async () => { + const { data } = await mocksOf("mocks.yaml"); + const shapes = functionBody(data, "shapesMock"); + expect(shapes).toContain(' stringAndOk: "ok",\n'); + expect(shapes).toContain(' okAndString: "ok",\n'); + expect(shapes).toContain(' statusAndSold: "sold",\n'); + expect(shapes).toContain(' statusAndText: "available",\n'); + expect(shapes).not.toContain("noCommon"); + expect(shapes).not.toContain("statusAndPriority"); + + // A literal is not a value of a TypeScript enum and of something else + // that limits the values. + const enums = await mocksOf("mocks.yaml", { enums: "typescript" }); + const typed = functionBody(enums.data, "shapesMock"); + expect(typed).toContain( + ' statusAndText: ("available" as Types.Status),\n', + ); + expect(typed).not.toContain("statusAndSold"); + expect(typed).not.toContain("statusAndPriority"); + }); + + test("an intersection of types takes the value of a member that fits all", async () => { + const { data } = await mocksOf("mocks.yaml"); + const shapes = functionBody(data, "shapesMock"); + // `string & number` has no value. + expect(shapes).not.toContain("stringAndNumber"); + // `(string | number) & number`: the second member's value, not "string". + expect(shapes).toContain(" numberOfEither: 1,\n"); + // `(string | null) & (number | null)` is `null`. + expect(shapes).toContain(" nullOfBoth: null,\n"); + // A number, but neither member's own value is known to be one. + expect(shapes).not.toContain("numberOfNeither"); + }); + + test("a reference that only leads back to itself limits nothing", async () => { + const { data } = await mocksOfDocument({ + components: { + schemas: { + Loop: { allOf: [{ $ref: "#/components/schemas/Loop" }] }, + Holder: { + type: "object", + properties: { + value: { + allOf: [ + { type: "string" }, + { allOf: [true, { $ref: "#/components/schemas/Loop" }] }, + ], + }, + }, + }, + }, + }, + }); + expect(functionBody(data, "holderMock")).toContain('value: "string",'); + }); + + test("an example is not taken for a wrapper that requires more", async () => { + const { data } = await mocksOf("mocks.yaml"); + expect(functionBody(data, "shapesMock")).toContain( + " wrapperRequired: {\n ...dogMock(),\n goodBoy: true,\n },", + ); + }); + + test("dates are Date objects when the types say so", async () => { + const { data } = await mocksOf("mocks.yaml", { useDateType: true }); + expect(functionBody(data, "petMock")).toContain( + 'bornAt: new Date("2024-01-01T00:00:00.000Z"),', + ); + expect(functionBody(data, "listPetsResponseMock")).toContain( + 'bornAt: new Date("2020-05-17T09:00:00Z"),', + ); + // Not a date, so the example is passed over. + expect(functionBody(data, "driftedMock")).toContain( + 'when: new Date("2024-01-01T00:00:00.000Z"),', + ); + }); + + test("a literal of a TypeScript enum is asserted to it", async () => { + const { data } = await mocksOf("mocks.yaml", { enums: "typescript" }); + expect(functionBody(data, "statusMock")).toContain( + 'return "available" as Types.Status;', + ); + expect(functionBody(data, "listPetsResponseMock")).toContain( + 'status: ("sold" as Types.Status),', + ); + const plain = await mocksOf("mocks.yaml", { enums: "javascript" }); + expect(functionBody(plain.data, "statusMock")).toContain( + 'return "available";', + ); + }); + + test("a discriminator's value goes with the member it stands for", async () => { + const { data } = await mocksOf("mocks.yaml"); + expect(functionBody(data, "animalMock")).toContain( + ' ...catMock(),\n kind: "cat",', + ); + // A subtype names itself, and what it makes required is written out. + expect(functionBody(data, "sportsCarMock")).toContain( + ' ...carMock(),\n doors: 0,\n turbo: true,\n type: "SportsCar",\n ...overrides,', + ); + }); + + test("only one object type takes overrides", async () => { + const { data } = await mocksOf("mocks.yaml"); + expect(data).toContain( + "export function petMock(overrides?: Partial): Types.Pet {", + ); + expect(data).toContain("export function animalMock(): Types.Animal {"); + expect(data).toContain("export function statusMock(): Types.Status {"); + expect(data).toContain("export function maybeMock(): Types.Maybe {"); + }); + + test("an alias of an object spreads what it stands for", async () => { + const { data } = await mocksOfDocument({ + components: { + schemas: { + Base: { type: "object", properties: { id: { type: "integer" } } }, + Alias: { allOf: [{ $ref: "#/components/schemas/Base" }] }, + Nothing: { type: "object" }, + }, + }, + }); + expect(functionBody(data, "aliasMock")).toContain( + " return {\n ...baseMock(),\n ...overrides,\n };", + ); + expect(functionBody(data, "nothingMock")).toContain( + " return {\n ...overrides,\n };", + ); + }); + + test("an example can hold a key that would set the prototype", async () => { + const { data } = await mocksOfDocument({ + components: { + schemas: { + Loose: { + type: "object", + example: JSON.parse('{"__proto__": 1, "odd key": [{"a": null}]}'), + }, + }, + }, + }); + const body = functionBody(data, "looseMock"); + expect(body).toContain('["__proto__"]: 1,'); + expect(body).toContain('"odd key": ['); + }); + }); + + describe("schemas that hold themselves", () => { + test("a reference back is cut where the schema allows", async () => { + const { data } = await mocksOf("mocks.yaml"); + // Pet is built first, so the owner's pets are the cut. + expect(functionBody(data, "petMock")).toContain("owner: ownerMock(),"); + const owner = functionBody(data, "ownerMock"); + expect(owner).toContain("pets: [],"); + expect(owner).toContain("partner: null,"); + expect(owner).not.toContain("bestFriend"); + expect(functionBody(data, "maybeMock")).toContain("return null;"); + }); + + test("a schema that requires itself gets an empty object and a warning", async () => { + const { data, warnings } = await mocksOf("mocks.yaml"); + expect(functionBody(data, "nodeMock")).toContain( + "return {} as unknown as Types.Node;", + ); + expect(warnings).toContainEqual( + expect.stringMatching( + /no value can be written[\s\S]*\n {2}- Node\n {2}- Ring$/, + ), + ); + }); + + test("a schema cut under another one is built again on its own", async () => { + const { data, warnings } = await mocksOfDocument({ + components: { + schemas: { + A: { + type: "object", + properties: { b: { $ref: "#/components/schemas/B" } }, + }, + B: { + type: "object", + required: ["a"], + properties: { a: { $ref: "#/components/schemas/A" } }, + }, + }, + }, + }); + // Under A, B cannot leave `a` out, so A goes without it. + expect(functionBody(data, "aMock")).not.toContain("bMock()"); + expect(functionBody(data, "bMock")).toContain("a: aMock(),"); + expect(warnings).toEqual([]); + }); + + test("gives up on schemas that all require each other", async () => { + const keys = ["A", "B", "C", "D", "E"]; + const { data, warnings } = await mocksOfDocument({ + components: { + schemas: Object.fromEntries( + keys.map((key) => { + const others = keys.filter((other) => other !== key); + return [ + key, + { + type: "object", + required: others, + properties: Object.fromEntries( + others.map((other) => [ + other, + { $ref: `#/components/schemas/${other}` }, + ]), + ), + }, + ]; + }), + ), + }, + }); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain(" - A"); + for (const key of keys) { + expect(data).toContain(`export function ${key.toLowerCase()}Mock(`); + } + }); + }); + + describe("handlers", () => { + test("a fixed path comes before a parameter in its place", async () => { + const { handlers } = await mocksOf("mocks.yaml"); + const list = handlers.slice(handlers.indexOf("export const handlers")); + expect(list.indexOf("listMyPetsHandler()")).toBeLessThan( + list.indexOf("getPetHandler()"), + ); + // A parameter with text around it is tighter than one alone. + expect(list.indexOf("archivePetHandler()")).toBeLessThan( + list.indexOf("deletePetHandler()"), + ); + // Paths that do not compete keep the order of the specification. + expect(list.indexOf("listPetsHandler()")).toBeLessThan( + list.indexOf("listAnimalsHandler()"), + ); + }); + + test("path parameters become MSW parameters under any base URL", async () => { + const { handlers } = await mocksOf("mocks.yaml"); + expect(handlers).toContain('"*/pets/:pet_id"'); + expect(handlers).toContain('"*/pets/mine"'); + // A name MSW would not read as one parameter is made into one. + expect(handlers).toContain('"*/tags/:_1st/"'); + }); + + test("a path with MSW's own syntax in it is matched by a regular expression", async () => { + const { handlers } = await mocksOf("mocks.yaml"); + expect(handlers).toContain( + 'http.get(\n new RegExp("/pets:count/?$"),\n', + ); + // The path ends with a slash, so the request has to as well. + expect(handlers).toContain( + String.raw`new RegExp("/files/([^/]+)\\.\\(json\\|yaml\\)/$")`, + ); + }); + + test("a parameter followed by another or by letters is matched by a regular expression", async () => { + const { handlers } = await mocksOf("mocks.yaml"); + // MSW 2 rejects `:name:extension`, and `:majorbeta` would be one name. + expect(handlers).toContain('new RegExp("/archives/([^/]+)([^/]+)/?$")'); + expect(handlers).toContain('new RegExp("/v([^/]+)beta/ping/?$")'); + expect(handlers).not.toContain(":name:extension"); + }); + + test("fixed text is matched as a request carries it", async () => { + const { handlers } = await mocksOf("mocks.yaml"); + expect(handlers).toContain('new RegExp("/caf%C3%A9/([^/]+)/?$")'); + const encoded = await mocksOfDocument({ + paths: { + "/a b/%41%/x^y": { + get: { responses: { 204: { description: "ok" } } }, + }, + "/lone\ud800/surrogate": { + get: { responses: { 204: { description: "ok" } } }, + }, + }, + }); + // What is encoded already stays, and a lone `%` is not encoded again. + // URL parsers differ on `^`, so both spellings match. + expect(encoded.handlers).toContain( + String.raw`new RegExp("/a%20b/%41%/x(?:\\^|%5E)y/?$")`, + ); + expect(encoded.handlers).toContain( + 'new RegExp("/lone%EF%BF%BD/surrogate/?$")', + ); + }); + + test("answers with the lowest successful status", async () => { + const { handlers } = await mocksOf("mocks.yaml"); + expect(handlers).toContain( + "answer(override, mocks.createPetResponseMock, json(201))", + ); + // A range and `default` are answered with 200. + expect(handlers).toContain( + "answer(override, mocks.listMyPetsResponseMock, json(200))", + ); + expect(handlers).toContain( + 'override?: Types.ListAnimalsResponses["default"] | HttpResponseResolver', + ); + }); + + test("a range of statuses comes after the statuses it stands for", async () => { + const { data, handlers } = await mocksOf("mocks.yaml"); + expect(handlers).toContain( + "answer(override, mocks.getRangedResponseMock, json(206))", + ); + expect(data).toContain( + "export function getRangedResponseMock(): Types.GetRangedResponses[206] {", + ); + }); + + test("a body no value can be written for is an empty object", async () => { + const { data } = await mocksOf("mocks.yaml"); + expect(functionBody(data, "getImpossibleResponseMock")).toContain( + "return {} as unknown as Types.GetImpossibleResponses[200];", + ); + }); + + test("answers text as text", async () => { + const { handlers } = await mocksOf("mocks.yaml"); + expect(handlers).toContain( + "answer(override, mocks.getStatusResponseMock, text(200))", + ); + }); + + test("answers without a body where there is none to mock", async () => { + const { data, handlers } = await mocksOf("mocks.yaml"); + for (const [name, call] of [ + ["deletePet", 'http.delete("*/pets/:pet_id", override ?? empty(204))'], + ["headPets", 'http.head("*/pets", override ?? empty(200))'], + ["exportPets", 'http.get("*/export", override ?? empty(200))'], + ["getAnything", 'http.get("*/anything", override ?? empty(200))'], + ["getNothing", 'http.get("*/nothing", override ?? empty(200))'], + ]) { + expect(handlers).toContain( + `export const ${name}Handler = (override?: HttpResponseResolver) =>\n ${call};`, + ); + expect(data).not.toContain(`${name}ResponseMock`); + } + }); + + test("leaves out a method MSW has no handler for, with a warning", async () => { + const { handlers, warnings } = await mocksOf("mocks.yaml"); + expect(handlers).not.toContain("tracePets"); + expect(warnings).toContainEqual( + expect.stringMatching(/no handler[\s\S]*\n {2}- TRACE \/pets$/), + ); + }); + + test("only declares the helpers it uses", async () => { + const { handlers } = await mocksOfDocument({ + paths: { + "/ping": { get: { responses: { 204: { description: "ok" } } } }, + }, + }); + expect(handlers).toContain("const empty ="); + expect(handlers).not.toContain("const answer"); + expect(handlers).not.toContain("const json"); + expect(handlers).not.toContain("import * as mocks"); + expect(handlers).not.toContain("import type * as Types"); + }); + + test("a mock name taken by a schema's mock gets a number", async () => { + const { data, handlers } = await mocksOfDocument({ + paths: { + "/pets": { + get: { + operationId: "listPets", + responses: { + 200: { + description: "ok", + content: { + "application/json": { schema: { type: "string" } }, + }, + }, + }, + }, + }, + }, + components: { schemas: { ListPetsResponse: { type: "string" } } }, + }); + expect(data).toContain("export function listPetsResponseMock(): Types."); + expect(data).toContain("export function listPetsResponseMock2(): Types."); + expect(handlers).toContain("mocks.listPetsResponseMock2"); + }); + }); +}); diff --git a/tests/client/mocksCompile.test.ts b/tests/client/mocksCompile.test.ts new file mode 100644 index 0000000..e355aa3 --- /dev/null +++ b/tests/client/mocksCompile.test.ts @@ -0,0 +1,121 @@ +// The mocks are typed by the generated types, so a value the mock generator +// writes has to be one the type generator accepts. Compile them for every +// specification under tests/inputs, in each mode that changes the types. + +import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import ts from "typescript"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +import type { LimitedUserConfig } from "../../src/cli.mjs"; +import { generate } from "../../src/generate.mjs"; +import { inputPath } from "../utils"; + +const cases: Array<{ + input: string; + name: string; + options?: Partial; +}> = [ + { input: "petstore.yaml", name: "petstore" }, + { input: "features.yaml", name: "features" }, + { input: "hostile-names.yaml", name: "hostile-names" }, + { input: "dates.yaml", name: "dates" }, + { input: "digit-leading.yaml", name: "digit-leading" }, + { input: "string-pagination.yaml", name: "string-pagination" }, + { input: "mocks.yaml", name: "mocks" }, + { + input: "mocks.yaml", + name: "mocks-ts-enums-dates", + options: { enums: "typescript", useDateType: true }, + }, + { + input: "mocks.yaml", + name: "mocks-js-enums", + options: { enums: "javascript" }, + }, + { + input: "features.yaml", + name: "features-ts-enums-dates", + options: { enums: "typescript", useDateType: true }, + }, + { + input: "features.yaml", + name: "features-js-enums", + options: { enums: "javascript" }, + }, + { + input: "dates.yaml", + name: "dates-date-type", + options: { useDateType: true }, + }, + { + // Nothing to mock and no operation: no import may be left unused, in the + // mocks or in the client. + input: + '{"openapi":"3.1.0","info":{"title":"Empty","version":"1"},"paths":{}}', + name: "empty", + }, + { + input: "hostile-names.yaml", + name: "hostile-names-ts-enums", + options: { enums: "typescript", useDateType: true }, + }, +]; + +describe("generated mocks compile", () => { + let dir: string; + beforeAll(async () => { + // Inside the repo so that `msw` resolves. + dir = await mkdtemp(path.join(__dirname, "compile-mocks-")); + }); + afterAll(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + for (const { input, name, options } of cases) { + test(name, async () => { + const output = path.join(dir, name); + await generate( + { + input: input.startsWith("{") ? input : inputPath(input), + output: path.relative(process.cwd(), output), + pageParam: "page", + nextPageParam: "nextPage", + initialPageParam: "1", + mock: "msw", + ...options, + }, + "1.0.0", + { silent: true }, + ); + await writeFile(path.join(output, "package.json"), '{"type":"module"}'); + // The whole output: the mocks import the client, and an empty + // specification must leave nothing unused in any of the three. + const files = (await readdir(output, { recursive: true })).filter( + (file) => file.endsWith(".ts"), + ); + const program = ts.createProgram( + files.map((file) => path.join(output, file)), + { + strict: true, + // An import or a helper the handlers do not use is an error here. + noUnusedLocals: true, + noUnusedParameters: true, + noEmit: true, + skipLibCheck: true, + lib: ["lib.es2022.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"], + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + types: [], + }, + ); + const diagnostics = ts.getPreEmitDiagnostics(program).map((d) => { + const where = d.file + ? `${path.basename(d.file.fileName)}:${d.file.getLineAndCharacterOfPosition(d.start ?? 0).line + 1}` + : ""; + return `${where}: ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`; + }); + expect(diagnostics).toEqual([]); + }, 120_000); + } +}); diff --git a/tests/client/mocksRuntime.test.ts b/tests/client/mocksRuntime.test.ts new file mode 100644 index 0000000..51f16aa --- /dev/null +++ b/tests/client/mocksRuntime.test.ts @@ -0,0 +1,158 @@ +// End to end: generate the client and the mocks, start MSW with the generated +// handlers, and call the API through the generated client. Nothing listens on +// the base URL, so every answer comes from a handler. + +import { rm } from "node:fs/promises"; +import path from "node:path"; +import { HttpResponse } from "msw/http"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, describe, expect, test } from "vitest"; +import { generate } from "../../src/generate.mjs"; +import { inputPath } from "../utils"; + +const outputDir = path.join("tests", "client", "mocks-runtime-outputs"); +const importDir = path.join(__dirname, "mocks-runtime-outputs"); + +// biome-ignore lint/suspicious/noExplicitAny: the modules are generated by the test +type Generated = any; + +describe("generated handlers under MSW", () => { + let sdk: Generated; + let mocks: Generated; + let server: ReturnType; + + beforeAll(async () => { + await generate( + { + input: inputPath("mocks.yaml"), + output: outputDir, + client: "fetch", + pageParam: "page", + nextPageParam: "nextPage", + initialPageParam: "1", + useDateType: true, + mock: "msw", + }, + "0.0.0-test", + { silent: true }, + ); + const { client } = await import( + path.join(importDir, "requests", "client.gen.ts") + ); + client.setConfig({ baseUrl: "https://api.example.test/v1" }); + sdk = await import(path.join(importDir, "requests", "sdk.gen.ts")); + mocks = await import(path.join(importDir, "mocks", "index.ts")); + server = setupServer(...mocks.handlers); + server.listen(); + }, 60_000); + afterEach(() => server.resetHandlers()); + afterAll(async () => { + server?.close(); + await rm(importDir, { recursive: true, force: true }); + }); + + test("answers with the mock of the operation", async () => { + const { data, response } = await sdk.getPet({ path: { "pet-id": "1" } }); + expect(response.status).toBe(200); + expect(data).toEqual(mocks.getPetResponseMock()); + expect(data.name).toBe("Pochi"); + }); + + test("dates travel as text and come back as Date objects", async () => { + const { data } = await sdk.listPets(); + expect(data).toEqual([ + { + id: 7, + name: "Momo", + status: "sold", + bornAt: new Date("2020-05-17T09:00:00Z"), + }, + ]); + }); + + test("a fixed path is not taken for a parameter", async () => { + const { data } = await sdk.listMyPets(); + expect(Array.isArray(data)).toBe(true); + }); + + test("matches a path that has MSW's own syntax in it", async () => { + expect((await sdk.countPets()).data).toBe(3); + // The colon is part of the path and not a parameter: `/pets` is not it. + expect(Array.isArray((await sdk.listPets()).data)).toBe(true); + + const file = await sdk.getFile({ path: { name: "a" } }); + expect(file.request.url).toBe( + "https://api.example.test/v1/files/a.(json|yaml)/", + ); + expect(file.data).toBe("string"); + + const tag = await sdk.getTag({ path: { "1st": "x" } }); + expect(tag.data).toBe("string"); + }); + + test("a parameter followed by text is not taken for the parameter alone", async () => { + const archived = await sdk.archivePet({ path: { "pet-id": "1" } }); + expect(archived.response.status).toBe(202); + }); + + test("matches adjacent parameters, a parameter before letters and encoded text", async () => { + const archive = await sdk.getArchive({ + path: { name: "backup", extension: ".zip" }, + }); + expect(archive.response.status).toBe(200); + expect(archive.data).toBe("string"); + + const ping = await sdk.pingBeta({ path: { major: "2" } }); + expect(ping.request.url).toBe("https://api.example.test/v1/v2beta/ping"); + expect(ping.data).toBe("string"); + + const cafe = await sdk.getCafe({ path: { id: "1" } }); + expect(cafe.request.url).toBe("https://api.example.test/v1/caf%C3%A9/1"); + expect(cafe.data).toBe("string"); + }); + + test("answers with the status of the response", async () => { + const created = await sdk.createPet(); + expect(created.response.status).toBe(201); + expect(created.data.name).toBe("Kuro"); + + const deleted = await sdk.deletePet({ path: { "pet-id": "1" } }); + expect(deleted.response.status).toBe(204); + + const head = await sdk.headPets(); + expect(head.response.status).toBe(200); + }); + + test("answers text as text", async () => { + const { data, response } = await sdk.getStatus(); + expect(response.headers.get("content-type")).toContain("text/plain"); + expect(data).toBe("ok"); + }); + + test("a handler given a body answers with it", async () => { + server.use(mocks.listPetsHandler([])); + expect((await sdk.listPets()).data).toEqual([]); + + server.use(mocks.getPetHandler(mocks.petMock({ name: "Hachi" }))); + const { data } = await sdk.getPet({ path: { "pet-id": "1" } }); + expect(data.name).toBe("Hachi"); + }); + + test("a handler given a resolver lets it answer", async () => { + server.use( + mocks.getPetHandler(({ params }: { params: { pet_id: string } }) => + HttpResponse.json( + { message: `no pet ${params.pet_id}` }, + { status: 404 }, + ), + ), + mocks.deletePetHandler(() => new HttpResponse(null, { status: 409 })), + ); + const found = await sdk.getPet({ path: { "pet-id": "42" } }); + expect(found.response.status).toBe(404); + expect(found.error).toEqual({ message: "no pet 42" }); + + const deleted = await sdk.deletePet({ path: { "pet-id": "1" } }); + expect(deleted.response.status).toBe(409); + }); +}); diff --git a/tests/format.test.ts b/tests/format.test.ts index f40bba9..718b890 100644 --- a/tests/format.test.ts +++ b/tests/format.test.ts @@ -48,6 +48,23 @@ describe("processOutput", () => { ]); }); + test("names what it runs on", async () => { + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + await processOutput({ output: "/tmp/test", format: "biome" }); + await processOutput({ + output: "/tmp/test", + format: "biome", + lint: "eslint", + label: "mocks", + }); + expect(log.mock.calls.map(([message]) => message)).toEqual([ + "✨ Running Biome (Format) on queries", + "✨ Running Biome (Format) on mocks", + "✨ Running ESLint on mocks", + ]); + log.mockRestore(); + }); + test("does nothing without format or lint", async () => { const { sync } = await import("cross-spawn"); await processOutput({ output: "/tmp/test" }); diff --git a/tests/inputs/mocks.yaml b/tests/inputs/mocks.yaml new file mode 100644 index 0000000..a78746a --- /dev/null +++ b/tests/inputs/mocks.yaml @@ -0,0 +1,1080 @@ +openapi: 3.1.0 +info: + title: Mock coverage + version: 1.0.0 +paths: + /pets: + get: + operationId: listPets + responses: + "200": + description: Pets, with an example for the whole body + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Pet" + example: + - id: 7 + name: Momo + status: sold + bornAt: "2020-05-17T09:00:00Z" + post: + operationId: createPet + responses: + "201": + description: Created, with named examples + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + examples: + missing: + $ref: "#/components/examples/Missing" + empty: + summary: An example without a value + kuro: + $ref: "#/components/examples/Kuro" + "202": + description: Accepted + head: + operationId: headPets + responses: + "200": + description: A HEAD response has no body + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + trace: + operationId: tracePets + responses: + "200": + description: MSW has no handler for TRACE + /pets/{pet-id}: + get: + operationId: getPet + parameters: + - name: pet-id + in: path + required: true + schema: + type: string + responses: + "200": + description: An example that is not a value of the schema + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + example: + id: seven + name: Momo + delete: + operationId: deletePet + parameters: + - name: pet-id + in: path + required: true + schema: + type: string + responses: + "204": + description: Deleted + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + /pets/{pet-id}:archive: + delete: + operationId: archivePet + parameters: + - name: pet-id + in: path + required: true + schema: + type: string + responses: + "202": + description: A parameter followed by text is tighter than the parameter alone + /pets/mine: + get: + operationId: listMyPets + responses: + "2XX": + description: A range of statuses + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Pet" + /pets:count: + get: + operationId: countPets + responses: + "200": + description: A colon outside a parameter is not MSW's to read + content: + application/json: + schema: + type: integer + example: 3 + /tags/{1st}/: + get: + operationId: getTag + parameters: + - name: 1st + in: path + required: true + schema: + type: string + responses: + "200": + description: A parameter name MSW would not take, and a trailing slash + content: + application/json: + schema: + type: string + /files/{name}.(json|yaml)/: + get: + operationId: getFile + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + "200": + description: Characters of a regular expression, and a trailing slash + content: + application/json: + schema: + type: string + /archives/{name}{extension}: + get: + operationId: getArchive + parameters: + - name: name + in: path + required: true + schema: + type: string + - name: extension + in: path + required: true + schema: + type: string + responses: + "200": + description: Two parameters with nothing between them + content: + application/json: + schema: + type: string + /v{major}beta/ping: + get: + operationId: pingBeta + parameters: + - name: major + in: path + required: true + schema: + type: string + responses: + "200": + description: A parameter followed by letters + content: + application/json: + schema: + type: string + /café/{id}: + get: + operationId: getCafe + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + "200": + description: Text a URL percent-encodes + content: + application/json: + schema: + type: string + /animals: + get: + operationId: listAnimals + responses: + default: + description: Only a default response + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Animal" + /status: + get: + operationId: getStatus + responses: + "200": + description: Plain text + content: + text/plain: + schema: + type: string + example: ok + /export: + get: + operationId: exportPets + responses: + "200": + description: A file + content: + application/octet-stream: + schema: + type: string + format: binary + /anything: + get: + operationId: getAnything + responses: + "200": + description: A body of any type + content: + application/json: + schema: {} + /nothing: + get: + operationId: getNothing + responses: + "404": + description: No successful response at all + /ranged: + get: + operationId: getRanged + responses: + "2XX": + description: Any other success + content: + application/json: + schema: + type: string + "206": + description: The status that is answered with + content: + application/json: + schema: + type: integer + /impossible: + get: + operationId: getImpossible + responses: + "200": + description: A body no value can be written for + content: + application/json: + schema: + type: object + required: [never] + properties: + never: false + /shapes: + get: + operationId: getShapes + responses: + "200": + description: Every shape of schema a value is made up for + content: + application/json: + schema: + $ref: "#/components/schemas/Shapes" +components: + examples: + Kuro: + value: + id: 8 + name: Kuro + tags: [black, small] + extra: dropped, the type has no such property + schemas: + Pet: + type: object + required: [id, name] + properties: + id: + type: integer + name: + type: string + example: Pochi + status: + $ref: "#/components/schemas/Status" + tags: + type: array + items: + type: string + bornAt: + type: string + format: date-time + secret: + type: string + writeOnly: true + owner: + $ref: "#/components/schemas/Owner" + Status: + type: string + enum: [available, pending, sold] + Priority: + type: integer + enum: [1, 2, 3] + example: 2 + Owner: + type: object + required: [name, pets] + properties: + name: + type: string + pets: + type: array + items: + $ref: "#/components/schemas/Pet" + bestFriend: + $ref: "#/components/schemas/Owner" + partner: + oneOf: + - $ref: "#/components/schemas/Owner" + - type: "null" + Node: + type: object + required: [next] + properties: + next: + $ref: "#/components/schemas/Node" + Ring: + type: array + prefixItems: + - $ref: "#/components/schemas/Ring" + Dangling: + allOf: + - $ref: "#/components/schemas/Missing" + - type: object + properties: + id: + type: integer + Exampled: + type: object + description: Every example here is a value of its schema + properties: + ratio: + type: number + example: 0.5 + fixed: + const: x + example: x + nullableFixed: + const: x + nullable: true + example: null + status: + allOf: + - $ref: "#/components/schemas/Status" + example: pending + noStatus: + allOf: + - $ref: "#/components/schemas/Status" + nullable: true + example: null + maybeText: + type: [string, "null"] + example: null + textOrNumber: + type: [integer, string] + example: text + unknownNull: + example: null + anyItems: + type: array + example: [1, a] + nested: + type: object + properties: + tags: + $ref: "#/components/schemas/Pet/properties/tags" + example: + tags: [a, b] + ClashA: + type: object + properties: + k: + enum: [a] + "odd key": + enum: [a] + a: + type: string + ClashB: + type: object + properties: + b: + type: string + Clash: + description: Optional properties that no value is a value of everywhere + allOf: + - $ref: "#/components/schemas/ClashA" + - $ref: "#/components/schemas/ClashB" + - type: object + required: [id] + properties: + id: + type: integer + k: + enum: [b] + "odd key": + enum: [b] + WithMeta: + type: object + properties: + meta: + type: object + required: [x] + properties: + x: + type: string + secret: + type: string + writeOnly: true + MoreMeta: + allOf: + - $ref: "#/components/schemas/WithMeta" + - type: object + properties: + meta: + type: object + required: [y] + properties: + y: + type: integer + secret: + type: string + writeOnly: true + Maybe: + type: [object, "null"] + required: [self] + properties: + self: + $ref: "#/components/schemas/Maybe" + Animal: + oneOf: + - $ref: "#/components/schemas/Cat" + - $ref: "#/components/schemas/Dog" + discriminator: + propertyName: kind + mapping: + cat: "#/components/schemas/Cat" + dog: "#/components/schemas/Dog" + Cat: + type: object + required: [kind, lives] + properties: + kind: + type: string + lives: + type: integer + minimum: 9 + Dog: + type: object + required: [kind] + properties: + kind: + type: string + goodBoy: + type: boolean + Vehicle: + type: object + required: [type] + discriminator: + propertyName: type + properties: + type: + type: string + wheels: + type: integer + default: 4 + Car: + allOf: + - $ref: "#/components/schemas/Vehicle" + - type: object + properties: + doors: + type: integer + maximum: 0 + SportsCar: + allOf: + - $ref: "#/components/schemas/Car" + - required: [doors] + - type: object + properties: + turbo: + type: boolean + Settings: + type: object + example: + theme: dark + limits: + daily: 10 + flags: + beta: true + point: [1, two] + pair: [1, 2] + anything: + nested: [1, null] + properties: + theme: + enum: [light, dark] + limits: + type: object + additionalProperties: + type: integer + flags: + type: object + additionalProperties: true + properties: + beta: + type: boolean + point: + type: array + prefixItems: + - type: integer + - type: string + pair: + type: array + minItems: 2 + maxItems: 2 + items: + type: integer + anything: {} + Drifted: + type: object + description: Every example here is not a value of its schema + properties: + number: + type: integer + example: 1.5 + text: + type: string + example: 5 + flag: + type: boolean + example: "yes" + choice: + enum: [a, b] + example: c + fixed: + const: x + example: y + list: + type: array + items: + type: integer + example: [1, two] + notList: + type: array + items: + type: integer + example: 1 + short: + type: array + prefixItems: + - type: integer + - type: integer + example: [1] + long: + type: array + prefixItems: + - type: integer + items: false + example: [1, 2] + sized: + type: array + minItems: 2 + maxItems: 2 + items: + type: integer + example: [1] + object: + type: object + required: [id] + properties: + id: + type: integer + example: + name: no id + notObject: + type: object + properties: + id: + type: integer + example: [1] + nulled: + type: string + example: null + typedExtra: + type: object + additionalProperties: + type: integer + example: + a: one + when: + type: string + format: date-time + example: not a date + file: + type: string + format: binary + example: bytes + union: + oneOf: + - type: string + - type: integer + example: 1 + merged: + allOf: + - type: object + properties: + a: + type: string + - type: object + properties: + b: + type: string + example: + a: x + closed: + type: object + additionalProperties: false + example: + a: 1 + nullType: + type: "null" + example: 1 + referenced: + $ref: "#/components/schemas/Status" + example: other + nullableRef: + allOf: + - $ref: "#/components/schemas/Status" + example: null + picture: + contentMediaType: image/png + example: bytes + noItems: + type: array + items: false + example: [1] + siblings: + type: object + properties: + dog: + $ref: "#/components/schemas/Dog" + properties: + name: + type: string + example: + dog: + kind: shiba + missing: + type: object + properties: + gone: + $ref: "#/components/schemas/Missing" + example: + gone: 1 + fixedNull: + const: x + example: null + Shapes: + type: object + properties: + date: + type: string + format: date + uuid: + type: string + format: uuid + email: + type: string + format: email + short: + type: string + maxLength: 3 + long: + type: string + minLength: 8 + atLeast: + type: integer + minimum: 5 + above: + type: number + exclusiveMinimum: 5 + aboveFlag: + type: number + minimum: 5 + exclusiveMinimum: true + atMost: + type: integer + maximum: -3 + below: + type: number + exclusiveMaximum: 0 + belowFlag: + type: number + maximum: 0 + exclusiveMaximum: true + even: + type: integer + minimum: 3 + multipleOf: 2 + flag: + type: boolean + nothing: + type: "null" + fixed: + const: fixed + fixedObject: + const: + a: [1, 2] + choice: + enum: [null, a] + impossible: + enum: [] + never: false + nullableNever: + type: [string, "null"] + allOf: + - false + defaulted: + type: integer + default: 20 + firstExample: + type: string + examples: [first, second] + severalTypes: + type: [string, integer] + onlyNull: + type: ["null"] + untyped: + properties: + a: + type: string + untypedList: + items: + type: string + blob: + contentMediaType: image/png + file: + type: string + format: binary + three: + type: array + minItems: 3 + items: + type: string + none: + type: array + maxItems: 0 + items: + type: string + anyItems: + type: array + pair: + type: array + minItems: 2 + maxItems: 2 + items: + type: integer + tuple: + type: array + prefixItems: + - type: string + - $ref: "#/components/schemas/Status" + dictionary: + type: object + additionalProperties: + type: string + nullableStatus: + allOf: + - $ref: "#/components/schemas/Status" + nullable: true + narrowed: + allOf: + - maxLength: 3 + - type: string + withSiblings: + $ref: "#/components/schemas/Dog" + properties: + name: + type: string + anything: true + aliasWithNothing: + allOf: + - $ref: "#/components/schemas/Dog" + - type: object + aliasOrAnything: + allOf: + - $ref: "#/components/schemas/Dog" + oneOf: + - {} + taggedWithMore: + oneOf: + - $ref: "#/components/schemas/Cat" + discriminator: + propertyName: kind + mapping: + cat: "#/components/schemas/Cat" + properties: + more: + type: string + noMember: + oneOf: + - enum: [] + ownNever: + oneOf: + - type: object + required: [never] + properties: + never: false + onlyDocumented: + allOf: + - description: Says nothing about the type + twice: + allOf: + - type: string + - type: string + minLength: 1 + noType: + type: [object] + required: [never] + properties: + never: false + halfOpen: + type: number + minimum: 0 + exclusiveMaximum: 0.5 + negativeEven: + type: integer + minimum: -5 + maximum: -3 + multipleOf: 2 + tenths: + type: number + multipleOf: 0.1 + maximum: 0.35 + openSteps: + type: integer + exclusiveMinimum: 2 + exclusiveMaximum: 4 + openStepsBelow: + type: integer + exclusiveMaximum: -2 + noMultiple: + type: integer + minimum: 3 + maximum: 3.5 + multipleOf: 2 + between: + type: number + minimum: 2 + maximum: 3 + betweenOpen: + type: number + minimum: 2 + exclusiveMinimum: true + maximum: 3 + looserExclusive: + type: number + minimum: 5 + exclusiveMinimum: 3 + maximum: 9 + exclusiveMaximum: 12 + wholeOfFraction: + type: integer + multipleOf: 0.3 + minimum: 1 + maximum: 4 + smallFraction: + type: integer + multipleOf: 0.0003 + minimum: 1 + maximum: 4 + farWholeMultiple: + type: integer + multipleOf: 3.14159265 + exponentFraction: + type: integer + multipleOf: 2.5e-7 + tinyFraction: + type: integer + multipleOf: 3.0e-21 + minimum: 1 + maximum: 4 + everyInteger: + type: integer + multipleOf: 1.0e-300 + noWholeMultiple: + type: integer + multipleOf: 1.2345678901234567 + noWholeMultipleAboveZero: + type: integer + multipleOf: 1.2345678901234567 + minimum: 2 + betweenFractions: + type: integer + exclusiveMinimum: 1000000000.75 + exclusiveMaximum: 1000000001.25 + betweenFractionsOfTenths: + type: number + multipleOf: 0.1 + exclusiveMinimum: 100000000.04 + exclusiveMaximum: 100000000.16 + bigTenths: + type: number + multipleOf: 0.1 + minimum: 170000000000.1 + maximum: 170000000000.1 + bigInteger: + type: integer + minimum: 1700000000001 + maximum: 1700000000001 + clash: + $ref: "#/components/schemas/Clash" + requiredClash: + allOf: + - type: object + required: [k] + properties: + k: + enum: [a] + - type: object + properties: + k: + enum: [b] + overlap: + allOf: + - type: object + properties: + a: + type: object + required: [x] + properties: + x: + type: string + - type: object + properties: + a: + type: object + required: [y] + properties: + y: + type: integer + conflicting: + allOf: + - type: object + properties: + k: + enum: [a] + - type: object + properties: + k: + enum: [b] + moreMeta: + $ref: "#/components/schemas/MoreMeta" + petPlus: + allOf: + - $ref: "#/components/schemas/Dog" + - $ref: "#/components/schemas/Dog" + - type: object + properties: + extra: + type: string + stringAndOk: + allOf: + - type: string + - enum: [ok] + okAndString: + allOf: + - enum: [nope, ok] + - type: string + enum: [ok] + stringAndNumber: + allOf: + - type: string + - type: number + numberOfEither: + allOf: + - type: [string, number] + - type: number + nullOfBoth: + allOf: + - type: [string, "null"] + - type: [number, "null"] + numberOfNeither: + allOf: + - type: [string, number] + - type: [number, boolean] + noCommon: + allOf: + - enum: [a] + - enum: [b] + statusAndSold: + allOf: + - $ref: "#/components/schemas/Status" + - enum: [sold] + statusAndText: + allOf: + - $ref: "#/components/schemas/Status" + - type: string + statusAndPriority: + allOf: + - $ref: "#/components/schemas/Status" + - $ref: "#/components/schemas/Priority" + wrapperRequired: + allOf: + - $ref: "#/components/schemas/Dog" + required: [goodBoy] + example: + kind: shiba + oneOfPrimitives: + anyOf: + - type: integer + - type: string + animal: + $ref: "#/components/schemas/Animal" + car: + $ref: "#/components/schemas/SportsCar" + missing: + $ref: "#/components/schemas/Missing" + inlined: + $ref: "#/components/schemas/Pet/properties/tags" + loop: + $ref: "#/components/schemas/Shapes/properties/loop" + priority: + $ref: "#/components/schemas/Priority" + __proto__: + type: string + "odd key": + type: string + requiredLoop: + type: object + properties: + node: + $ref: "#/components/schemas/Node" + writeOnly: + type: string + writeOnly: true + readOnly: + type: string + readOnly: true diff --git a/tests/mockOption.test.ts b/tests/mockOption.test.ts new file mode 100644 index 0000000..e2f87d7 --- /dev/null +++ b/tests/mockOption.test.ts @@ -0,0 +1,192 @@ +// `--mock`, from the options down: the version of MSW the project has, the +// files written, and `--check` over them. + +import { + appendFile, + mkdir, + mkdtemp, + readFile, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + test, + vi, +} from "vitest"; +import { check } from "../src/check.mjs"; +import type { LimitedUserConfig } from "../src/cli.mjs"; +import { detectMswMajor } from "../src/client/index.mjs"; +import { generate } from "../src/generate.mjs"; +import { inputPath } from "./utils"; + +/** A project directory outside the repo, with the given MSW installed. */ +async function projectWithMsw(version?: string) { + const dir = await mkdtemp(path.join(tmpdir(), "orqc-msw-")); + if (version !== undefined) { + const msw = path.join(dir, "node_modules", "msw"); + await mkdir(msw, { recursive: true }); + await writeFile( + path.join(msw, "package.json"), + JSON.stringify({ name: "msw", version }), + ); + } + return dir; +} + +const dirs: string[] = []; +async function project(version?: string) { + const dir = await projectWithMsw(version); + dirs.push(dir); + return dir; +} +afterAll(async () => { + await Promise.all( + dirs.map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); + +describe("detectMswMajor", () => { + test("reads the installed version", async () => { + expect(detectMswMajor(await project("3.0.4"))).toEqual({ major: 3 }); + expect(detectMswMajor(await project("2.15.0"))).toEqual({ major: 2 }); + // A later major is taken to keep the entry points of version 3. + expect(detectMswMajor(await project("4.1.0"))).toEqual({ major: 3 }); + }); + + test("is version 3 when MSW is not installed", async () => { + expect(detectMswMajor(await project())).toEqual({ major: 3 }); + }); + + test("finds the repo's own MSW from a directory inside it", () => { + expect(detectMswMajor(process.cwd())).toEqual({ major: 3 }); + }); + + test("warns about a version the handlers cannot run on", async () => { + const detected = detectMswMajor(await project("1.3.5")); + expect(detected.major).toBe(2); + expect(detected.warning).toContain("MSW 2 or later"); + expect(detected.warning).toContain("1.3.5"); + }); +}); + +describe("generate with --mock", () => { + const options = (output: string): LimitedUserConfig => ({ + input: inputPath("mocks.yaml"), + output, + pageParam: "page", + nextPageParam: "nextPage", + initialPageParam: "1", + mock: "msw", + }); + + afterEach(() => vi.restoreAllMocks()); + + test("writes the handlers for the MSW of the project, and its warnings", async () => { + const dir = await project("1.3.5"); + vi.spyOn(process, "cwd").mockReturnValue(dir); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + await generate(options(path.join(dir, "openapi")), "1.0.0"); + + const handlers = await readFile( + path.join(dir, "openapi", "mocks", "handlers.ts"), + "utf-8", + ); + expect(handlers).toContain('} from "msw";'); + const warnings = warn.mock.calls.map(([message]) => String(message)); + expect(warnings[0]).toContain("MSW 2 or later"); + expect(warnings).toContainEqual(expect.stringContaining("TRACE /pets")); + }); + + test("says nothing when silent", async () => { + const dir = await project("1.3.5"); + vi.spyOn(process, "cwd").mockReturnValue(dir); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + await generate(options(path.join(dir, "openapi")), "1.0.0", { + silent: true, + }); + expect(warn).not.toHaveBeenCalled(); + }); + + test("writes no mocks directory without the option", async () => { + const dir = await project(); + const output = path.join(dir, "openapi"); + await generate({ ...options(output), mock: undefined }, "1.0.0", { + silent: true, + }); + await expect( + readFile(path.join(output, "mocks", "index.ts")), + ).rejects.toThrow(); + }); + + test("formats and lints the mocks with the queries", async () => { + const dir = await project(); + const output = path.join(dir, "openapi"); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + await generate( + { ...options(output), format: "biome", lint: "biome" }, + "1.0.0", + { silent: true }, + ); + const messages = log.mock.calls.map(([message]) => String(message)); + expect(messages).toContainEqual(expect.stringContaining("on queries")); + expect(messages).toContainEqual( + expect.stringContaining("Biome (Format) on mocks"), + ); + expect(messages).toContainEqual( + expect.stringContaining("Biome (Lint) on mocks"), + ); + }); +}); + +describe("check with --mock", () => { + const output = path.join("tests", "outputs-check-mocks"); + const options: LimitedUserConfig = { + input: inputPath("petstore.yaml"), + output, + pageParam: "page", + nextPageParam: "nextPage", + initialPageParam: "1", + mock: "msw", + }; + + beforeAll(async () => { + await generate({ ...options }, "1.0.0", { silent: true }); + }, 60_000); + afterAll(async () => { + await rm(output, { recursive: true, force: true }); + }); + + test("the mocks are part of what is checked", async () => { + expect(await check({ ...options }, "1.0.0")).toEqual({ + upToDate: true, + files: [], + }); + + const handlers = path.join(output, "mocks", "handlers.ts"); + const original = await readFile(handlers, "utf-8"); + await appendFile(handlers, "// edited\n"); + try { + expect((await check({ ...options }, "1.0.0")).files).toEqual([ + { + path: "tests/outputs-check-mocks/mocks/handlers.ts", + status: "modified", + }, + ]); + } finally { + await writeFile(handlers, original); + } + }); + + test("without the option a mocks directory is not the generator's", async () => { + const result = await check({ ...options, mock: undefined }, "1.0.0"); + expect(result).toEqual({ upToDate: true, files: [] }); + }); +}); diff --git a/tests/runCli.test.ts b/tests/runCli.test.ts index de76a11..c992af7 100644 --- a/tests/runCli.test.ts +++ b/tests/runCli.test.ts @@ -87,6 +87,21 @@ describe("runCli", () => { ); }); + test("--mock takes the mocking library", async () => { + const cli = setup(); + expect(await cli.run("-i", "spec.yaml", "--mock", "msw")).toBe(0); + expect(cli.dependencies.generate).toHaveBeenCalledWith( + expect.objectContaining({ mock: "msw" }), + "9.9.9", + { silent: false }, + ); + + const unknown = setup(); + expect(await unknown.run("-i", "spec.yaml", "--mock", "nock")).toBe(2); + expect(unknown.stderr()).toContain("--mock"); + expect(unknown.dependencies.generate).not.toHaveBeenCalled(); + }); + test("does not silence the generator in the default mode", async () => { const cli = setup(); expect(await cli.run("-i", "spec.yaml")).toBe(0);